From 541a172bd26df693777981c15ef6918f27e6adac Mon Sep 17 00:00:00 2001 From: "Xunnamius (Romulus)" Date: Fri, 28 Aug 2020 19:39:17 -0700 Subject: [PATCH] updated README --- README.md | 94 ++++++++++++++++++++++- external-scripts/ban-hammer.ts | 17 ++-- external-scripts/bin/ban-hammer.js | 30 +++++++- external-scripts/bin/generate-flights.js | 10 +-- external-scripts/bin/prune-logs.js | 30 +++++++- external-scripts/generate-flights.ts | 3 +- external-scripts/prune-logs.ts | 4 +- markov-arrivals.png | Bin 0 -> 36992 bytes markov-departures.png | Bin 0 -> 43820 bytes tsconfig.json | 2 + 10 files changed, 169 insertions(+), 21 deletions(-) create mode 100644 markov-arrivals.png create mode 100644 markov-departures.png diff --git a/README.md b/README.md index 5553511..87f0bee 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,94 @@ node external-scripts/bin/script-name.js ### Stochastic flight states -Or: *how are flights' gates and statuses changing automatically in the db?* - -(explain how it works) (include drawn image/graphic) +Or: *how are flight gates and statuses changing automatically in the db?* + +Flights are generated between 1 and 30 days in advance of their arrival time +(i.e. `arriveAtReceiver`). When a flight is generated, every single state it +will enter into, from being cancelled to being delayed to arriving to boarding, +is also generated using a [Markov +process](https://en.wikipedia.org/wiki/Markov_chain) depending on its `type`. +Afterwards, using an aggregation pipeline, one of these states is selected +everytime an API request is made. The state that gets selected depends on the +time the request is received. This means flight data isn't actually "changing" +"randomly" (i.e. stochastically) in the database, it only looks that way. + +These states, made up of `arriveAtReceiver`, `gate`, `status`, and +`departFromReceiver`, are generated and stored according to the following rules: + +All flights start off with status *scheduled* (**A**), meaning they are scheduled to arrive at their +`landingAt` airport (at `arriveAtReceiver` time) coming in from their +`comingFrom` airport (at `departFromSender` time). Once `departFromSender` time +elapses, there's an 80% chance the flight status becomes *on time* (**B**) and a 20% chance the flight status +becomes *cancelled* (**C**). Once a +flight is cancelled, it no longer changes states in the system. + +At some point before `arriveAtReceiver` but after `departFromSender`, there is a +20% chance the flight status becomes *delayed* (**D**), pushing `arriveAtReceiver` back by 15 minutes. +Between 15 minutes and 2 hours before `arriveAtReceiver` elapses (but after the +flight is or isn't delayed), the flight's arrival gate is chosen and visible in +the API (**E**). + +After the flight's arrival gate is chosen, between 5 and 30 minutes before +`arriveAtReceiver`, the flight's status becomes *landed* (**F**). Immediately, there's a 50% chance *the gate changes* (**G**). + +Once `arriveAtReceiver` elapses, the flight's status becomes *arrived* (**H**). Immediately, there is a 15% chance +*the gate changes* (**I**). + +*** + +If the flight is an **arrival** (`type` is `arrival`), upon the next hour, the +flight's status becomes *past* +(**J**) and no longer changes states in the system. + +![The Markov model describing how flight states update](markov-arrivals.png +"Stochastic state flight update markov chain for arrivals") + +*** + +If, on the other hand, the flight is a **departure** (`type` is `departure`), +between 3 and 10 minutes after the flight's status becomes `arrived`, the +flight's status becomes *boarding* +(**J**). + +Once `departFromReceiver` elapses, the flight's status becomes *boarding* (**K**). 2 to 5 hours after +that, the flight's status becomes *past* +(**L**) and no longer changes states in the system. + +![The Markov model describing how flight states update](markov-departures.png +"Stochastic state flight update markov chain for departures") + +#### Are gates and flight numbers unique? + +Gates and flight numbers are unique **but only per airport per hour**. Hence, +two or more flights in the same several-hour span might have the same flight +number or land at the same gate at the same airport, but never within the same +hour. + +#### Why does the API respond so slowly? + +The API responds slowly for certain queries due to how each flight's stochastic +states are stored. Since they're nested within the rest of the flight data +(under the `stochasticStates` field) and the correct state is selected through +an [aggregation +pipeline](https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline), +[the current state of the flight is not +indexable](https://docs.mongodb.com/manual/core/aggregation-pipeline/#pipeline-operators-and-indexes). +Not being able to generate indices on the stochastic state fields slows down +searches involving those fields (like `arriveAtReceiver`, `status`, and `gate`) +by an order of magnitude. + +The obvious solution is to break the stochastic states out into their own +collection and index them there; however, we decided to leave the stochastic +states nested within each flight document since it made it easy for the judges +to see [how apps behave while waiting several seconds for a +response](https://reactjs.org/docs/concurrent-mode-suspense.html). + +tl;dr "It's a feature, not a bug!" diff --git a/external-scripts/ban-hammer.ts b/external-scripts/ban-hammer.ts index 818b32a..1fb25fe 100644 --- a/external-scripts/ban-hammer.ts +++ b/external-scripts/ban-hammer.ts @@ -1,3 +1,5 @@ +import { getEnv } from 'universe/backend/env' + const oneSecond = 1000; const scheduledToRepeatEvery = oneSecond * 60; // * seconds @@ -166,11 +168,12 @@ const pipeline = [ ]; exports = function() { - return context.services.get('neptune-1') - .db('hscc-api-airports') - .collection('request-log') - .aggregate(pipeline) - .next() - // eslint-disable-next-line no-console - .catch(e => console.error('Error: ', e)); + getEnv(); + // return context.services.get('neptune-1') + // .db('hscc-api-airports') + // .collection('request-log') + // .aggregate(pipeline) + // .next() + // // eslint-disable-next-line no-console + // .catch(e => console.error('Error: ', e)); }; diff --git a/external-scripts/bin/ban-hammer.js b/external-scripts/bin/ban-hammer.js index 5e070cf..2df9e50 100644 --- a/external-scripts/bin/ban-hammer.js +++ b/external-scripts/bin/ban-hammer.js @@ -1 +1,29 @@ -!function(e){var t={};function o(n){if(t[n])return t[n].exports;var $=t[n]={i:n,l:!1,exports:{}};return e[n].call($.exports,$,$.exports,o),$.l=!0,$.exports}o.m=e,o.c=t,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var $ in e)o.d(n,$,function(t){return e[t]}.bind(null,$));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=131)}({131:function(e,t){const o=[{$limit:1},{$project:{_id:1}},{$project:{_id:0}},{$lookup:{from:"request-log",as:"keyBased",pipeline:[{$match:{key:{$ne:null},$expr:{$gte:["$time",{$subtract:[{$toLong:"$$NOW"},6e4]}]}}},{$group:{_id:{key:"$key",interval:{$subtract:["$time",{$mod:["$time",1e3]}]}},count:{$sum:1}}},{$match:{count:{$gt:10}}},{$project:{key:"$_id.key",until:{$add:[{$toLong:"$$NOW"},9e5]}}},{$project:{_id:0,count:0}}]}},{$lookup:{from:"request-log",as:"ipBased",pipeline:[{$match:{$expr:{$gte:["$time",{$subtract:[{$toLong:"$$NOW"},6e4]}]}}},{$group:{_id:{ip:"$ip",interval:{$subtract:["$time",{$mod:["$time",1e3]}]}},count:{$sum:1}}},{$match:{count:{$gt:10}}},{$project:{ip:"$_id.ip",until:{$add:[{$toLong:"$$NOW"},9e5]}}},{$project:{_id:0,count:0}}]}},{$lookup:{from:"limited-log-mview",as:"previous",pipeline:[{$match:{$expr:{$gte:["$until",{$subtract:[{$toLong:"$$NOW"},18e5]}]}}},{$project:{_id:0}}]}},{$project:{union:{$concatArrays:["$keyBased","$ipBased","$previous"]}}},{$unwind:{path:"$union"}},{$replaceRoot:{newRoot:"$union"}},{$group:{_id:{ip:"$ip",key:"$key"},count:{$sum:1},until:{$first:"$until"}}},{$set:{until:{$cond:{if:{$ne:["$count",1]},then:{$add:[{$toLong:"$$NOW"},36e5]},else:"$until"}},ip:"$_id.ip",key:"$_id.key"}},{$project:{count:0,_id:0}},{$out:"limited-log-mview"}]}}); \ No newline at end of file +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=234)}([function(e,t,n){"use strict";const r=n(2).MongoError,o=n(29);var s=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},i=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;nprocess.emitWarning(e,"DeprecationWarning"):e=>console.error(e);function l(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(92),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class h{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new h(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new h(e.substring(0,t),e.substring(t+1))}}function f(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],s=0;s{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const s=e.s.promiseLibrary;let i,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),i=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:i})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(i&&i.owner===c&&!o.returnsCursor)i.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new s((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,s=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const i=o.fromOptions(n);return i?Object.assign(e,{writeConcern:i}):s&&s.writeConcern?Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const s=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!s||!s.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:l,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(o.hasOwnProperty(t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(u(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:h,emitDeprecationWarning:u,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:f,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=f()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,s=!1;const i=(t=t||{}).interval||1e3,a=t.minInterval||500;function c(e){s||(clearTimeout(n),n=setTimeout(u,e||i))}function u(){o=0,r=f(),e(e=>{if(e)throw e;c(i)})}return"boolean"==typeof t.immediate&&t.immediate?u():(r=f(),c()),{wake:function(){const e=f(),t=e-o,n=e-r,s=Math.max(i-n,0);o=e,ta&&c(a)},stop:function(){s=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){if(Array.isArray(t))return t.reduce((t,n)=>t||e(n),null);const n=Object.keys(t);return n.length>0&&"$"===n[0][0]}}},function(e,t,n){"use strict";let r=n(88);const o=n(72),s=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(2).MongoError,MongoNetworkError:n(2).MongoNetworkError,MongoParseError:n(2).MongoParseError,MongoTimeoutError:n(2).MongoTimeoutError,MongoServerSelectionError:n(2).MongoServerSelectionError,MongoWriteConcernError:n(2).MongoWriteConcernError,Connection:n(90),Server:n(75),ReplSet:n(160),Mongos:n(162),Logger:n(19),Cursor:n(20).CoreCursor,ReadPreference:n(13),Sessions:n(31),BSON:r,EJSON:s,Topology:n(163).Topology,Query:n(22).Query,MongoCredentials:n(101).MongoCredentials,defaultAuthProviders:n(96).defaultAuthProviders,MongoCR:n(97),X509:n(98),Plain:n(99),GSSAPI:n(100),ScramSHA1:n(58).ScramSHA1,ScramSHA256:n(58).ScramSHA256,parseConnectionString:n(179)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const s=Symbol("beforeHandshake");class i extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[s]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),p=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const h=new Set([91,189,11600,11602,13436]),f=new Set([10107,13435]),d=new Set([11600,91]);function m(e){return!(!e.code||!h.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:i,MongoNetworkTimeoutError:class extends i{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof i||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&f.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&d.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?p.has(e.code)||p.has(e.result.code):p.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[s]}}},function(e,t,n){"use strict";const r={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS")};e.exports={Aspect:r,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){this.options=Object.assign({},e)}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";const r=n(143),o=n(21),s=n(72);const i=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=null;try{e=s("mongodb-extjson")}catch(e){}return e||(e={parse:i,deserialize:i,serialize:i,stringify:i,setBSONModule:i,BSON:i}),e},retrieveKerberos:function(){let e;try{e=s("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;re===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(144).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"d",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"a",(function(){return c})),n.d(t,"f",(function(){return u}));class r extends Error{}class o extends r{constructor(e,t){super(`${e}${t=t?": "+t:""}`)}}class s extends o{constructor(e){super(s.name,e)}}class i extends o{constructor(e){super(i.name,e||"data upsert failed")}}class a extends o{constructor(e){super(a.name,e?`expected valid ObjectId instance, got "${e}" instead`:"invalid ObjectId encountered")}}class c extends o{constructor(){super(c.name,"invalid API key encountered")}}class u extends o{constructor(e){super(u.name,null!=e?e:"validation failed")}}},function(e,t,n){"use strict";const r=n(13),o=n(2).MongoError,s=n(15).ServerType,i=n(91).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===s.Mongos)return!0;if(e.description&&e.description instanceof i){return Array.from(e.description.servers.values()).some(e=>e.type===s.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";e.exports=(e,t)=>{if(void 0===t&&(t=e,e=0),"number"!=typeof e||"number"!=typeof t)throw new TypeError("Expected all arguments to be numbers");return Math.floor(Math.random()*(t-e+1)+e)}},function(e,t,n){"use strict";const r=n(13),o=n(15).TopologyType,s=n(2).MongoError,i=n(2).isRetryableWriteError,a=n(4).maxWireVersion,c=n(2).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},p=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},h=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},f=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},d=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:s,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var s=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name}),function(e,t,n){var r=f(e,t);return f(e,n)!==r}(e,e.s.ismaster,o.result)&&p(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?f(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=s}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(d(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function y(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const g=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&y(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},inquireServerState:d,getTopologyType:f,emitServerDescriptionChanged:p,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:h(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:g,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new s({message:b,errmsg:b,originalError:e}):e},topologyType:y,legacyIsRetryableWriteError:function(e,t){return e instanceof s&&(g(t)&&(e instanceof c||a(t)<9&&i(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(72);function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){var e=n(88);e.native=!1;try{var t=r("bson-ext");if(t)return t.native=!0,t}catch(e){}return e},retrieveSnappy:function(){var e=null;try{e=r("snappy")}catch(e){}return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).MongoError,p=n(1).ReadPreference,h=n(0).toError,f=n(20).CursorState;function d(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),s(u,e,e.cmd)):s(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),i(u,e),u},deleteCallback:function(e,t,n){if(null!=n){if(e&&n)return n(e);if(null==t)return n(null,{result:{ok:1}});t.deletedCount=t.result.n,n&&n(null,t)}},findAndModify:function(e,t,n,i,l,h){const f={findAndModify:e.collectionName,query:t};(n=c(n))&&(f.sort=n),f.new=!!l.new,f.remove=!!l.remove,f.upsert=!!l.upsert;const d=l.projection||l.fields;d&&(f.fields=d),l.arrayFilters&&(f.arrayFilters=l.arrayFilters,delete l.arrayFilters),i&&!l.remove&&(f.update=i),l.maxTimeMS&&(f.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(f.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(f.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=p.primary;try{s(f,e,m)}catch(e){return h(e,null)}a(e.s.db,f,m,(e,t)=>e?u(h,e,null):u(h,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(h(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n{if(e.s.state=f.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:d,insertDocuments:function(e,t,n,s){"function"==typeof n&&(s=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},n);i=r(i,e.s.db),i=o(i,{db:e.s.db,collection:e},n),!0===i.keepGoing&&(i.ordered=!1),i.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=d(e,t,n),e.s.topology.insert(e.s.namespace,t,i,(e,n)=>{if(null!=s){if(e)return u(s,e);if(null==n)return u(s,null,null);if(n.result.code)return u(s,h(n.result));if(n.result.writeErrors)return u(s,h(n.result.writeErrors[0]));n.ops=t,u(s,null,n)}})},removeDocuments:function(e,t,n,i){"function"==typeof n?(i=n,n={}):"function"==typeof t&&(i=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{s(a,e,n)}catch(e){return i(e,null)}e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=i)return e?u(i,e,null):null==t?u(i,null,null):t.result.code?u(i,h(t.result)):t.result.writeErrors?u(i,h(t.result.writeErrors[0])):void u(i,null,t)})},updateDocuments:function(e,t,n,i,a){if("function"==typeof i&&(a=i,i=null),null==i&&(i={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(h("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(h("document must be a valid JavaScript object"));let c=Object.assign({},i);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},i),c.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const l={q:t,u:n};l.upsert=void 0!==i.upsert&&!!i.upsert,l.multi=void 0!==i.multi&&!!i.multi,i.hint&&(l.hint=i.hint),c.arrayFilters&&(l.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&l.multi&&(c.retryWrites=!1);try{s(c,e,i)}catch(e){return a(e,null)}e.s.topology.update(e.s.namespace,[l],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,h(t.result)):t.result.writeErrors?u(a,h(t.result.writeErrors[0])):void u(a,null,t)})},updateCallback:function(e,t,n){if(null!=n){if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}}}},function(e,t,n){"use strict";const r=function(e,t,n){if(!r.isValid(e))throw new TypeError("Invalid read preference mode "+e);if(t&&!Array.isArray(t)){console.warn("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,r=void 0!==t.hedge;e||r?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===r.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(r.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),r.PRIMARY="primary",r.PRIMARY_PREFERRED="primaryPreferred",r.SECONDARY="secondary",r.SECONDARY_PREFERRED="secondaryPreferred",r.NEAREST="nearest";const o=[r.PRIMARY,r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST,null];r.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,o=e.maxStalenessSeconds;if("string"==typeof t)return new r(t,n);if(!(t instanceof r)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new r(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||o,hedge:t.hedge})}return t},r.resolve=function(e,t){const n=(t=t||{}).session,o=e&&e.readPreference;let s;return s=t.readPreference?r.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=o?o:r.primary,"string"==typeof s?new r(s):s},r.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new r(t);else if(!t||t instanceof r||"object"!=typeof t){if(!(t instanceof r))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new r(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},r.isValid=function(e){return-1!==o.indexOf(e)},r.prototype.isValid=function(e){return r.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];r.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},r.prototype.equals=function(e){return e.mode===this.mode},r.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},r.primary=new r("primary"),r.primaryPreferred=new r("primaryPreferred"),r.secondary=new r("secondary"),r.secondaryPreferred=new r("secondaryPreferred"),r.nearest=new r("nearest"),e.exports=r},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).debugOptions,i=n(0).handleCallback,a=n(1).MongoError,c=n(0).parseIndexOptions,u=n(1).ReadPreference,l=n(0).toError,p=n(80),h=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function d(e,t,n,o,s){let h=Object.assign({},{readPreference:u.PRIMARY},o);if(h=r(h,{db:e},o),h.writeConcern&&"function"!=typeof s)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));!function(e,t,n,o,s){const p=c(n),h="string"==typeof o.name?o.name:p.name,f=[{name:h,key:p.fieldHash}],d=Object.keys(f[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===d.indexOf(e)&&(f[0][e]=o[e]);const y=e.s.topology.capabilities();if(f[0].collation&&y&&!y.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,s(e)}const g=r({createIndexes:t,indexes:f},{db:e},o);o.readPreference=u.PRIMARY,m(e,g,o,(e,t)=>e?i(s,e,null):0===t.ok?i(s,l(t),null):void i(s,null,h))}(e,t,n,h,(r,c)=>{if(null==r)return i(s,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return i(s,r,c);const u=g(e,t,n,o);h.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(p.SYSTEM_INDEX_COLLECTION),u,h,(e,t)=>{if(null!=s)return e?i(s,e):null==t?i(s,null,null):t.result.writeErrors?i(s,a.create(t.result.writeErrors[0]),null):void i(s,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(s(f,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?i(r,e):n.full?i(r,null,t):void i(r,null,t.result))}function y(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?i(r,null,t):void i(r,null,function(e){let t={};for(let n=0;n0){n.emit(t,r,e);for(let n=0;n{if(null!=r&&26!==r.code)return i(s,r,null);if(null!=a&&a[l]){if("function"==typeof s)return i(s,null,l)}else d(e,t,n,o,s)})},evaluate:function(e,t,n,r,s){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let p={$eval:c,args:l};r.nolock&&(p.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,p,r,(e,t)=>e?i(s,e,null):t&&1===t.ok?i(s,null,t.retval):t?i(s,a.create({message:"eval failed: "+t.errmsg,driver:!0}),null):void i(s,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new h("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?i(r,t):void i(r,null,n.result))},indexInformation:y,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n"undefined"==typeof window,i=n(69),a=n(6);function c(e=!1){const t={NODE_ENV:"development",MONGODB_URI:"mongodb://127.0.0.1:27017/hscc-api-airports".toString(),MONGODB_MS_PORT:parseInt(null!=="6666"?"6666":"-Infinity"),DISABLED_API_VERSIONS:[],FLIGHTS_GENERATE_DAYS:parseInt(null!=="1"?"1":"-Infinity"),AIRPORT_NUM_OF_GATE_LETTERS:parseInt(null!=="4"?"4":"-Infinity"),AIRPORT_GATE_NUMBERS_PER_LETTER:parseInt(null!=="20"?"20":"-Infinity"),AIRPORT_PAIR_USED_PERCENT:parseInt(null!=="75"?"75":"-Infinity"),FLIGHT_HOUR_HAS_FLIGHTS_PERCENT:parseInt(null!=="66"?"66":"-Infinity"),RESULTS_PER_PAGE:parseInt(null!=="100"?"100":"-Infinity"),IGNORE_RATE_LIMITS:!1,LOCKOUT_ALL_KEYS:!1,DISALLOWED_METHODS:[],REQUESTS_PER_CONTRIVED_ERROR:parseInt(null!=="10"?"10":"-Infinity"),MAX_CONTENT_LENGTH_BYTES:Object(o.parse)("100kb"),HYDRATE_DB_ON_STARTUP:!Object(r.isUndefined)("true")&&!0,DEBUG_MODE:/--debug|--inspect/.test(process.execArgv.join(" "))},n=e=>s()?[e]:[],c=[t.FLIGHTS_GENERATE_DAYS,t.AIRPORT_NUM_OF_GATE_LETTERS,t.AIRPORT_GATE_NUMBERS_PER_LETTER,...n(t.AIRPORT_PAIR_USED_PERCENT),...n(t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT),t.RESULTS_PER_PAGE,t.REQUESTS_PER_CONTRIVED_ERROR,t.MAX_CONTENT_LENGTH_BYTES];e&&"development"==t.NODE_ENV&&console.info("debug - "+t);if("unknown"==t.NODE_ENV||s()&&""===t.MONGODB_URI||c.some(e=>!Object(r.isNumber)(e)||e<0))throw new a.b("illegal environment detected, check environment variables");if(t.RESULTS_PER_PAGE= "+i.a);if(t.AIRPORT_NUM_OF_GATE_LETTERS>26)throw new a.b("AIRPORT_NUM_OF_GATE_LETTERS must be <= 26");if(s()&&t.AIRPORT_PAIR_USED_PERCENT>100)throw new a.b("AIRPORT_PAIR_USED_PERCENT must between 0 and 100");if(s()&&t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT>100)throw new a.b("FLIGHT_HOUR_HAS_FLIGHTS_PERCENT must between 0 and 100");if(s()&&t.MONGODB_MS_PORT&&t.MONGODB_MS_PORT<=1024)throw new a.b("optional environment variable MONGODB_MS_PORT must be > 1024");return t}},function(e,t,n){"use strict";var r=n(5).format,o=n(2).MongoError,s={},i={},a=null,c=process.pid,u=null,l=function(e,t){if(!(this instanceof l))return new l(e,t);t=t||{},this.className=e,t.logger?u=t.logger:null==u&&(u=console.log),t.loggerLevel&&(a=t.loggerLevel||"error"),null==i[this.className]&&(s[this.className]=!0)};l.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",i={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(i={},t.forEach((function(e){i[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(19),o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(4).collationNotSupported,c=n(13),u=n(4).isUnifiedTopology,l=n(43),p=n(24).Readable,h=n(0).SUPPORTS,f=n(0).MongoDBNamespace,d=n(3).OperationBase,m=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function g(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class b extends p{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof d&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=f.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const s=e.s.options;"boolean"==typeof s.promoteLongs?this.cursorState.promoteLongs=s.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof s.promoteValues?this.cursorState.promoteValues=s.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof s.promoteBuffers?this.cursorState.promoteBuffers=s.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),s.reconnect&&(this.cursorState.reconnect=s.reconnect),this.logger=r("Cursor",s),"number"==typeof n?(this.cursorState.cursorId=m.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof m&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return g(t,new s("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new s("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new s("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);if(t.cursorState.cursorIndex!==t.cursorState.documents.length||m.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId))return g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&m.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return t.kill(),S(t,(function(){g(n,new s(e?e.$err:void 0))}));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),g(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new i("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return w(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,i){return r?g(n,r):(t.connection=i,0===t.cursorState.documents.length&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId)?g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!m.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){return this.topology.cursor(this.ns,this.cmd,this.options)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return v(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new s(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new s(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?m.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const i=o.cursorId||0;t.cursorState.cursorId=i instanceof m?i:m.fromNumber(i),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,i)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=i,t.cursorState.init=!0,a(t.server,t.cmd))return e(new s(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void i.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);i.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,v(e,t)}function v(e,t){w(e,()=>g(t,null,null))}function w(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}h.ASYNC_ITERATOR&&(b.prototype[Symbol.asyncIterator]=n(92).asyncIterator),e.exports={CursorState:y,CoreCursor:b}},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(11).retrieveBSON)().Long;const o=n(16).Buffer;var s=0,i=n(7).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=s++},a.nextRequestId=function(){return s+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var s=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+s.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=i.OP_QUERY>>24&255,r[c+2]=i.OP_QUERY>>16&255,r[c+1]=i.OP_QUERY>>8&255,r[c]=255&i.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++s};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=s++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_GETMORE>>24&255,n[t+2]=i.OP_GETMORE>>16&255,n[t+1]=i.OP_GETMORE>>8&255,n[t]=255&i.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=s++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_KILL_CURSORS>>24&255,n[t+2]=i.OP_KILL_CURSORS>>16&255,n[t+1]=i.OP_KILL_CURSORS>>8&255,n[t]=255&i.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,s){s=s||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=s,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof s.promoteLongs||s.promoteLongs,this.promoteValues="boolean"!=typeof s.promoteValues||s.promoteValues,this.promoteBuffers="boolean"==typeof s.promoteBuffers&&s.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var s=0;st?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t){e.exports=require("stream")},function(e,t,n){"use strict";const r=n(24).Transform,o=n(24).PassThrough,s=n(5).deprecate,i=n(0).handleCallback,a=n(1).ReadPreference,c=n(1).MongoError,u=n(20).CoreCursor,l=n(20).CursorState,p=n(1).BSON.Map,h=n(0).maybePromise,f=n(43),d=n(0).formattedOrderClause,m=n(181).each,y=n(182),g=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],b=["numberOfRetries","tailableRetryInterval"];class S extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,s=r.tailableRetryInterval||500,i=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return h(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===S.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return h(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=d(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===b.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${b}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===g.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${g}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:e+" is not a valid query modifier",driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new p(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,m(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{m(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});m(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return h(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,s)=>{if(o)return i(e,o);if(null==s)return t.close({skipKillCursors:!0},()=>i(e,null,n));if(n.push(s),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new y(this,e,t);return f(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),h(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e){return this.operation&&null==this.operation.cmd?(this.operation.options.explain=!0,this.operation.fullResponse=!1,f(this.topology,this.operation,e)):(this.cmd.explain=!0,this.cmd.readConcern&&delete this.cmd.readConcern,h(this,e,e=>{u.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}S.prototype.maxTimeMs=S.prototype.maxTimeMS,s(S.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),s(S.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),s(S.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=S},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).OperationBase,s=n(1).ReadPreference,i=n(36),a=n(29),c=n(4).maxWireVersion,u=n(31).commandSupportsReadConcern,l=n(2).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=s.resolve(o,this.options),this.readConcern=function(e,t){return i.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),this.explain=!1,n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,s=c(e),i=this.session&&this.session.inTransaction();this.readConcern&&u(t)&&!i&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&s<5?n(new l(`Server ${e.name}, which reports wire version ${s}, does not support collation`)):(s>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t,n){"use strict";const r=n(11).retrieveSnappy(),o=n(145),s={snappy:1,zlib:2},i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:s,uncompressibleCommands:i,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var s={};e.options.zlibCompressionLevel&&(s.level=e.options.zlibCompressionLevel),o.deflate(t,s,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>s.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case s.snappy:r.uncompress(t,n);break;case s.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","fsync"]);class o{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new o(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new o(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j,e.writeConcern.fsync)}return new o(e.w,e.wtimeout,e.j,e.fsync)}}}e.exports=o},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(10),s=r(),i=s.Binary,a=n(4).uuidV4,c=n(2).MongoError,u=n(2).isRetryableError,l=n(2).MongoNetworkError,p=n(2).MongoWriteConcernError,h=n(41).Transaction,f=n(41).TxnState,d=n(4).isPromiseLike,m=n(13),y=n(41).isTransactionCommand,g=n(9).resolveClusterTime,b=n(7).isSharded,S=n(4).maxWireVersion,v=n(0).now,w=n(0).calculateDurationInMs;function _(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const O=Symbol("serverSession");class T extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof M))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[O]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new h}get id(){return this.serverSession.id}get serverSession(){return null==this[O]&&(this[O]=this.sessionPool.acquire()),this[O]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},this.hasEnded||(this.serverSession&&this.inTransaction()&&this.abortTransaction(),this.sessionPool.release(this.serverSession),this[O]=void 0,this.hasEnded=!0,this.emit("ended",this)),"function"==typeof t&&t(null,null)}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof T&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(_(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(b(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new h(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(f.STARTING_TRANSACTION)}commitTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"commitTransaction",(n,r)=>n?t(n):e(r))});I(this,"commitTransaction",e)}abortTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"abortTransaction",(n,r)=>n?t(n):e(r))});I(this,"abortTransaction",e)}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return N(this,v(),e,t)}}const E=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function C(e,t){return w(e){if(!function(e){return A.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(s=>{if(s instanceof c&&C(n,12e4)&&!x(s)){if(s.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(s.hasErrorLabel("TransientTransactionError"))return N(t,n,r,o)}throw s})}(e,t,n,r)}).catch(o=>{function s(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&C(t,12e4))return N(e,t,n,r);throw x(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>s(o)):s(o)})}function I(e,t,n){if(!_(e,n))return;let r=e.transaction.state;if(r===f.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===f.STARTING_TRANSACTION||r===f.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(f.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===f.STARTING_TRANSACTION)return e.transaction.transition(f.TRANSACTION_ABORTED),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===f.TRANSACTION_COMMITTED||r===f.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let s;function i(r,o){var s;"commitTransaction"===t?(e.transaction.transition(f.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof p||u(r)||x(r))&&(x(s=r)||!E.has(s.codeName)&&100!==s.code&&79!==s.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(f.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?s=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(s={w:e.clientOptions.w}),r===f.TRANSACTION_COMMITTED&&(s=Object.assign({wtimeout:1e4},s,{w:"majority"})),s&&Object.assign(o,{writeConcern:s}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>i(a(e),t));i(a(t),n)})}class k{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)},this.lastUse=v(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(w(this.lastUse)%864e5%36e5/6e4)>e-1}}class M{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new k}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function R(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:T,ServerSession:k,ServerSessionPool:M,TxnState:f,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=v(),t.lsid=r.id;const o=e.inTransaction()||y(t),i=n.willRetryWrite,a=R(t,n);if(r.txnNumber&&(i||o)&&(t.txnNumber=s.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==f.NO_TRANSACTION&&e.transaction.transition(f.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c("Read preference in a transaction must be primary, not: "+n.readPreference.mode);if(t.autocommit=!1,e.transaction.state===f.STARTING_TRANSACTION){e.transaction.transition(f.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&g(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:R}},function(e,t,n){"use strict";const r=n(10),o=n(1).MongoError,s=n(5).format,i=n(1).ReadPreference,a=n(1).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:i})},c.prototype.addObjectAndMethod=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:i})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?(n&&r||n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)||!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode))&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):(n&&r||n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)||!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode))&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var p=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,s=!1,i=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,s=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(i=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",s),t(this,"hasListCollectionsCommand",i),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class h extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new p(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,i.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=i.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=i.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(h.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(h.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(h.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(h.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=p,t.TopologyBase=h},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===i.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=(":"+this.port).length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===h(this.topologyVersion,e.topologyVersion);return null!=e&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:p,compareTopologyVersion:h}},function(e,t,n){"use strict";const r=n(16).Buffer,o=n(7).opcodes,s=n(7).databaseNamespace,i=n(13);let a=0;class c{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=s(t),r.readPreference&&r.readPreference.mode!==i.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:c.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let s=n.length;const i=this.command;return s+=this.makeDocumentSegment(e,i),n.writeInt32LE(s,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}c.getRequestId=function(){return a=a+1&2147483647,a};e.exports={Msg:c,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(s.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(s.BUFFER_SIZE+this.buffer.length)):new Array(s.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(s=0;sthis.position?t:this.position}else if("string"==typeof e){for(s=0;sthis.position?t:this.position}},s.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r=6&&null==t.__nodejs_mock_server__}(e),b=h.session;let S=e.clusterTime,v=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(S.clusterTime)&&(S=b.clusterTime);const e=l(b,v,h);if(e)return f(e)}S&&(v.$clusterTime=S),a(e)&&!g&&y&&"primary"!==y.mode&&(v={$query:v,$readPreference:y.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},h);w.slaveOk=y.slaveOk();const _=c(t)+".$cmd",O=g?new o(d,_,v,w):new r(d,_,v,w),T=b&&(b.inTransaction()||u(v))?function(e){return e&&e instanceof p&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),f.apply(null,arguments)}:f;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new s(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return h(e)&&e.autoEncrypter}(e))return void f(e,t,n,r,o);const i=h(e);"number"!=typeof i||i<8?o(new s("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const s=e.autoEncrypter;function i(e,t){e||null==t?o(e,t):s.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}s.encrypt(t,n,r,(n,s)=>{n?o(n,null):f(e,t,s,r,i)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(3).Aspect,s=n(3).OperationBase,i=n(13),a=n(2).isRetryableError,c=n(4).maxWireVersion,u=n(4).isUnifiedTopology;function l(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");if(u(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){const r=e.s.promiseLibrary;let o;"function"!=typeof n&&(o=new r((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));return e.selectServer(i.primaryPreferred,r=>{r?n(r):l(e,t,n)}),o}(e,t,n);const c=e.s.promiseLibrary;let h,f,d;if(e.hasSessionSupport())if(null==t.session)f=Symbol(),h=e.startSession({owner:f}),t.session=h;else if(t.session.hasEnded)throw new r("Use of expired sessions is not permitted");function m(e,r){h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),n(e,r)}"function"!=typeof n&&(d=new c((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));try{t.hasAspect(o.EXECUTE_WITH_SELECTION)?function(e,t,n){const s=t.readPreference||i.primary,c=t.session&&t.session.inTransaction();if(c&&!s.equals(i.primary))return void n(new r("Read preference in a transaction must be primary, not: "+s.mode));const u={readPreference:s,session:t.session};function l(r,o){return null==r?n(null,o):a(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,s)=>{if(r)return void n(r,null);const i=!1!==e.s.options.retryReads&&t.session&&!c&&p(s)&&t.canRetryRead;t.hasAspect(o.RETRYABLE)&&i?t.execute(s,l):t.execute(s,n)})}(e,t,m):t.execute(m)}catch(e){throw h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),e}return d}function p(e){return c(e)>=6}e.exports=l},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(170)}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(14).createIndex,i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(14).ensureIndex,u=n(14).evaluate,l=n(14).executeCommand,p=n(0).handleCallback,h=n(14).indexInformation,f=n(1).BSON.Long,d=n(1).MongoError,m=n(1).ReadPreference,y=n(12).insertDocuments,g=n(12).updateDocuments;function b(e,t,n){h(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){s(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}),h.group.key=e}(f=Object.assign({},f)).readPreference=m.resolve(e,f),a(h,e,f);try{i(h,e,f)}catch(e){return d(e,null)}l(e.s.db,h,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.retval)})}else{const i=null!=s&&"Code"===s._bsontype?s.scope:{};i.ns=e.collectionName,i.keys=t,i.condition=n,i.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,s.toString()+";");u(e.s.db,new o(a,i),null,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),h(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return p(r,e,null);if(!Array.isArray(t))return p(r,null,null!=n[t]);for(let e=0;e{if(r)return p(n,r,null);if(null==s)return p(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const i=[];o&&(t.raw=o);for(let n=0;n{if(null!=o)return null==t?p(o,null,null):e?p(o,e,null):void p(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,s=n(0).checkCollectionName,i=n(1).BSON.ObjectID,a=n(1).MongoError,c=n(0).normalizeHintField,u=n(0).decorateCommand,l=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,h=n(0).formattedOrderClause,f=n(1).ReadPreference,d=n(183),m=n(184),y=n(79),g=n(0).executeLegacyOperation,b=n(29),S=n(36),v=n(0).MongoDBNamespace,w=n(82),_=n(83),O=n(46).ensureIndex,T=n(46).group,E=n(46).parallelCollectionScan,C=n(12).removeDocuments,x=n(46).save,A=n(12).updateDocuments,N=n(63),I=n(113),k=n(185),M=n(114),R=n(186),D=n(187),B=n(188),P=n(84).DropCollectionOperation,L=n(115),j=n(189),U=n(190),z=n(191),F=n(192),W=n(64),q=n(193),$=n(194),H=n(195),V=n(196),Y=n(197),G=n(198),K=n(116),X=n(199),J=n(200),Z=n(201),Q=n(202),ee=n(203),te=n(117),ne=n(121),re=n(212),oe=n(213),se=n(214),ie=n(215),ae=n(216),ce=n(43),ue=["ignoreUndefined"];function le(e,t,n,r,o,a){s(r);const c=null==a||null==a.slaveOk?e.slaveOk:a.slaveOk,u=null==a||null==a.serializeFunctions?e.s.options.serializeFunctions:a.serializeFunctions,l=null==a||null==a.raw?e.s.options.raw:a.raw,p=null==a||null==a.promoteLongs?e.s.options.promoteLongs:a.promoteLongs,h=null==a||null==a.promoteValues?e.s.options.promoteValues:a.promoteValues,d=null==a||null==a.promoteBuffers?e.s.options.promoteBuffers:a.promoteBuffers,m=new v(n,r),y=a.promiseLibrary||Promise;o=null==o?i:o,this.s={pkFactory:o,db:e,topology:t,options:a,namespace:m,readPreference:f.fromOptions(a),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:p,promoteValues:h,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:y,readConcern:S.fromOptions(a),writeConcern:b.fromOptions(a)}}Object.defineProperty(le.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(le.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(le.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(le.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(le.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(le.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(le.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function he(e,t,n,r,o){const s=Array.prototype.slice.call(arguments,1);return o="function"==typeof s[s.length-1]?s.pop():void 0,t=s.length&&s.shift()||[],n=s.length?s.shift():null,r=s.length&&s.shift()||{},(r=Object.assign({},r)).readPreference=f.PRIMARY,ce(this.s.topology,new W(this,e,t,n,r),o)}le.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let i=Object.assign({},t);for(let e in this.s.options)-1!==ue.indexOf(e)&&(i[e]=this.s.options[e]);if(i.skip=t.skip?t.skip:0,i.limit=t.limit?t.limit:0,i.raw="boolean"==typeof t.raw?t.raw:this.s.raw,i.hint=null!=t.hint?c(t.hint):this.s.collectionHint,i.timeout=void 0===t.timeout?void 0:t.timeout,i.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,i.readPreference=f.resolve(this,i),null==i.readPreference||"primary"===i.readPreference&&"primary"===i.readPreference.mode||(i.slaveOk=!0),null!=r&&"object"!=typeof r)throw a.create({message:"query selector must be an object",driver:!0});const d={find:this.s.namespace.toString(),limit:i.limit,skip:i.skip,query:r};"boolean"==typeof t.allowDiskUse&&(d.allowDiskUse=t.allowDiskUse),"boolean"==typeof i.awaitdata&&(i.awaitData=i.awaitdata),"boolean"==typeof i.timeout&&(i.noCursorTimeout=i.timeout),u(d,i,["session","collation"]),s&&(d.fields=s),i.db=this.s.db,i.promiseLibrary=this.s.promiseLibrary,null==i.raw&&"boolean"==typeof this.s.raw&&(i.raw=this.s.raw),null==i.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(i.promoteLongs=this.s.promoteLongs),null==i.promoteValues&&"boolean"==typeof this.s.promoteValues&&(i.promoteValues=this.s.promoteValues),null==i.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(i.promoteBuffers=this.s.promoteBuffers),d.sort&&(d.sort=h(d.sort)),p(d,this,t);try{l(d,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const m=this.s.topology.cursor(new z(this,this.s.namespace,d,i),i);if("function"!=typeof n)return m;n(null,m)})),le.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new J(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ce(this.s.topology,r,n)},le.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw a.create({message:"operations must be an array of documents",driver:!0});const r=new I(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),le.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ae(this,e,t,n),r)},le.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new oe(this,e,t,n),r)},le.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ie(this,e,t,n),r)},le.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,A,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),le.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeOne=le.prototype.deleteOne,le.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new R(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeMany=le.prototype.deleteMany,le.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,C,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),le.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,x,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),le.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new F(this,e=e||{},t=t||{});return ce(this.s.topology,r,n)})),le.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:f.PRIMARY});const r=new ne(this,e,t);return ce(this.s.topology,r,n)},le.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new P(this.s.db,this.collectionName,e);return ce(this.s.topology,n,t)},le.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new te(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Z(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=f.PRIMARY;const o=new L(this,e,t);return ce(this.s.topology,o,n)},le.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new j(this,e);return ce(this.s.topology,n,t)},le.prototype.dropAllIndexes=r(le.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),le.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new re(this,e=e||{});return ce(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),le.prototype.listIndexes=function(e){return new _(this.s.topology,new Q(this,e),e)},le.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},g(this.s.topology,O,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),le.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ce(this.s.topology,r,n)},le.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new K(this.s.db,this.collectionName,e);return ce(this.s.topology,r,t)},le.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ce(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),le.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new k(this,e,t);return ce(this.s.topology,o,n)},le.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const s=o.length&&o.shift()||{},i=o.length&&o.shift()||{},a=new B(this,e,s,i);return ce(this.s.topology,a,r)},le.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ce(this.s.topology,r,t)},le.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},ce(this.s.topology,new q(this,e,t),n)},le.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new $(this,e,t,n),r)},le.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new H(this,e,t,n),r)},le.prototype.findAndModify=r(he,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),le.prototype._findAndModify=he,le.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ce(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),le.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new w(this.s.topology,new N(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},le.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},le.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=f.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),g(this.s.topology,E,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),le.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const s=new V(this,e,t,n);return ce(this.s.topology,s,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),le.prototype.group=r((function(e,t,n,r,o,s,i,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,s=c.length?c.shift():null,i=c.length&&c.shift()||{},"function"!=typeof o&&(s=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),s=null==s||s,g(this.s.topology,T,[this,e,t,n,r,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),le.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new ee(this,e,t,n);return ce(this.s.topology,o,r)},le.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,d(this.s.topology,this,e)},le.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},le.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=le},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&s,r[5]=s>>8&255,r[4]=s>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof h?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var p=[];for(l=0;l<10;)p[48+l]=l++;for(;l<16;)p[55+l]=p[87+l]=l++;var h=Buffer,f=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new h(12),n=0,r=0;r<24;)t[n++]=p[e.charCodeAt(r++)]<<4|p[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&i.test(e):e instanceof c||(e instanceof h||"function"==typeof e.toHexString&&(e.id instanceof h||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&i.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(s),D=e.match(i);if(!M&&!R&&!D||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!f(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(h.toBuffer(n?u:l));if("N"===e[k])return new m(h.toBuffer(c))}for(;f(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||y)&&(y||(w=b),y=!0,_[T++]=parseInt(e[k],10),O+=1),y&&(S+=1),d&&(v+=1),b+=1,k+=1;else{if(d)return new m(h.toBuffer(c));d=!0,k+=1}if(d&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var B=e.substr(++k).match(p);if(!B||!B[2])return new m(h.toBuffer(c));x=parseInt(B[0],10),k+=B[0].length}if(e[k])return new m(h.toBuffer(c));if(E=0,O){if(C=O-1,g=S,0!==x&&1!==g)for(;"0"===e[w+g-1];)g-=1}else E=0,C=0,_[0]=0,S=1,O=1,g=0;for(x<=v&&v-x>16384?x=-6176:x-=v;x>6111;){if((C+=1)-E>34){var P=_.join("");if(P.match(/^0+$/)){x=6111;break}return new m(h.toBuffer(n?u:l))}x-=1}for(;x<-6176||O=5&&(U=1,5===j))for(U=_[C]%2==1,A=w+C+2;A=0&&++_[z]>9;z--)if(_[z]=0,0===z){if(!(x<6111))return new m(h.toBuffer(n?u:l));x+=1,_[z]=1}}if(N=r.fromNumber(0),I=r.fromNumber(0),0===g)N=r.fromNumber(0),I=r.fromNumber(0);else if(C-E<17)for(z=E,I=r.fromNumber(_[z++]),N=new r(0,0);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));else{for(z=E,N=r.fromNumber(_[z++]);z<=C-17;z++)N=(N=N.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));for(I=r.fromNumber(_[z++]);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]))}var F,W,q,$,H=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new r(t.getLowBits(),0),a=n.multiply(s),c=n.multiply(i),u=o.multiply(s),l=o.multiply(i);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(N,r.fromString("100000000000000000"));H.low=H.low.add(I),F=H.low,W=I,q=F.high_>>>0,$=W.high_>>>0,(q<$||q===$&&F.low_>>>0>>0)&&(H.high=H.high.add(r.fromNumber(1))),t=x+a;var V={low:r.fromNumber(0),high:r.fromNumber(0)};H.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(V.high=V.high.or(r.fromNumber(3).shiftLeft(61)),V.high=V.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),V.high=V.high.or(H.high.and(r.fromNumber(0x7fffffffffff)))):(V.high=V.high.or(r.fromNumber(16383&t).shiftLeft(49)),V.high=V.high.or(H.high.and(r.fromNumber(562949953421311)))),V.low=H.low,n&&(V.high=V.high.or(r.fromString("9223372036854775808")));var Y=h.allocBuffer(16);return k=0,Y[k++]=255&V.low.low_,Y[k++]=V.low.low_>>8&255,Y[k++]=V.low.low_>>16&255,Y[k++]=V.low.low_>>24&255,Y[k++]=255&V.low.high_,Y[k++]=V.low.high_>>8&255,Y[k++]=V.low.high_>>16&255,Y[k++]=V.low.high_>>24&255,Y[k++]=255&V.high.low_,Y[k++]=V.high.low_>>8&255,Y[k++]=V.high.low_>>16&255,Y[k++]=V.high.low_>>24&255,Y[k++]=255&V.high.high_,Y[k++]=V.high.high_>>8&255,Y[k++]=V.high.high_>>16&255,Y[k++]=V.high.high_>>24&255,new m(Y)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,s,i,c=0,u=new Array(36),l=0;l>26&31)>>3==3){if(30===s)return v.join("")+"Infinity";if(31===s)return"NaN";i=e>>15&16383,f=8+(e>>14&1)}else f=e>>14&7,i=e>>17&16383;if(p=i-a,S.parts[0]=(16383&e)+((15&f)<<14),S.parts[1]=t,S.parts[2]=n,S.parts[3]=o,0===S.parts[0]&&0===S.parts[1]&&0===S.parts[2]&&0===S.parts[3])b=!0;else for(y=3;y>=0;y--){var _=0,O=d(S);if(S=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*y+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[g]=0;else for(c=36,l=0;!u[g];)l++,c-=1,g+=1;if((h=c-1+p)>=34||h<=-7||p>0){for(v.push(u[g++]),(c-=1)&&v.push("."),l=0;l0?v.push("+"+h):v.push(h)}else if(p>=0)for(l=0;l0)for(l=0;l{if(r)return n(r);Object.assign(t,{nonce:s});const i=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(f(o,i,s),{db:i.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?d(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,s=t.nonce,i=o.source,a=f(e,o,s);r.command(i+".$cmd",a,(r,o)=>{const s=v(r,o);if(s)return n(s);d(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function h(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function f(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new c(o.concat([o.from("n,,","utf8"),h(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function d(e,t,n,s){const a=n.connection,l=n.credentials,f=n.nonce,d=l.source,w=p(l.username),_=l.password;let O;if("sha256"===e)O=u?u(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new i("username must be a string");if("string"!=typeof t)throw new i("password must be a string");if(0===t.length)throw new i("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(w,_)}catch(e){return s(e)}const T=o.isBuffer(t.payload)?new c(t.payload):t.payload,E=m(T.value()),C=parseInt(E.i,10);if(C&&C<4096)return void s(new i("Server returned an invalid iteration count "+C),!1);const x=E.s,A=E.r;if(A.startsWith("nonce"))return void s(new i("Server returned an invalid nonce: "+A),!1);const N="c=biws,r="+A,I=function(e,t,n,o){const s=[e,t.toString("base64"),n].join("_");if(void 0!==g[s])return g[s];const i=r.pbkdf2Sync(e,t,n,S[o],o);b>=200&&(g={},b=0);return g[s]=i,b+=1,i}(O,o.from(x,"base64"),C,e),k=y(e,I,"Client Key"),M=y(e,I,"Server Key"),R=(D=e,B=k,r.createHash(D).update(B).digest());var D,B;const P=[h(w,f),T.value().toString("base64"),N].join(","),L=[N,"p="+function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o{const n=v(e,t);if(n)return s(n);const c=t.result,u=m(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r{const n=m(t.s.options);if(n)return e(n);d(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},y.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),y.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return h(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof f))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.autoEncrypter;o?o.teardown(e,e=>r(t||e)):r(t)}):r()})},y.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},y.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},y.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new y(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},y.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");if(!this.topology.hasSessionSupport())throw new a("Current topology does not support sessions");return this.topology.startSession(e,this.s.options)},y.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},y.prototype.getLogger=function(){return this.s.options.logger},e.exports=y},function(e,t,n){"use strict";const r=n(26),o=n(1).MongoError,s=n(4).maxWireVersion,i=n(1).ReadPreference,a=n(3).Aspect,c=n(3).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=i.primary),n.explain&&(this.readConcern||this.writeConcern))throw new o('"explain" cannot be used on an aggregate call with readConcern/writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=s(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),n.explain&&(n.full=!1,o.explain=n.explain),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyRetryableWrites,s=n(0).applyWriteConcern,i=n(0).decorateWithCollation,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(4).maxWireVersion,h=n(112).MongoError;e.exports=class extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),f=this.doc;let d=this.options;const m={findAndModify:t.collectionName,query:n};r&&(m.sort=r),m.new=!!d.new,m.remove=!!d.remove,m.upsert=!!d.upsert;const y=d.projection||d.fields;y&&(m.fields=y),d.arrayFilters&&(m.arrayFilters=d.arrayFilters),f&&!d.remove&&(m.update=f),d.maxTimeMS&&(m.maxTimeMS=d.maxTimeMS),d.serializeFunctions=d.serializeFunctions||t.s.serializeFunctions,d.checkKeys=!1,d=o(d,t.s.db),d=s(d,{db:t.s.db,collection:t},d),d.writeConcern&&(m.writeConcern=d.writeConcern),!0===d.bypassDocumentValidation&&(m.bypassDocumentValidation=d.bypassDocumentValidation),d.readPreference=l.primary;try{i(m,t,d)}catch(t){return e(t,null)}if(d.hint){if(d.writeConcern&&0===d.writeConcern.w||p(t.s.topology)<8)return void e(new h("The current topology does not support a hint on findAndModify commands"));m.hint=d.hint}a(t.s.db,m,d,(t,n)=>t?u(e,t,null):u(e,null,n))}}},function(e,t,n){"use strict";const r=n(10).EventEmitter,o=n(5).inherits,s=n(0).getSingleProperty,i=n(83),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(1).ReadPreference,p=n(1).MongoError,h=n(1).ObjectID,f=n(1).Logger,d=n(47),m=n(0).mergeOptionsAndWriteConcern,y=n(0).executeLegacyOperation,g=n(79),b=n(5).deprecate,S=n(0).deprecateOptions,v=n(0).MongoDBNamespace,w=n(80),_=n(29),O=n(36),T=n(82),E=n(14).createListener,C=n(14).ensureIndex,x=n(14).evaluate,A=n(14).profilingInfo,N=n(14).validateDatabaseName,I=n(63),k=n(118),M=n(204),R=n(23),D=n(205),B=n(206),P=n(114),L=n(84).DropCollectionOperation,j=n(84).DropDatabaseOperation,U=n(119),z=n(116),F=n(207),W=n(208),q=n(120),$=n(121),H=n(209),V=n(43),Y=["w","wtimeout","fsync","j","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function G(e,t,n){if(n=n||{},!(this instanceof G))return new G(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,Y)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:f("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||h,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new v(e)},N(e),s(this,"serverConfig",this.s.topology),s(this,"bufferMaxEntries",this.s.bufferMaxEntries),s(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",E(this,"error",this)),t.on("timeout",E(this,"timeout",this)),t.on("close",E(this,"close",this)),t.on("parseError",E(this,"parseError",this)),t.once("open",E(this,"open",this)),t.once("fullsetup",E(this,"fullsetup",this)),t.once("all",E(this,"all",this)),t.on("reconnect",E(this,"reconnect",this)))}o(G,r),Object.defineProperty(G.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(G.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(G.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(G.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(G.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(G.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(G.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),G.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new D(this,e,t);return V(this.s.topology,r,n)},G.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new I(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},G.prototype.admin=function(){return new(n(122))(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];G.prototype.collection=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined),null==(t=m(t,this.s.options,K,!0))||!t.strict)try{const r=new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof p&&n)return n(e);throw e}if("function"!=typeof n)throw u("A callback is required in strict mode. While getting collection "+e);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new p("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},G.prototype.createCollection=S({name:"Db.createCollection",deprecatedOptions:["autoIndexId"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new B(this,e,t);return V(this.s.topology,r,n)})),G.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return V(this.s.topology,r,t)},G.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new i(this.s.topology,new F(this,e,t),t)},G.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},y(this.s.topology,x,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),G.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new $(this.collection(e),t,n);return V(this.s.topology,o,r)},G.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new L(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new j(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new U(this,e,t);return V(this.s.topology,r,n)},G.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},y(this.s.topology,C,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),G.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},G.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new q(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new H(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},y(this.s.topology,A,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),G.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new W(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new z(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.unref=function(){this.s.topology.unref()},G.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new g(this,e,t)},G.prototype.getLogger=function(){return this.s.logger},G.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,G.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,G.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,G.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,G.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,G.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=G},function(e,t,n){"use strict";const r=n(1).Server,o=n(25),s=n(32).TopologyBase,i=n(32).Store,a=n(1).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,p=n(0).mergeOptions;var h=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class f extends s{constructor(e,t,n){super();const s=(n=l(n,h)).promiseLibrary;var f={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},d=n.store||new i(this,f);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var y=p({},{host:e,port:t,disconnectHandler:d,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});y=u(y,n);var g=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;y=u(y,g),this.s={coreTopology:new r(y),sCapabilities:null,clonedOptions:y,reconnect:y.reconnect,emitError:y.emitError,poolSize:y.size,storeOptions:f,store:d,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:s||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(){n.s.store.flush()},i=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",s),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("attemptReconnect",i("attemptReconnect")),n.s.coreTopology.on("monitoring",i("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(f.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(f.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(f.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(f.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=f},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.shuffle=void 0;var r=n(229);function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,s=void 0;try{for(var i,a=e[Symbol.iterator]();!(r=(i=a.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw s}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return i(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);np()(1,100),w=e=>36e5*Math.floor(e/36e5),_=e=>{const t=(Math.floor(e/1e3).toString(16)+b+(++g).toString(16)).padEnd(24,"0");return new r.ObjectId(t)},O=await y.deleteMany({_id:{$lt:_(Date.now()-6048e5)}});!e&&console.info(`api - Deleted ${O.deletedCount} flights older than 7 days`);const T=w((null!==(t=null===(n=await y.find().sort({_id:-1}).limit(1).next())||void 0===n?void 0:n._id)&&void 0!==t?t:new r.ObjectId).getTimestamp().getTime()),E=(w(Date.now()+S)-T)/36e5;if(!e&&console.info(`api - Generating ${E} hours worth of flights...`),!E)return 0;const C=[...Array(9999)].map((e,t)=>t+1),x="abcdefghijklmnopqrstuvwxyz".split("").slice(0,Object(o.a)().AIRPORT_NUM_OF_GATE_LETTERS).map(e=>[...Array(Object(o.a)().AIRPORT_GATE_NUMBERS_PER_LETTER)].map((t,n)=>`${e}${n+1}`)).flat(),A=[];let N=!1;[...Array(E)].forEach((t,n)=>{if(v()>Object(o.a)().FLIGHT_HOUR_HAS_FLIGHTS_PERCENT)return;const r=T+36e5+36e5*n,s=Object(a.shuffle)(l).slice(0,p()(2,l.length)),i=s.reduce((e,t)=>({...e,[t._id.toHexString()]:f()(u()(C))}),{});!e&&console.info(`api ↳ Generating flights for hour ${r} (${n+1}/${E})`),c.forEach(e=>{const t=Object(a.shuffle)(u()(x)),n=e=>t.push(e),l=()=>{const e=t.shift();if(!e)throw new d.d("ran out of gates");return e},f=[];c.forEach(t=>{e._id.equals(t._id)||v()>Object(o.a)().AIRPORT_PAIR_USED_PERCENT||s.forEach(n=>{N=!N;const o=p()(0,10),s=p()(0,4),u={};let l=p()(60,150),d=p()(5e3,8e3);const m=[...Array(h.seatClasses.length)].map(e=>p()(10,100/h.seatClasses.length)).sort((e,t)=>t-e);m[0]+=100-m.reduce((e,t)=>e+t,0);for(const[e,t]of Object.entries(h.seatClasses))l=p()(l,2*l)+Number(Math.random().toFixed(2)),d=p()(d,2*d),u[t]={total:m[Number(e)],priceDollars:l,priceFfms:d};const y={};let g=1,b=p()(10,150);for(const e of h.allExtras)v()>75||(g=p()(g,2.5*g)+Number(Math.random().toFixed(2)),b=p()(b,2*b),y[e]={priceDollars:g,priceFfms:b});f.push({_id:_(r),bookerKey:N?null:e.chapterKey,type:N?"arrival":"departure",airline:n.name,comingFrom:N?t.shortName:Object(a.shuffle)(c).filter(t=>t.shortName!=e.shortName)[0].shortName,landingAt:e.shortName,departingTo:N?null:t.shortName,flightNumber:n.codePrefix+i[n._id.toHexString()]().toString(),baggage:{checked:{max:o,prices:[...Array(o)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||35))]},[])},carry:{max:s,prices:[...Array(s)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||15))]},[])}},ffms:p()(2e3,6e3),seats:u,extras:y})})});const m=e=>{if(!e.stochasticStates)throw new d.d("expected stochastic state to exist");return Object.values(e.stochasticStates).slice(-1)[0]};f.forEach(e=>{let t=0,n=!1;const o="arrival"==e.type,s=p()(r,r+36e5-(o?96e4:186e4));e.stochasticStates={0:{arriveAtReceiver:s,departFromSender:s-p()(72e5,18e6),departFromReceiver:o?null:s+9e5,status:"scheduled",gate:null}};for(let r=1;!n&&r<3;++r){const o={...m(e)};switch(r){case 1:t=o.departFromSender,v()>80?(o.status="cancelled",n=!0):o.status="on time",e.stochasticStates[t.toString()]=o;break;case 2:v()>75&&(t=p()(o.arriveAtReceiver-72e5,o.departFromSender+9e5),o.status="delayed",o.arriveAtReceiver+=p()(3e5,9e5),o.departFromReceiver&&(o.departFromReceiver+=p()(3e5,9e5)),e.stochasticStates[t.toString()]=o);break;default:throw new d.d("unreachable stage encountered (1)")}}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 3 encountered impossible condition");const t=m(e);"cancelled"!=t.status&&(e.stochasticStates[p()(t.arriveAtReceiver-72e5,t.arriveAtReceiver-9e5).toString()]={...t,gate:l()})}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 4 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>50&&(n(r),r=l()),e.stochasticStates[p()(t.arriveAtReceiver-18e5,t.arriveAtReceiver-3e5).toString()]={...t,gate:r,status:"landed"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 5 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>85&&(n(r),r=l()),e.stochasticStates[t.arriveAtReceiver]={...t,gate:r,status:"arrived"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 6-9 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let n=0,o=!1;const s="arrival"==e.type;for(let i=6;!o&&i<10;++i){const a={...t};switch(i){case 6:if(!s)continue;n=r+36e5,a.status="past",a.gate=null,o=!0;break;case 7:if(s)throw new d.d("arrival type encountered in departure-only model");n=a.arriveAtReceiver+p()(18e4,6e5),a.status="boarding";break;case 8:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (1)");n=a.departFromReceiver,a.status="departed";break;case 9:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (2)");n=a.departFromReceiver+p()(72e5,18e6),a.status="past",a.gate=null;break;default:throw new d.d("unreachable stage encountered (2)")}e.stochasticStates[n.toString()]=a}}),A.push(...f)})});try{if(!A.length)return 0;!e&&console.info(`api - Committing ${A.length} flights into database...`);const t=await y.insertMany(A);if(!t.result.ok)throw new d.c("flight insertion failed");if(t.insertedCount!=A.length)throw new d.d("assert failed: operation.insertedCount != totalHoursToGenerate");return!e&&console.info("api - Operation completed successfully!"),t.insertedCount}catch(e){throw e instanceof d.b?e:new d.c(e)}}},function(e,t,n){"use strict";if(void 0!==global.Map)e.exports=global.Map,e.exports.Map=global.Map;else{var r=function(e){this._keys=[],this._values={};for(var t=0;t{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else{if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete E[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new p("server instance pool was destroyed"):void 0:new p("server instance is not connected")}A.prototype.connect=function(e){if(e=e||{},T&&(E[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new p(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",I(this,"close")),this.s.pool.on("error",I(this,"error")),this.s.pool.on("timeout",I(this,"timeout")),this.s.pool.on("parseError",I(this,"parseError")),this.s.pool.on("connect",I(this,"connect")),this.s.pool.on("reconnect",I(this,"reconnect")),this.s.pool.on("reconnectFailed",I(this,"reconnectFailed")),S(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:x(this)}),this.emit("serverOpening",{topologyId:x(this),address:this.name}),this.s.pool.connect()},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},A.prototype.lastIsMaster=function(){return this.ismaster},A.prototype.unref=function(){this.s.pool.unref()},A.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},A.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},A.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var s=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof i))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return s?r(s):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),N(this,"command",e,t,n,r)?void 0:v(this,t)?r(new p(`server ${this.name} does not support collation`)):void f.command(this,e,t,n,r))},A.prototype.query=function(e,t,n,r,o){f.query(this,e,t,n,r,o)},A.prototype.getMore=function(e,t,n,r,o){f.getMore(this,e,t,n,r,o)},A.prototype.killCursors=function(e,t,n){f.killCursors(this,e,t,n)},A.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],f.insert(this,e,t,n,r))},A.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"update",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.update(this,e,t,n,r))},A.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"remove",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.remove(this,e,t,n,r))},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},A.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},A.prototype.connections=function(){return this.s.pool.allConnections()},A.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];A.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete E[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool)return this._destroyed=!0,void("function"==typeof t&&t(null,null));e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:x(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:x(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t),this._destroyed=!0}},e.exports=A},function(e,t,n){"use strict";const r=n(147),o=n(95),s=n(90),i=n(2).MongoError,a=n(2).MongoNetworkError,c=n(2).MongoNetworkTimeoutError,u=n(96).defaultAuthProviders,l=n(30).AuthContext,p=n(93),h=n(4).makeClientMetadata,f=p.MAX_SUPPORTED_WIRE_VERSION,d=p.MAX_SUPPORTED_SERVER_VERSION,m=p.MIN_SUPPORTED_WIRE_VERSION,y=p.MIN_SUPPORTED_SERVER_VERSION;let g;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function S(e,t){const n="string"==typeof t.host?t.host:"localhost";if(-1!==n.indexOf("/"))return{path:n};return{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const v=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const p=e&&e.connectionType?e.connectionType:s;null==g&&(g=u(e.bson)),function(e,t,n,s){const i="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const p="boolean"!=typeof t.noDelay||t.noDelay,h="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,f="number"==typeof t.socketTimeout?t.socketTimeout:36e4,d="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>f&&(l=Math.round(f/2));let m;const y=function(e,t){e&&m&&m.destroy(),s(e,t)};try{i?(m=o.connect(function(e,t){const n=S(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null==n.servername&&(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(S(e,t))}catch(e){return y(e)}m.setKeepAlive(u,l),m.setTimeout(h),m.setNoDelay(p);const g=i?"secureConnect":"connect";let w;function _(e){return t=>{v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(g,O),y(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&d)return y(m.authorizationError);m.setTimeout(f),y(null,m)}v.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(g,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!g[o.mechanism])return void r(new i(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||h(n),compression:r},s=e.credentials;if(s){if(s.mechanism.match(/DEFAULT/i)&&s.username)return Object.assign(o,{saslSupportedMechs:`${s.source}.${s.username}`}),void g["scram-sha-256"].prepare(o,e,t);return void g[s.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const p=u.result;if(0===p.ok)return void r(new i(p));const h=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=f;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${f} (MongoDB ${d})`;return new i(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${y})`;return new i(o)}(p,t);if(h)r(h);else{if(!function(e){return!(e instanceof s)}(e)&&p.compression){const n=c.compression.filter(e=>-1!==p.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=p,e.lastIsMasterMS=(new Date).getTime()-l,p.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:p});const t=o.resolveAuthMechanism(p);g[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new p(r,e),e,n)})}},function(e,t,n){"use strict";function r(e){this._head=0,this._tail=0,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,s=this._list[t];if(e0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return s}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var s=this.size(),i=this._list.length;if(!(r>=s||r<-s||t<1)){if(r<0&&(r+=s),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=s)return n=this.toArray(),this.clear(),n;var a;for(r+t>s&&(t=s-r),n=new Array(t),a=0;a0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+i&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(r0;a--)this.unshift(this._list[r=r-1+i&this._capacityMask]);for(r=this._head-1+i&this._capacityMask;o>0;)this._list[r=r-1+i&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+i&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+i&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=i>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,s,i,a=arguments.length,c=this._list.length,u=2;if(!r||n0&&(this._head=this._head+n+c&this._capacityMask)):(i=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{var l=(s=new Array(r-(n+t))).length;for(o=0;othis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(77),o=n(10),s=n(112).isResumableError,i=n(1).MongoError,a=n(25),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,p=n(0).now,h=n(0).calculateDurationInMs,f=n(63),d=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],y=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),g={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of y)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function S(e,t){const n={fullDocument:t.fullDocument||"default"};v(n,t,m),e.type===g.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=v({},t,y),s=new b(e.topology,new f(e.parent,r,t),o);if(c(s,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&s.on("data",(function(t){w(e,t)})),s.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=s.stream(e.streamOptions);for(let n in e.pipeDestinations)t.pipe(n)}return s}function v(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new i("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&s(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=p());const o=n.start||p(),s=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():h(o)>s?r(new i("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=S(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new i("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new i("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[d].push(t)}function T(e,t){for(;e[d].length;){const n=e[d].pop();if(e.isClosed()&&!t)return void n(new i("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const s=n(47),i=n(65),a=n(62);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof s)this.type=g.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof i)this.type=g.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=g.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[d]=new r,this.cursor=S(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[d].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(1).BSON.Long,o=n(1).MongoError,s=n(1).BSON.ObjectID,i=n(1).BSON,a=n(1).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,p=n(0).applyWriteConcern,h=n(0).executeLegacyOperation,f=n(0).isPromiseLike,d=n(0).hasAtomicOperators,m=n(4).maxWireVersion,y=new i([i.Binary,i.Code,i.DBRef,i.Decimal128,i.Double,i.Int32,i.Long,i.Map,i.MaxKey,i.MinKey,i.ObjectId,i.BSONRegExp,i.Symbol,i.Timestamp]);class g{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return ee.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,v(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:y,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(25),s=n(20).CursorState,i=n(5).deprecate;class a extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,i(a.prototype.geoNear,"The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2."),e.exports=a},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(1).MongoError,s=n(25),i=n(20).CursorState;class a extends s{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==i.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?i(e,t):n.ok?i(e,null,!0):void i(e,null,!1))}}s(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,s;e.exports={loadCollection:function(){return r||(r=n(47)),r},loadCursor:function(){return o||(o=n(25)),o},loadDb:function(){return s||(s=n(65)),s}}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=n(228);function s(e){if(!o.existy(e))return null;if(o.not.string(e))throw new TypeError('Expected a string, got "'.concat(r(e),'"'));return e.split(",").map((function(e){var t=e.trim();if(t.includes(":")){var n=t.split(":");if(2===n.length)return n[0]}return t})).find(o.ip)}function i(e){if(e.headers){if(o.ip(e.headers["x-client-ip"]))return e.headers["x-client-ip"];var t=s(e.headers["x-forwarded-for"]);if(o.ip(t))return t;if(o.ip(e.headers["cf-connecting-ip"]))return e.headers["cf-connecting-ip"];if(o.ip(e.headers["fastly-client-ip"]))return e.headers["fastly-client-ip"];if(o.ip(e.headers["true-client-ip"]))return e.headers["true-client-ip"];if(o.ip(e.headers["x-real-ip"]))return e.headers["x-real-ip"];if(o.ip(e.headers["x-cluster-client-ip"]))return e.headers["x-cluster-client-ip"];if(o.ip(e.headers["x-forwarded"]))return e.headers["x-forwarded"];if(o.ip(e.headers["forwarded-for"]))return e.headers["forwarded-for"];if(o.ip(e.headers.forwarded))return e.headers.forwarded}if(o.existy(e.connection)){if(o.ip(e.connection.remoteAddress))return e.connection.remoteAddress;if(o.existy(e.connection.socket)&&o.ip(e.connection.socket.remoteAddress))return e.connection.socket.remoteAddress}return o.existy(e.socket)&&o.ip(e.socket.remoteAddress)?e.socket.remoteAddress:o.existy(e.info)&&o.ip(e.info.remoteAddress)?e.info.remoteAddress:o.existy(e.requestContext)&&o.existy(e.requestContext.identity)&&o.ip(e.requestContext.identity.sourceIp)?e.requestContext.identity.sourceIp:null}e.exports={getClientIpFromXForwardedFor:s,getClientIp:i,mw:function(e){var t=o.not.existy(e)?{}:e;if(o.not.object(t))throw new TypeError("Options must be an object!");var n=t.attributeName||"clientIp";return function(e,t,r){var o=i(e);Object.defineProperty(e,n,{get:function(){return o},configurable:!0}),r()}}}},function(e,t,n){"use strict";const r=n(230),o=n(131),s=n(231);function i(e,t){switch(o(e)){case"object":return function(e,t){if("function"==typeof t)return t(e);if(t||s(e)){const n=new e.constructor;for(let r in e)n[r]=i(e[r],t);return n}return e}(e,t);case"array":return function(e,t){const n=new e.constructor(e.length);for(let r=0;r{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));const s=n.opCode===m?u:c;e.emit("message",new s(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=v++,this.options=t,this.logger=f("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,i,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&C(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new p(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=g.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,x(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=g.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&nt.length)e.buffer=g.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=g.alloc(0);else if(n>4&&ne.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=g.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),x(e,r)}}else e.stubBuffer=g.alloc(t.length),t.copy(e.stubBuffer,0),t=g.alloc(0)}}(this)),O&&(i=this.id,a=this,T[i]=a,_&&_.addConnection(i,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&C(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),null==e&&(e=new h(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function p(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new h(t)):u(void 0,new S(t,this,e))}o.setSocketTimeout(s),E.forEach(e=>o.once(e,l)),o.on("message",p),o.write(a.toBin())}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(34).ServerDescription,s=n(93),i=n(15).TopologyType,a=s.MIN_SUPPORTED_SERVER_VERSION,c=s.MAX_SUPPORTED_SERVER_VERSION,u=s.MIN_SUPPORTED_WIRE_VERSION,l=s.MAX_SUPPORTED_WIRE_VERSION;class p{constructor(e,t,n,o,s,p,h){h=h||{},this.type=e||i.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=s||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0,this.localThresholdMS=h.localThresholdMS||0,this.commonWireVersion=p||null,Object.defineProperty(this,"options",{value:h,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersione.isReadable);this.logicalSessionTimeoutMinutes=f.reduce((e,t)=>null==t.logicalSessionTimeoutMinutes?null:null==e?t.logicalSessionTimeoutMinutes:Math.min(e,t.logicalSessionTimeoutMinutes),null)}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new p(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,s=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&s&&e.setName!==s&&(e=new o(t,null));const l=e.type;let d=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),d.set(t,e),n===i.Single)return new p(i.Single,d,s,a,c,u,this.options);if(n===i.Unknown&&(l===r.Standalone&&1!==this.servers.size?d.delete(t):n=function(e){if(e===r.Standalone)return i.Single;if(e===r.Mongos)return i.Sharded;if(e===r.RSPrimary)return i.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return i.Unknown;return i.ReplicaSetNoPrimary}(l)),n===i.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&d.delete(t),n===i.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&d.delete(t),l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=i.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(d,s,e);n=t[0],s=t[1]}if(n===i.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)d.delete(t),n=f(d);else if(l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return f(e)}(d,s,e):f(d);return new p(n,d,s,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function h(e,t,n,s,i){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[f(e),t,s,i];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(s&&i&&(s>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(i,a)>0))return e.set(n.address,new o(n.address)),[f(e),t,s,i];i=n.electionId}null!=n.setVersion&&(null==s||n.setVersion>s)&&(s=n.setVersion);for(const t of e.keys()){const s=e.get(t);if(s.type===r.RSPrimary&&s.address!==n.address){e.set(t,new o(s.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[f(e),t,s,i]}function f(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return i.ReplicaSetWithPrimary;return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:p}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(35).Msg,o=n(22).KillCursor,s=n(22).GetMore,i=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],p=e=>e.ns.split(".")[1],h=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,f=(e,t)=>a.has(e)?{}:t,d={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},y=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],g=e=>{if(e instanceof s)return{getMore:e.cursorId,collection:p(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:p(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:p(e)},Object.keys(d).forEach(n=>{void 0!==e.query[n]&&(t[d[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),y.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof s?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,S=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:h(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=g(t),r=c(n),o=S(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),reply:f(s,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),failure:f(s,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(97),o=n(98),s=n(99),i=n(100),a=n(58).ScramSHA1,c=n(58).ScramSHA256,u=n(152);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(21),o=n(30).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,s=o.username,i=o.password,a=o.source;n.command(a+".$cmd",{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(s+":mongo:"+i,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+s+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:s,nonce:c,key:u};n.command(a+".$cmd",l,t)})}}},function(e,t,n){"use strict";const r=n(30).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.apply(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(30).AuthProvider,s=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,i=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new s(`\0${o}\0${i}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(30).AuthProvider,o=n(4).retrieveKerberos;let s;e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(null==s)try{s=o()}catch(e){return t(e,null)}const i=r.username,a=r.password,c=r.mechanismProperties,u=c.gssapiservicename||c.gssapiServiceName||"mongodb",l=new(0,s.processes.MongoAuthProcess)(n.host,n.port,u,c);l.init(i,a,e=>{if(e)return t(e,!1);l.transition("",(e,r)=>{if(e)return t(e,!1);const o={saslStart:1,mechanism:"GSSAPI",payload:r,autoAuthorize:1};n.command("$external.$cmd",o,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,n)=>{if(e)return t(e,!1);const r=n.result;l.transition(null,e=>{if(e)return t(e,null);t(null,r)})})})})})})})})}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";const r=n(156);e.exports={insert:function(e,t,n,o,s){r(e,"insert","documents",t,n,o,s)},update:function(e,t,n,o,s){r(e,"update","updates",t,n,o,s)},remove:function(e,t,n,o,s){r(e,"delete","deletes",t,n,o,s)},killCursors:n(157),getMore:n(158),query:n(159),command:n(42)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(10),o=n(166),s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(2).MongoNetworkTimeoutError,c=n(2).MongoWriteConcernError,u=n(74),l=n(174).StreamDescription,p=n(103),h=n(94),f=n(31).updateSessionFromResponse,d=n(4).uuidV4,m=n(0).now,y=n(0).calculateDurationInMs,g=Symbol("stream"),b=Symbol("queue"),S=Symbol("messageStream"),v=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),E=Symbol("autoEncrypter");function C(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:x.bind(e),isConnected:()=>!0}}};return e[E]&&(t.autoEncrypter=e[E]),t}function x(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[g].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new h.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[S].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return d().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[v]=t.generation,this[w]=m(),t.autoEncrypter&&(this[E]=t.autoEncrypter),this[b]=new Map,this[S]=new o(t),this[S].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[g].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new s(e))}if(e.documents[0]){const o=e.documents[0],i=t.session;if(i&&f(i,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new s(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[g]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new i(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[S]),this[S].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[v]||0}get idleTime(){return y(this[w])}get clusterTime(){return this[_]}get stream(){return this[g]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[g]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[g].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[g].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){p.command(C(this),e,t,n,r)}query(e,t,n,r,o){p.query(C(this),e,t,n,r,o)}getMore(e,t,n,r,o){p.getMore(C(this),e,t,n,r,o)}killCursors(e,t,n){p.killCursors(C(this),e,t,n)}insert(e,t,n,r){p.insert(C(this),e,t,n,r)}update(e,t,n,r){p.update(C(this),e,t,n,r)}remove(e,t,n,r){p.remove(C(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(60);e.exports=b;var o,s=n(169);b.ReadableState=g;n(10).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=n(107),c=n(16).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(44));l.inherits=n(45);var p=n(5),h=void 0;h=p&&p.debuglog?p.debuglog("stream"):function(){};var f,d=n(171),m=n(108);l.inherits(b,a);var y=["error","close","destroy","pause","resume"];function g(e,t){e=e||{};var r=t instanceof(o=o||n(37));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var s=e.highWaterMark,i=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=s||0===s?s:r&&(i||0===i)?i:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=n(110).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(37),!(this instanceof b))return new b(e);this._readableState=new g(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function S(e,t,n,r,o){var s,i=e._readableState;null===t?(i.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,i)):(o||(s=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(i,t)),s?e.emit("error",s):i.objectMode||t&&t.length>0?("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?i.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):v(e,i,t,!0):i.ended?e.emit("error",new Error("stream.push() after EOF")):(i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?v(e,i,t,!1):T(e,i)):v(e,i,t,!1))):r||(i.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(h("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){h("emit readable"),e.emit("readable"),A(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(E,e,t))}function E(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;es.length?s.length:e;if(i===s.length?o+=s:o+=s.slice(0,e),0===(e-=i)){i===s.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(i));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var s=r.data,i=e>s.length?s.length:e;if(s.copy(n,n.length-e,0,i),0===(e-=i)){i===s.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(i));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function I(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return h("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?I(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&I(this),null;var r,o=t.needReadable;return h("need readable",o),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&I(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,h("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){h("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),e.removeListener("close",y),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",d),p=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){h("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,A(e))}}(n);e.on("drain",l);var p=!1;var f=!1;function d(t){h("ondata"),f=!1,!1!==e.write(t)||f||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!p&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,f=!0),n.pause())}function m(t){h("onerror",t),b(),e.removeListener("error",m),0===i(e,"error")&&e.emit("error",t)}function y(){e.removeListener("finish",g),b()}function g(){h("onfinish"),e.removeListener("close",y),b()}function b(){h("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",y),e.once("finish",g),e.emit("pipe",n),o.flowing||(h("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s-1?setImmediate:r.nextTick;y.WritableState=m;var a=Object.create(n(44));a.inherits=n(45);var c={deprecate:n(172)},u=n(107),l=n(16).Buffer,p=global.Uint8Array||function(){};var h,f=n(108);function d(){}function m(e,t){s=s||n(37),e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var p=!1===e.decodeStrings;this.decodeStrings=!p,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,s=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,s){--t.pendingcb,n?(r.nextTick(s,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(s(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,s);else{var a=v(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||S(e,n),o?i(b,e,n,a,s):b(e,n,a,s)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function y(e){if(s=s||n(37),!(h.call(y,this)||this instanceof s))return new y(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function g(e,t,n,r,o,s,i){t.writelen=r,t.writecb=i,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function S(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),i=t.corkedRequestsFree;i.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,g(e,t,!0,t.length,s,"",i.finish),t.pendingcb++,t.lastBufferedRequest=null,i.next?(t.corkedRequestsFree=i.next,i.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,p=n.callback;if(g(e,t,!1,t.objectMode?1:u.length,u,l,p),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function v(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=v(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(y,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===y&&(e&&e._writableState instanceof m)}})):h=function(e){return e instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(e,t,n){var o,s=this._writableState,i=!1,a=!s.objectMode&&(o=e,l.isBuffer(o)||o instanceof p);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=s.defaultEncoding),"function"!=typeof n&&(n=d),s.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var s=!0,i=!1;return null===n?i=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(i=new TypeError("Invalid non-string/buffer chunk")),i&&(e.emit("error",i),r.nextTick(o,i),s=!1),s}(this,s,e,n))&&(s.pendingcb++,i=function(e,t,n,r,o,s){if(!n){var i=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==i&&(n=!0,o="buffer",r=i)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),y.prototype.destroy=f.destroy,y.prototype._undestroy=f.undestroy,y.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(16).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=p,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function i(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return o>0&&(e.lastNeed=o-1),o;if(--r=0)return o>0&&(e.lastNeed=o-2),o;if(--r=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=i;var r=n(37),o=Object.create(n(44));function s(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(1).MongoError,i=n(3).OperationBase;e.exports=class extends i{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let i=this.options;t.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===i.ordered||null==i.ordered?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let c=!1;try{for(let e=0;e{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends s{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=i(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,s.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(21),a=n(0).handleCallback,c=n(0).toError;class u extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=Array.isArray(r.roles)?r.roles:[];0===o.length&&console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:s};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}s(u,r.WRITE_OPERATION),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError,i=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new i("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new s("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback,a=n(29);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return i(e,t,null);i(e,t,!!n.ok)})}}s(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyWriteConcern,s=n(0).checkCollectionName,i=n(14).executeDbAdminCommand,a=n(0).handleCallback,c=n(85).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();s(n);const p={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(p,{db:t.s.db,collection:t},r),i(t.s.db.admin().s.db,p,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(118),s=n(119),i=n(120),a=n(210),c=n(211),u=n(43);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new s(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,s){const i=Array.prototype.slice.call(arguments,2);s="function"==typeof i[i.length-1]?i.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=i.length?i.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,s)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const s=new i(this.s.db,e,t);return u(this.s.db.s.topology,s,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(1).Topology,o=n(32).ServerCapabilities,s=n(25),i=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:s,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=i(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=i(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(1).Logger,s=n(1).MongoCredentials,i=n(1).MongoError,a=n(125),c=n(123),u=n(1).parseConnectionString,l=n(36),p=n(1).ReadPreference,h=n(126),f=n(66),d=n(1).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,y=n(40),g=n(11).retrieveBSON(),b=n(61).CMAP_EVENT_NAMES;let S;const v=r(n(217),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),w={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},_=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],O=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),T=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],E=["native_parser"],C=["server","replset","replSet","mongos","db"];const x=T.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function A(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function N(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new d(t.s.coreTopology))}function I(e,t){let r=(S||(S=n(62)),S);const o=[];return e instanceof r&&_.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}const k=r(()=>{},"current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.");function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function D(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const s={};"unified"===t&&(s.createServers=!1);const u=F(r,s);if(null!=r.autoEncryption){let t;try{let e=n(127);"function"!=typeof e.extension&&o(new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`")),t=e.extension(n(17)).AutoEncrypter}catch(e){return void o(e)}const s=Object.assign({bson:r.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp])},r.autoEncryption);r.autoEncrypter=new t(e,s)}let l;"mongos"===t?l=new a(u,r):"replicaset"===t?l=new h(u,r):"unified"===t&&(l=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),A(e,l),U(e,l),N(e,l),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):l.connect(r,e=>{if(e)return l.close(!0),void o(e);o(void 0,l)})}):l.connect(r,e=>{if(e)return l.close(!0),o(e);o(void 0,l)})}function B(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"];for(const o in t)-1!==r.indexOf(o.toLowerCase())?e[o]=t[o]:-1!==n.indexOf(o.toLowerCase())?e=j(e,t[o],!1):!t[o]||"object"!=typeof t[o]||Buffer.isBuffer(t[o])||Array.isArray(t[o])?e[o]=t[o]:e=j(e,t[o],!0);return e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!O.has(c))throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new s({mechanism:w[c],mechanismProperties:u,source:o,username:t,password:n})}function L(e){return j(B({},e),e,!1)}function j(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=j(e,t[r],n):e[r]=t[r];return e}function U(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(b).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function z(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=x[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;return(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS),e.srvHost&&(t.srvHost=e.srvHost),t}function F(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new p(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=36e4),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new f(t.domain_socket,27017,e):new f(t.host,t.port,e))}e.exports={validOptions:function(e){const t=T.concat(C);for(const n in e)if(-1===E.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new i(`option ${n} is not supported`);console.warn(`the options [${n}] is not supported`)}-1!==C.indexOf(n)&&console.warn(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${T}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let s=!1;const c=o("MongoClient",n);if(t instanceof f||t instanceof h||t instanceof a)return function(e,t,n,r){N(e,t),A(e,t),U(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new p(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,d=l?z:L;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new i(o));s&&e.emit("authenticated",null,!0),r(t,n)}(l?u:v)(t,n,(t,o)=>{if(t)return r(t);const i=d(o),a=B(i,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=36e4),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,null!=a.journal&&(a.j=a.journal,a.journal=void 0),function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,0===i.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{s=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?D(e,"unified",a,m):(k(),a.replicaSet||a.rs_name?D(e,"replicaset",a,m):i.servers.length>1?D(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=F(t)[0],o=I(e,r);r.connect(t,(s,i)=>{if(s)return r.close(!0),n(s);!function(e){_.forEach(t=>e.removeAllListeners(t))}(r),U(e,r),A(e,r);const a=i.lastIsMaster();if(N(e,i),a&&"isdbgrid"===a.msg)return i.close(),D(e,"mongos",t,n);!function(e,t){for(let n=0;n0?t.socketOptions:t;g=l(g,b),this.s={coreTopology:new s(m,g),sCapabilities:null,debug:g.debug,storeOptions:r,clonedOptions:g,store:d,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",s("joined")),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";const r=n(66),o=n(25),s=n(1).MongoError,i=n(32).TopologyBase,a=n(32).Store,c=n(1).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,p=n(0).filterOptions,h=n(0).mergeOptions;var f=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class d extends i{constructor(e,t){super();var n=this;t=p(t=t||{},f);for(var i=0;i0?t.socketOptions:t;g=l(g,b);var S=new c(y,g);S.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:S,sCapabilities:null,tag:t.tag,storeOptions:d,clonedOptions:g,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},g.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return S}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,s=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("ping",s("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var i=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,i)})),n.s.coreTopology.removeListener("connect",i),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";let r;function o(){return r||(r=i(n(17))),r}const s=n(67).MongoCryptError;function i(e){const t={mongodb:e};return t.stateMachine=n(218)(t),t.autoEncrypter=n(219)(t),t.clientEncryption=n(223)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:s}}e.exports={extension:i,MongoCryptError:s,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(40),s=n(39),i=n(220),a=s.join,c=s.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||s.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=s.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,i=require,c=[],u=0,p=e.try.length;u{let s;try{s=r.createHmac(e,t).update(n).digest()}catch(e){return e}return s.copy(o),s.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let s;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},aes256CbcDecryptHook:function(e,t,n,o){let s;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length}}},function(e,t,n){"use strict";var r=n(1).BSON.Binary,o=n(1).BSON.ObjectID,s=n(16).Buffer,i=function(e,t,n){if(!(this instanceof i))return new i(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=s.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=s.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!s.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};i.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},i.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},i.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=s.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},i.prototype.eof=function(){return this.internalPosition===this.length()},i.prototype.getc=function(){return this.read(1)},i.prototype.rewind=function(){this.internalPosition=0,this.data=new r},i.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var s={upsert:!0};for(var i in e)s[i]=e[i];for(i in n.writeConcern)s[i]=n.writeConcern[i];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var i in n.writeConcern)r[i]=n.writeConcern[i];o.replaceOne({_id:n.objectId},e,s,(function(e){t(e,n)}))})):t(null,n)}))},i.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},i.prototype.length=function(){return this.data.length()},Object.defineProperty(i.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),i.DEFAULT_CHUNK_SIZE=261120,e.exports=i},function(e,t){var n=Object.prototype.toString;function r(e){return"function"==typeof e.constructor?e.constructor.name:null}e.exports=function(e){if(void 0===e)return"undefined";if(null===e)return"null";var t=typeof e;if("boolean"===t)return"boolean";if("string"===t)return"string";if("number"===t)return"number";if("symbol"===t)return"symbol";if("function"===t)return"GeneratorFunction"===r(e)?"generatorfunction":"function";if(function(e){return Array.isArray?Array.isArray(e):e instanceof Array}(e))return"array";if(function(e){if(e.constructor&&"function"==typeof e.constructor.isBuffer)return e.constructor.isBuffer(e);return!1}(e))return"buffer";if(function(e){try{if("number"==typeof e.length&&"function"==typeof e.callee)return!0}catch(e){if(-1!==e.message.indexOf("callee"))return!0}return!1}(e))return"arguments";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";if(function(e){return e instanceof RegExp||"string"==typeof e.flags&&"boolean"==typeof e.ignoreCase&&"boolean"==typeof e.multiline&&"boolean"==typeof e.global}(e))return"regexp";switch(r(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(function(e){return"function"==typeof e.throw&&"function"==typeof e.return&&"function"==typeof e.next}(e))return"generator";switch(t=n.call(e)){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")}},function(e,t,n){"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */e.exports=function(e,t){if("string"==typeof e)return c(e);if("number"==typeof e)return a(e,t);return null},e.exports.format=a,e.exports.parse=c;var r=/\B(?=(\d{3})+(?!\d))/g,o=/(?:\.0*|(\.[^0]+)0+)$/,s={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},i=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function a(e,t){if(!Number.isFinite(e))return null;var n=Math.abs(e),i=t&&t.thousandsSeparator||"",a=t&&t.unitSeparator||"",c=t&&void 0!==t.decimalPlaces?t.decimalPlaces:2,u=Boolean(t&&t.fixedDecimals),l=t&&t.unit||"";l&&s[l.toLowerCase()]||(l=n>=s.pb?"PB":n>=s.tb?"TB":n>=s.gb?"GB":n>=s.mb?"MB":n>=s.kb?"KB":"B");var p=(e/s[l.toLowerCase()]).toFixed(c);return u||(p=p.replace(o,"$1")),i&&(p=p.replace(r,i)),p+a+l}function c(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var t,n=i.exec(e),r="b";return n?(t=parseFloat(n[1]),r=n[4].toLowerCase()):(t=parseInt(e,10),r="b"),Math.floor(s[r]*t)}},function(e,t,n){"use strict";const r=n(233);e.exports=e=>{const t=r(0,e.length-1);return()=>e[t()]}},function(e,t,n){"use strict";var r=n(70),o=n(33),s=n(48),i=n(49),a=n(50),c=n(51),u=n(52),l=n(71),p=n(53),h=n(54),f=n(55),d=n(56),m=n(57),y=n(38),g=n(135),b=n(136),S=n(138),v=n(28),w=v.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,s="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.lengthe.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,i=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!i)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,p=null!=n.promoteBuffers&&n.promoteBuffers,h=null==n.promoteLongs||n.promoteLongs,f=null==n.promoteValues||n.promoteValues,d=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var y=r?[]:{},g=0;;){var b=e[t++];if(0===b)break;for(var S=t;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var v=r?g++:e.toString("utf8",t,S);if(t=S+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),y[v]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===f)y[v]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)y[v]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===f)y[v]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)y[v]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;y[v]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");y[v]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var E=t,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(C<=0||C>e.length-t)throw new Error("bad embedded document length in bson");y[v]=u?e.slice(t,t+C):deserializeObject(e,E,n,!1),t+=C}else if(b===BSON.BSON_DATA_ARRAY){E=t;var x=n,A=t+(C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[v]){for(var N in x={},n)x[N]=n[N];x.raw=!0}if(y[v]=deserializeObject(e,E,x,!0),0!==e[(t+=C)-1])throw new Error("invalid array terminator byte");if(t!==A)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)y[v]=void 0;else if(b===BSON.BSON_DATA_NULL)y[v]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var I=new Long(O,T);y[v]=h&&!0===f&&I.lessThanOrEqual(JS_INT_MAX_LONG)&&I.greaterThanOrEqual(JS_INT_MIN_LONG)?I.toNumber():I}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);y[v]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,D=R,B=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(B===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>D-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(RD-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,S);for(S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var j=e.toString("utf8",t,S);t=S+1;var U=new Array(j.length);for(S=0;S=e.length)throw new Error("Bad BSON Document: illegal CString");for(L=e.toString("utf8",t,S),S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");j=e.toString("utf8",t,S),t=S+1,y[v]=new BSONRegExp(L,j)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,y[v]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)y[v]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)y[v]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var z=e.toString("utf8",t,t+w-1);if(o)if(s){var F=i?a(z):z;y[v]=isolateEvalWithHash(functionCache,F,z,y)}else y[v]=isolateEval(z);else y[v]=new Code(z);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(W<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");z=e.toString("utf8",t,t+w-1),E=t+=w,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,E,n,!1);if(t+=C,W<8+C+w)throw new Error("code_w_scope total size is to short, truncating scope");if(W>8+C+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(s?(F=i?a(z):z,y[v]=isolateEvalWithHash(functionCache,F,z,y)):y[v]=isolateEval(z),y[v].scope=q):y[v]=new Code(z,q)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+v+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var $=e.toString("utf8",t,t+w-1);t+=w;var H=utils.allocBuffer(12);e.copy(H,0,t,t+12),_=new ObjectID(H),t+=12;var V=$.split("."),Y=V.shift(),G=V.join(".");y[v]=new DBRef(G,_,Y)}}if(m!==t-d){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=y.$id&&(y=new DBRef(y.$ref,y.$id,y.$db)),y},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(137).writeIEEE754,o=n(33).Long,s=n(70),i=n(38).Binary,a=n(28).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},p=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},h=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var s=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+s+1)-1]=0;var i=e.write(n,r+4,"utf8");return e[r+3]=i+1>>24&255,e[r+2]=i+1>>16&255,e[r+1]=i+1>>8&255,e[r]=i+1&255,r=r+4+i,e[r++]=0,r},f=function(e,t,n,s,i){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[s++]=R.BSON_DATA_INT;var a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8");s+=a,e[s++]=0,e[s++]=255&n,e[s++]=n>>8&255,e[s++]=n>>16&255,e[s++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;else{e[s++]=R.BSON_DATA_LONG,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[s++]=255&u,e[s++]=u>>8&255,e[s++]=u>>16&255,e[s++]=u>>24&255,e[s++]=255&l,e[s++]=l>>8&255,e[s++]=l>>16&255,e[s++]=l>>24&255}else e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;return s},d=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},y=function(e,t,n,r,s){e[r++]=R.BSON_DATA_DATE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=o.fromNumber(n.getTime()),a=i.getLowBits(),c=i.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},g=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.length;return e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,s),r+=s},_=function(e,t,n,r,o,s,i,a,c,u){for(var l=0;l>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,r},E=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},C=function(e,t,n,o,s){return e[o++]=R.BSON_DATA_NUMBER,o+=s?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},x=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_CODE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},A=function(e,t,n,r,o,s,i,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,p="string"==typeof n.code?n.code:n.code.toString();r+=4;var h=e.write(p,r+4,"utf8")+1;e[r]=255&h,e[r+1]=h>>8&255,e[r+2]=h>>16&255,e[r+3]=h>>24&255,e[r+4+h-1]=0,r=r+h+4;var f=M(e,n.scope,o,r,s+1,i,a);r=f-1;var d=f-l;e[l++]=255&d,e[l++]=d>>8&255,e[l++]=d>>16&255,e[l++]=d>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,p=n.code.toString();var m=e.write(p,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},N=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.value(!0),a=n.position;return n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),s.copy(e,r,0,n.position),r+=n.position},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=e.write(n.value,r+4,"utf8")+1;return e[r]=255&s,e[r+1]=s>>8&255,e[r+2]=s>>16&255,e[r+3]=s>>24&255,r=r+4+s-1,e[r++]=0,r},k=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_OBJECT,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,s):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,s))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,i,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var D=0;D>8&255,e[r++]=F>>16&255,e[r++]=F>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var s,i,a="big"===n,c=8*o-r-1,u=(1<>1,p=-7,h=a?0:o-1,f=a?1:-1,d=e[t+h];for(h+=f,s=d&(1<<-p)-1,d>>=-p,p+=c;p>0;s=256*s+e[t+h],h+=f,p-=8);for(i=s&(1<<-p)-1,s>>=-p,p+=r;p>0;i=256*i+e[t+h],h+=f,p-=8);if(0===s)s=1-l;else{if(s===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),s-=l}return(d?-1:1)*i*Math.pow(2,s-r)},t.writeIEEE754=function(e,t,n,r,o,s){var i,a,c,u="big"===r,l=8*s-o-1,p=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=u?s-1:0,m=u?-1:1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=p):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=p?(a=0,i=p):i+h>=1?(a=(t*c-1)*Math.pow(2,o),i+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;e[n+d]=255&a,d+=m,a/=256,o-=8);for(i=i<0;e[n+d]=255&i,d+=m,i/=256,l-=8);e[n+d-m]|=128*y}},function(e,t,n){"use strict";var r=n(33).Long,o=n(48).Double,s=n(49).Timestamp,i=n(50).ObjectID,a=n(52).Symbol,c=n(51).BSONRegExp,u=n(53).Code,l=n(54),p=n(55).MinKey,h=n(56).MaxKey,f=n(57).DBRef,d=n(38).Binary,m=n(28).normalizedFunctionString,y=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return g||!S?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof p||t instanceof h||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof i||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof s||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+y(t.scope,n,S):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof d||"Binary"===t._bsontype)return t.sub_type===d.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof f||"DBRef"===t._bsontype){var v={$ref:t.namespace,$id:t.oid};return null!=t.db&&(v.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+y(v,n,S)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+y(t,n,S)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+y(t.scope,n,S);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=y},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";var r=n(39),o=n(141);e.exports=function(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected `fromDir` and `moduleId` to be a string");e=r.resolve(e);var n=r.join(e,"noop.js");try{return o._resolveFilename(t,{id:n,filename:n,paths:o._nodeModulePaths(e)})}catch(e){return null}}},function(e,t){e.exports=require("module")},function(e,t){var n;t=e.exports=V,n="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var r=Number.MAX_SAFE_INTEGER||9007199254740991,o=t.re=[],s=t.src=[],i=0,a=i++;s[a]="0|[1-9]\\d*";var c=i++;s[c]="[0-9]+";var u=i++;s[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var l=i++;s[l]="("+s[a]+")\\.("+s[a]+")\\.("+s[a]+")";var p=i++;s[p]="("+s[c]+")\\.("+s[c]+")\\.("+s[c]+")";var h=i++;s[h]="(?:"+s[a]+"|"+s[u]+")";var f=i++;s[f]="(?:"+s[c]+"|"+s[u]+")";var d=i++;s[d]="(?:-("+s[h]+"(?:\\."+s[h]+")*))";var m=i++;s[m]="(?:-?("+s[f]+"(?:\\."+s[f]+")*))";var y=i++;s[y]="[0-9A-Za-z-]+";var g=i++;s[g]="(?:\\+("+s[y]+"(?:\\."+s[y]+")*))";var b=i++,S="v?"+s[l]+s[d]+"?"+s[g]+"?";s[b]="^"+S+"$";var v="[v=\\s]*"+s[p]+s[m]+"?"+s[g]+"?",w=i++;s[w]="^"+v+"$";var _=i++;s[_]="((?:<|>)?=?)";var O=i++;s[O]=s[c]+"|x|X|\\*";var T=i++;s[T]=s[a]+"|x|X|\\*";var E=i++;s[E]="[v=\\s]*("+s[T]+")(?:\\.("+s[T]+")(?:\\.("+s[T]+")(?:"+s[d]+")?"+s[g]+"?)?)?";var C=i++;s[C]="[v=\\s]*("+s[O]+")(?:\\.("+s[O]+")(?:\\.("+s[O]+")(?:"+s[m]+")?"+s[g]+"?)?)?";var x=i++;s[x]="^"+s[_]+"\\s*"+s[E]+"$";var A=i++;s[A]="^"+s[_]+"\\s*"+s[C]+"$";var N=i++;s[N]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var I=i++;s[I]="(?:~>?)";var k=i++;s[k]="(\\s*)"+s[I]+"\\s+",o[k]=new RegExp(s[k],"g");var M=i++;s[M]="^"+s[I]+s[E]+"$";var R=i++;s[R]="^"+s[I]+s[C]+"$";var D=i++;s[D]="(?:\\^)";var B=i++;s[B]="(\\s*)"+s[D]+"\\s+",o[B]=new RegExp(s[B],"g");var P=i++;s[P]="^"+s[D]+s[E]+"$";var L=i++;s[L]="^"+s[D]+s[C]+"$";var j=i++;s[j]="^"+s[_]+"\\s*("+v+")$|^$";var U=i++;s[U]="^"+s[_]+"\\s*("+S+")$|^$";var z=i++;s[z]="(\\s*)"+s[_]+"\\s*("+v+"|"+s[E]+")",o[z]=new RegExp(s[z],"g");var F=i++;s[F]="^\\s*("+s[E]+")\\s+-\\s+("+s[E]+")\\s*$";var W=i++;s[W]="^\\s*("+s[C]+")\\s+-\\s+("+s[C]+")\\s*$";var q=i++;s[q]="(<|>)?=?\\s*\\*";for(var $=0;$<35;$++)n($,s[$]),o[$]||(o[$]=new RegExp(s[$]));function H(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?o[w]:o[b]).test(e))return null;try{return new V(e,t)}catch(e){return null}}function V(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof V))return new V(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var s=e.trim().match(t.loose?o[w]:o[b]);if(!s)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);-1===n&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,n,r){"string"==typeof n&&(r=n,n=void 0);try{return new V(e,n).inc(t,r).version}catch(e){return null}},t.diff=function(e,t){if(Z(e,t))return null;var n=H(e),r=H(t),o="";if(n.prerelease.length||r.prerelease.length){o="pre";var s="prerelease"}for(var i in n)if(("major"===i||"minor"===i||"patch"===i)&&n[i]!==r[i])return o+i;return s},t.compareIdentifiers=G;var Y=/^[0-9]+$/;function G(e,t){var n=Y.test(e),r=Y.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e0}function J(e,t,n){return K(e,t,n)<0}function Z(e,t,n){return 0===K(e,t,n)}function Q(e,t,n){return 0!==K(e,t,n)}function ee(e,t,n){return K(e,t,n)>=0}function te(e,t,n){return K(e,t,n)<=0}function ne(e,t,n,r){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return Z(e,n,r);case"!=":return Q(e,n,r);case">":return X(e,n,r);case">=":return ee(e,n,r);case"<":return J(e,n,r);case"<=":return te(e,n,r);default:throw new TypeError("Invalid operator: "+t)}}function re(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof re){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof re))return new re(e,t);n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===oe?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}t.rcompareIdentifiers=function(e,t){return G(t,e)},t.major=function(e,t){return new V(e,t).major},t.minor=function(e,t){return new V(e,t).minor},t.patch=function(e,t){return new V(e,t).patch},t.compare=K,t.compareLoose=function(e,t){return K(e,t,!0)},t.rcompare=function(e,t,n){return K(t,e,n)},t.sort=function(e,n){return e.sort((function(e,r){return t.compare(e,r,n)}))},t.rsort=function(e,n){return e.sort((function(e,r){return t.rcompare(e,r,n)}))},t.gt=X,t.lt=J,t.eq=Z,t.neq=Q,t.gte=ee,t.lte=te,t.cmp=ne,t.Comparator=re;var oe={};function se(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof se)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new se(e.raw,t);if(e instanceof re)return new se(e.value,t);if(!(this instanceof se))return new se(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ie(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,n,r,o,s,i,a,c,u,l,p,h){return((t=ie(n)?"":ie(r)?">="+n+".0.0":ie(o)?">="+n+"."+r+".0":">="+t)+" "+(a=ie(c)?"":ie(u)?"<"+(+c+1)+".0.0":ie(l)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+l+"-"+p:"<="+a)).trim()}function ce(e,t,r){for(var o=0;o0){var s=e[o].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}function ue(e,t,n){try{t=new se(t,n)}catch(e){return!1}return t.test(e)}function le(e,t,n,r){var o,s,i,a,c;switch(e=new V(e,r),t=new se(t,r),n){case">":o=X,s=te,i=J,a=">",c=">=";break;case"<":o=J,s=ee,i=X,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,r))return!1;for(var u=0;u=0.0.0")),p=p||e,h=h||e,o(e.semver,p.semver,r)?p=e:i(e.semver,h.semver,r)&&(h=e)})),p.operator===a||p.operator===c)return!1;if((!h.operator||h.operator===a)&&s(e,h.semver))return!1;if(h.operator===c&&i(e,h.semver))return!1}return!0}re.prototype.parse=function(e){var t=this.options.loose?o[j]:o[U],n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1],"="===this.operator&&(this.operator=""),n[2]?this.semver=new V(n[2],this.options.loose):this.semver=oe},re.prototype.toString=function(){return this.value},re.prototype.test=function(e){return n("Comparator.test",e,this.options.loose),this.semver===oe||("string"==typeof e&&(e=new V(e,this.options)),ne(e,this.operator,this.semver,this.options))},re.prototype.intersects=function(e,t){if(!(e instanceof re))throw new TypeError("a Comparator is required");var n;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return n=new se(e.value,t),ue(this.value,n,t);if(""===e.operator)return n=new se(this.value,t),ue(e.semver,n,t);var r=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),o=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),s=this.semver.version===e.semver.version,i=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=ne(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=ne(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return r||o||s&&i||a||c},t.Range=se,se.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},se.prototype.toString=function(){return this.range},se.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var r=t?o[W]:o[F];e=e.replace(r,ae),n("hyphen replace",e),e=e.replace(o[z],"$1$2$3"),n("comparator trim",e,o[z]),e=(e=(e=e.replace(o[k],"$1~")).replace(o[B],"$1^")).split(/\s+/).join(" ");var s=t?o[j]:o[U],i=e.split(" ").map((function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){n("caret",e,t);var r=t.loose?o[L]:o[P];return e.replace(r,(function(t,r,o,s,i){var a;return n("caret",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a="0"===r?">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":">="+r+"."+o+".0 <"+(+r+1)+".0.0":i?(n("replaceCaret pr",i),a="0"===r?"0"===o?">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+"-"+i+" <"+(+r+1)+".0.0"):(n("no pr"),a="0"===r?"0"===o?">="+r+"."+o+"."+s+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+" <"+(+r+1)+".0.0"),n("caret return",a),a}))}(e,t)})).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var r=t.loose?o[R]:o[M];return e.replace(r,(function(t,r,o,s,i){var a;return n("tilde",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a=">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":i?(n("replaceTilde pr",i),a=">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0"):a=">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0",n("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var r=t.loose?o[A]:o[x];return e.replace(r,(function(t,r,o,s,i,a){n("xRange",e,t,r,o,s,i,a);var c=ie(o),u=c||ie(s),l=u||ie(i);return"="===r&&l&&(r=""),c?t=">"===r||"<"===r?"<0.0.0":"*":r&&l?(u&&(s=0),i=0,">"===r?(r=">=",u?(o=+o+1,s=0,i=0):(s=+s+1,i=0)):"<="===r&&(r="<",u?o=+o+1:s=+s+1),t=r+o+"."+s+"."+i):u?t=">="+o+".0.0 <"+(+o+1)+".0.0":l&&(t=">="+o+"."+s+".0 <"+o+"."+(+s+1)+".0"),n("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(o[q],"")}(e,t),n("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter((function(e){return!!e.match(s)}))),i=i.map((function(e){return new re(e,this.options)}),this)},se.prototype.intersects=function(e,t){if(!(e instanceof se))throw new TypeError("a Range is required");return this.set.some((function(n){return n.every((function(n){return e.set.some((function(e){return e.every((function(e){return n.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new se(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},se.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new V(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!X(n,t)||(n=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(n&&e.test(n))return n;return null},t.validRange=function(e,t){try{return new se(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,n){return le(e,t,"<",n)},t.gtr=function(e,t,n){return le(e,t,">",n)},t.outside=le,t.prerelease=function(e,t){var n=H(e,t);return n&&n.prerelease.length?n.prerelease:null},t.intersects=function(e,t,n){return e=new se(e,n),t=new se(t,n),e.intersects(t)},t.coerce=function(e){if(e instanceof V)return e;if("string"!=typeof e)return null;var t=e.match(o[N]);if(null==t)return null;return H(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"_from":"mongodb@^3.6.0","_id":"mongodb@3.6.0","_inBundle":false,"_integrity":"sha512-/XWWub1mHZVoqEsUppE0GV7u9kanLvHxho6EvBxQbShXTKYF9trhZC2NzbulRGeG7xMJHD8IOWRcdKx5LPjAjQ==","_location":"/mongodb","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"mongodb@^3.6.0","name":"mongodb","escapedName":"mongodb","rawSpec":"^3.6.0","saveSpec":null,"fetchSpec":"^3.6.0"},"_requiredBy":["#DEV:/","/mongodb-memory-server-core"],"_resolved":"https://registry.npmjs.org/mongodb/-/mongodb-3.6.0.tgz","_shasum":"babd7172ec717e2ed3f85e079b3f1aa29dce4724","_spec":"mongodb@^3.6.0","_where":"/repos/.nhscc/airports.api.hscc.bdpa.org","bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"bundleDependencies":false,"dependencies":{"bl":"^2.2.0","bson":"^1.1.4","denque":"^1.4.1","require_optional":"^1.0.1","safe-buffer":"^5.1.2","saslprep":"^1.0.0"},"deprecated":false,"description":"The official MongoDB driver for Node.js","devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^4.5.0","eslint-plugin-prettier":"^2.2.0","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","standard-version":"^4.4.0","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"engines":{"node":">=4"},"files":["index.js","lib"],"homepage":"https://github.com/mongodb/node-mongodb-native","keywords":["mongodb","driver","official"],"license":"Apache-2.0","main":"index.js","name":"mongodb","optionalDependencies":{"saslprep":"^1.0.0"},"peerOptionalDependencies":{"kerberos":"^1.1.0","mongodb-client-encryption":"^1.0.0","mongodb-extjson":"^2.1.2","snappy":"^6.3.4","bson-ext":"^2.0.0"},"repository":{"type":"git","url":"git+ssh://git@github.com/mongodb/node-mongodb-native.git"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","bench":"node test/benchmarks/driverBench/","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional","format":"prettier --print-width 100 --tab-width 2 --single-quote --write \'test/**/*.js\' \'lib/**/*.js\'","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","lint":"eslint -v && eslint lib test","release":"standard-version -i HISTORY.md","test":"npm run lint && mocha --recursive test/functional test/unit test/core","test-nolint":"mocha --recursive test/functional test/unit test/core"},"version":"3.6.0"}')},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(10).EventEmitter,s=n(2).MongoError,i=n(2).MongoTimeoutError,a=n(2).MongoWriteConcernError,c=n(19),u=n(5).format,l=n(35).Msg,p=n(74),h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(94),S=n(16).Buffer,v=n(76),w=n(31).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,E="destroying",C="destroyed",x=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",E,C],[E]:[E,C],[C]:[C]}),A=new Set(["error","close","timeout","parseError","connect","message"]);var N=0,I=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:36e4,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=N++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;oe.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==C&&e.state!==E&&"draining"!==e.state&&e.options.reconnect&&x(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval));B(e){null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}}function D(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function B(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){x(e,E),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],x(e,C),"function"==typeof r&&r(null,null))})}function L(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(t))return n(null,r);const o=S.concat(r),s=o.slice(h),i=o.readInt32LE(12);m(e,s,(function(r,o){if(r)return n(r,null);const a=S.alloc(h);a.writeInt32LE(h+f+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(d.OP_COMPRESSED,12);const c=S.alloc(f);return c.writeInt32LE(i,0),c.writeInt32LE(s.length,4),c.writeUInt8(y[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function j(e,t){for(var n=0;n(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===C||e.state===E?("function"==typeof t&&t(new s("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void W(e)())))):"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}function F(e){for(var t=0;t0)e.executing=!1;else{for(;;){const i=B(e);if(0===e.availableConnections.length){F(e.queue),i0&&z(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){U(e,t),F(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n0&&z(e),setTimeout(()=>W(e)(),10);break}}if(i0){e.queue.unshift(n),z(e);break}var o=n.buffer;n.monitoring&&D(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var s=!0;if(Array.isArray(o))for(let e=0;e{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(x(this,"connected"),this.minSize)for(let e=0;e0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new s("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==C&&n.state!==E)if(F(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o0)return setTimeout(e,1);P(n,r,{force:!1},t)}else W(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},I.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new s("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),z(this,()=>{"function"==typeof e&&e(null,null)}))})},I.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new s("write method must provide a callback");if(this.state!==C&&this.state!==E)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,i.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,i.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,i.started)),"function"==typeof n&&n(t,o)}),L(r,e,(e,n)=>{if(e)throw e;i.buffer=n,t.monitoring?r.queue.unshift(i):r.queue.push(i),r.executing||process.nextTick((function(){W(r)()}))})}else n(new s("pool is draining, new operations prohibited"));else n(new s("pool destroyed"))},I._execute=W,e.exports=I},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:c}=n(149);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=h(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),s=h(o);if(s.some(e=>i.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(s.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const f=s.some(e=>a.get(e)),d=s.some(e=>c.get(e));if(f&&d)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(p((g=o,g[0]))),y=a.get(p((e=>e[e.length-1])(o)));var g;if(f&&(!m||!y))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=s,l=o,p=e=>e.codePointAt(0);function h(e){const t=[],n=e.length;for(let r=0;r=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(40),o=n(39),s=n(150),i=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);return a+=e,s({buffer:t})}const u=c(),l=c(),p=c(),h=c(),f=c(),d=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:p,prohibited_characters:h,bidirectional_r_al:f,bidirectional_l:d}}).call(this,"/")},function(e,t,n){var r=n(151);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages0;s--){var i=this.path[s],a=o[i];if(!a){if(t)return;a=o[i]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,s,i=this._array(e,t),a=this.path[0],c=i&&i[a];return c||t||(c=i[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,s=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(s),s),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),s=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[s]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=n[s],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);i?i.buffer=a:n[s]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new s(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new s("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void d("http://169.254.170.2"+process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,(e,r)=>{if(e)return t(e);n(r)});d(p+"/latest/api/token",{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);d(`${p}/${h}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);d(`${p}/${h}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,y=r.mechanismProperties.AWS_SESSION_TOKEN,g=this.bson;i.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:g.serialize({r:r,p:110})};n.command(m+".$cmd",o,(e,o)=>{if(e)return t(e);const i=o.result,c=g.deserialize(i.payload.buffer),p=c.h,h=c.s.buffer;if(64!==h.length)return void t(new s(`Invalid server nonce length ${h.length}, expected 64`));if(0!==h.compare(r,0,r.length,0,r.length))return void t(new s("Server nonce does not begin with client nonce"));if(p.length<1||p.length>255||-1!==p.indexOf(".."))return void t(new s(`Server returned an invalid host: "${p}"`));const d="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:p,region:f(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":d.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:d},{accessKeyId:a,secretAccessKey:u,token:y}),S={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};y&&(S.t=y);const v={saslContinue:1,conversationId:1,payload:g.serialize(S)};n.command(m+".$cmd",v,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(59),s=n(102),i=n(21),a=n(155)(1e3);function c(e,t,n){return i.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return i.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function p(e){return l(encodeURIComponent(e))}function h(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}h.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var n=0;n<2;n++)if(/^s3-/.test(t[n])){t[1]=t[n].slice(3),t[0]="s3";break}return t},h.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},h.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},h.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},h.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},h.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},h.prototype.getDate=function(){return this.getDateTime().substr(0,8)},h.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},h.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),s=a.get(o);return s||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),s=c(n,"aws4_request"),a.set(o,s)),c(s,this.stringToSign(),"hex")},h.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},h.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",s="s3"!==this.service,i="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[p(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),h=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(p).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+p(l[e]))})),o=h.join("&")}return"/"!==t&&(s&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return s&&".."===t?e.pop():s&&"."===t||(i&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(p(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},h.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()=0&&(n=s.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},h.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(s.stringify(t))):e},r.RequestSigner=h,r.sign=function(e,t){return new h(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(7).collectionNamespace,s=n(42);e.exports=function(e,t,n,i,a,c,u){if(0===a.length)throw new r(t+" must contain at least one document");"function"==typeof c&&(u=c,c={});const l="boolean"!=typeof(c=c||{}).ordered||c.ordered,p=c.writeConcern,h={};if(h[t]=o(i),h[n]=a,h.ordered=l,p&&Object.keys(p).length>0&&(h.writeConcern=p),c.collation)for(let e=0;e{};const l=n.cursorId;if(a(e)<4){const o=e.s.bson,s=e.s.pool,i=new r(o,t,[l]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),s&&s.isConnected())try{s.write(i,a,u)}catch(e){"function"==typeof u?u(e,null):console.warn(e)}return}const p={killCursors:i(t),cursors:[l]},h={};"object"==typeof n.session&&(h.session=n.session),c(e,t,p,h,(e,t)=>{if(e)return u(e);const n=t.message;return n.cursorNotFound?u(new s("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void u(null,n.documents[0]):u(new o("invalid killCursors result returned for cursor id "+l))})}},function(e,t,n){"use strict";const r=n(22).GetMore,o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=o().Long,c=n(7).collectionNamespace,u=n(4).maxWireVersion,l=n(7).applyCommonQueryOptions,p=n(42);e.exports=function(e,t,n,o,h,f){h=h||{};const d=u(e);function m(e,t){if(e)return f(e);const r=t.message;if(r.cursorNotFound)return f(new i("cursor killed or timed out"),null);if(d<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void f(null,null,r.connection)}if(0===r.documents[0].ok)return f(new s(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,f(null,r.documents[0],r.connection)}if(d<4){const s=e.s.bson,i=new r(s,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(i,a,m)}const y={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(y.maxTimeMS=n.cmd.maxAwaitTimeMS);const g=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},h);n.session&&(g.session=n.session),p(e,t,y,g,m)}},function(e,t,n){"use strict";const r=n(22).Query,o=n(2).MongoError,s=n(7).getReadPreference,i=n(7).collectionNamespace,a=n(7).isSharded,c=n(4).maxWireVersion,u=n(7).applyCommonQueryOptions,l=n(42);e.exports=function(e,t,n,p,h,f){if(h=h||{},null!=p.cursorId)return f();if(null==n)return f(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const i=function(e,t,n,i,c){c=c||{};const u=e.s.bson,l=s(n,c);i.batchSize=n.batchSize||i.batchSize;let p=0;p=i.limit<0||0!==i.limit&&i.limit0&&0===i.batchSize?i.limit:i.batchSize;const h=i.skip||0,f={};a(e)&&l&&(f.$readPreference=l.toJSON());n.sort&&(f.$orderby=n.sort);n.hint&&(f.$hint=n.hint);n.snapshot&&(f.$snapshot=n.snapshot);void 0!==n.returnKey&&(f.$returnKey=n.returnKey);n.maxScan&&(f.$maxScan=n.maxScan);n.min&&(f.$min=n.min);n.max&&(f.$max=n.max);void 0!==n.showDiskLoc&&(f.$showDiskLoc=n.showDiskLoc);n.comment&&(f.$comment=n.comment);n.maxTimeMS&&(f.$maxTimeMS=n.maxTimeMS);n.explain&&(p=-Math.abs(n.limit||0),f.$explain=!0);if(f.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o("server find command does not support a readConcern level of "+n.readConcern.level);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const d="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,y=new r(u,t,f,{numberToSkip:h,numberToReturn:p,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:d,ignoreUndefined:m});"boolean"==typeof n.tailable&&(y.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(y.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(y.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(y.awaitData=n.awaitData);"boolean"==typeof n.partial&&(y.partial=n.partial);return y.slaveOk=l.slaveOk(),y}(e,t,n,p,h),c=u({},p);return"string"==typeof i.documentsReturnedIn&&(c.documentsReturnedIn=i.documentsReturnedIn),void e.s.pool.write(i,c,f)}const d=s(n,h),m=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;let o={find:i(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let s=n.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[s[0]]=t}else for(let t=0;te.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),s()}var r=new p(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",i(e,"connect")),r.once("close",i(e,"close")),r.once("timeout",i(e,"timeout")),r.once("error",i(e,"error")),r.once("parseError",i(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),g(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c0&&e.emit(t,n)}A.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},E(this,"connecting");var n=this.s.seedlist.map((function(n){return new p(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",B(e,"close")),t.once("timeout",B(e,"timeout")),t.once("parseError",B(e,"parseError")),t.once("error",B(e,"error")),t.once("connect",B(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),g(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),E(this,T),"function"==typeof t&&t(null,null))};this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o{if(!o)return n(null,s);if(!w(o,r))return o=S(o),n(o);if(c){return L(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[s](i,a,t,u)}A.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof i?e:t.readPreference||i.primary;const s=_(),a=()=>{if(O(s)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof p))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},A.prototype.getServers=function(){return this.s.replicaSetState.allServers()},A.prototype.insert=function(e,t,n,r){L({self:this,op:"insert",ns:e,ops:t},n,r)},A.prototype.update=function(e,t,n,r){L({self:this,op:"update",ns:e,ops:t},n,r)},A.prototype.remove=function(e,t,n,r){L({self:this,op:"remove",ns:e,ops:t},n,r)};const j=["findAndModify","insert","update","delete"];A.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var s=this,a=n.readPreference?n.readPreference:i.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof p))return r(c);if(s.s.debug&&s.emit("pickedServer",i.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&y(s)&&!n.session.inTransaction()&&(h=t,j.some(e=>h[e]));var h;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!w(o,s))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=A},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,s=n(9).diff,i=n(10).EventEmitter,a=n(19),c=n(13),u=n(2).MongoError,l=n(16).Buffer,p="ReplicaSetNoPrimary",h="ReplicaSetWithPrimary",f="Unknown",d="PossiblePrimary",m="RSPrimary",y="RSSecondary",g="RSArbiter",b="RSOther",S="RSGhost",v="Unknown",w=function(e){e=e||{},i.call(this),this.topologyType=p,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,i),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,I(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var s=0;sc)return!1}else if(!l&&i&&c&&c=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&null==e.maxStalenessSeconds){var o=E(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=E(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var s=n[e.index];return e.index=e.index+1,s}function C(e,t,n){for(var r=0;r0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var i=s(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:i};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,s=n(10).EventEmitter,i=n(20).CoreCursor,a=n(19),c=n(11).retrieveBSON,u=n(2).MongoError,l=n(75),p=n(9).diff,h=n(9).cloneOptions,f=n(9).SessionMixins,d=n(9).isRetryableWritesSupported,m=n(4).relayEvents,y=c(),g=n(9).getMMAPError,b=n(4).makeClientMetadata,S=n(9).legacyIsRetryableWriteError;var v="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",v,w,"disconnected"],connecting:["connecting",v,w,"connected","disconnected"],connected:["connected","disconnected",v,w,"unreferenced"],unreferenced:["unreferenced",v,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],E=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>(e.find(e=>e.host===t.host&&e.port===t.port)||e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout0&&e.emit(t,n)}r(E,s),Object.assign(E.prototype,f),Object.defineProperty(E.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(E.prototype,"parserType",{enumerable:!0,get:function(){return y.native?"c++":"js"}}),Object.defineProperty(E.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const x=["serverDescriptionChanged","error","close","timeout","parseError"];function A(e,t,n){t=t||{},x.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function N(e){return function(){e.state!==w&&e.state!==v&&(M(e.connectedProxies,e.disconnectedProxies,this),L(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function I(e,t){return function(){if(e.state===w)return L(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===v||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==v&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),D(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==v&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var s=0;s{if(!o)return n(null,s);if(!S(o,r)||!c)return o=g(o),n(o);if(a=k(r,t.session),!a)return n(o);return B(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](s,i,t,l)}E.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));C(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),L(e),t.once("close",I(e,"close")),t.once("timeout",I(e,"timeout")),t.once("parseError",I(e,"parseError")),t.once("error",I(e,"error")),t.once("connect",I(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},E.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},E.prototype.lastIsMaster=function(){return this.ismaster},E.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},E.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,v),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(L(this),C(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),A(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},E.prototype.isConnected=function(){return this.connectedProxies.length>0},E.prototype.isDestroyed=function(){return this.state===w},E.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},E.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},E.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function L(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=p(e.topologyDescription,n),s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",s),e.topologyDescription=n}}E.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var s=this,i=k(s,n.session);if((null==i||!i.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==i)return r(new u("no mongos proxy available"));var a=h(n);a.topology=s;const c=!n.retrying&&n.retryWrites&&n.session&&d(s)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),i.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!S(n,s))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},E.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},E.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},E.prototype.connections=function(){for(var e=[],t=0;t({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},k.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:A(t),compression:{compressors:g(t)}})),H.forEach(e=>{t[e]&&C(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,i=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:t.host+":27017";return e.set(n,new s(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:F,description:new a(n,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),servers:new Map,sessionPool:new x(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Z(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return y.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===q)return void("function"==typeof t&&t());var n,r;$(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=J(n,t);return e.set(t.address,r),e},new Map),h.translate(e);const o=e.readPreference||h.primary,s=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));$(this,q),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},s):this.selectServer(B(o),e,s)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==F&&this.s.state!==z?($(this,z),te(this[Y],new S("Topology closed")),M(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{E(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),$(this,F),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof h?n=e:"string"==typeof e?n=new h(e):(h.translate(t),n=t.readPreference||h.primary),e=B(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,s=o&&o.transaction;if(r&&s&&s.server)return void n(void 0,s.server);let i=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:h.primary;i=B(t)}const a={serverSelector:i,transaction:s,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[V]=!0,a.timer=void 0;const e=new v(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),ne(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return I(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new S(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Z(this,e),this[Y].length>0&&ne(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){Q({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){Q({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){Q({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),h.translate(n);const o=n.readPreference||h.primary;this.selectServer(B(o),n,(o,s)=>{if(o)return void r(o);const i=!n.retrying&&!!n.retryWrites&&n.session&&f(this)&&!n.session.inTransaction()&&(a=t,K.some(e=>a[e]));var a;i&&(n.session.incrementTransactionNumber(),n.willRetryWrite=i),s.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!ee(o))return r(o);if(i){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return h.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===q}isDestroyed(){return this.s.state===F}unref(){console.log("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(0===e.length)return{};return e.filter(e=>e.type!==i.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),j.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function J(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(p(r,e,j),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{R(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Z(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=J(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function Q(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,s=e.ns,i=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&f(r)&&!t.session.inTransaction();r.selectServer(P(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!ee(r))return r=O(r),n(r);if(a){return Q(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](s,i,t,u)})}function ee(e){return e instanceof S&&e.hasErrorLabel("RetryableWriteError")}function te(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[V]||n.callback(t)}}function ne(e){if(e.s.state===F)return void te(e[Y],new S("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(10),o=n(165).ConnectionPool,s=n(61).CMAP_EVENT_NAMES,i=n(2).MongoError,a=n(4).relayEvents,c=n(11).retrieveBSON(),u=n(19),l=n(34).ServerDescription,p=n(34).compareTopologyVersion,h=n(13),f=n(176).Monitor,d=n(2).MongoNetworkError,m=n(2).MongoNetworkTimeoutError,y=n(4).collationNotSupported,g=n(11).debugOptions,b=n(2).isSDAMUnrecoverableError,S=n(2).isRetryableWriteError,v=n(2).isNodeShuttingDownError,w=n(2).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(15),E=T.ServerType,C=n(41).isTransactionCommand,x=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],A=T.STATE_CLOSING,N=T.STATE_CLOSED,I=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[N]:[N,I],[I]:[I,A,k,N],[k]:[k,A,N],[A]:[A,N]}),R=Symbol("monitor");class D extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:N,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new f(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>L(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:B(this.description.roundTripTime,e.duration)})),this.s.state===I&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===N&&(M(this,I),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==N?(M(this,A),this[R].close(),this.s.pool.close(e,e=>{M(this,N),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===A||this.s.state===N)return void r(new i("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof h))return new i("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:g(x,n)})}] against ${this.name}`),y(this,t)?r(new i(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,s)=>{if(r)return L(this,r),s(r);o.command(e,t,n,U(this,o,t,n,s))},r)}query(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.query(e,t,n,r,U(this,s,t,r,i))},o):o(new i("server is closed"))}getMore(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.getMore(e,t,n,r,U(this,s,null,r,i))},o):o(new i("server is closed"))}killCursors(e,t,n){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((n,r,o)=>{if(n)return L(this,n),o(n);r.killCursors(e,t,U(this,r,null,void 0,o))},n):"function"==typeof n&&n(new i("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function B(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,s=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];if(r.s.state===A||r.s.state===N)return void n(new i("server is closed"));if(y(r,t))return void n(new i(`server ${r.name} does not support collation`));!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,i)=>{if(e)return L(r,e),i(e);n[o](s,a,t,U(r,n,a,t,i))},n):n(new i("servers < 3.4 do not support hint on "+o))}function L(e,t){t instanceof d&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function j(e,t){return e&&e.inTransaction()&&!C(t)}function U(e,t,n,r,o){const s=r&&r.session;return function(r,i){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof d?(s&&!s.hasEnded&&(s.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==E.Standalone}(e)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(L(e,r),e.s.pool.clear())):(_(e)<9&&S(r)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return p(r,n)<0}(e,r)&&((_(e)<=7||v(r))&&e.s.pool.clear(),L(e,r),process.nextTick(()=>e.requestCheck())))),o(r,i)}}Object.defineProperty(D.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:D}},function(e,t,n){"use strict";const r=n(77),o=n(10).EventEmitter,s=n(19),i=n(0).makeCounter,a=n(2).MongoError,c=n(105).Connection,u=n(4).eachAsync,l=n(76),p=n(4).relayEvents,h=n(175),f=h.PoolClosedError,d=h.WaitQueueTimeoutError,m=n(61),y=m.ConnectionPoolCreatedEvent,g=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,S=m.ConnectionReadyEvent,v=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,E=m.ConnectionPoolClearedEvent,C=Symbol("logger"),x=Symbol("connections"),A=Symbol("permits"),N=Symbol("minPoolSizeTimer"),I=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),D=Symbol("cancelled"),B=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[I]}function L(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function j(e,t){const n=Object.assign({id:e[k].next().value,generation:e[I]},e.options);e[A]--,l(n,e[M],(n,r)=>{if(n)return e[A]++,e[C].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(p(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new S(e,r)),"function"!=typeof t?(e[x].push(r),z(e)):t(void 0,r))})}function U(e,t,n){e.emit("connectionClosed",new v(e,t,n)),e[A]++,process.nextTick(()=>t.destroy())}function z(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[D]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[x].shift(),r=P(e,n),o=L(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const s=n.closed?"error":r?"stale":"idle";U(e,n,s)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount{const r=e[R].shift();null!=r?r[D]||(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n)):null==t&&e[x].push(n)})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(B).reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[C]=s("ConnectionPool",e),this[x]=new r,this[A]=this.options.maxPoolSize,this[N]=void 0,this[I]=0,this[k]=i(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new y(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;ee(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[I]}get totalConnectionCount(){return this[x].length+(this.options.maxPoolSize-this[A])}get availableConnectionCount(){return this[x].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new f(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[D]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new d(n))},r)),this[R].push(t),z(this)}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[x].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){U(this,e,e.closed?"error":t?"poolClosed":"stale")}z(this)}clear(){this[I]+=1,this.emit("connectionPoolCleared",new E(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[D]||e.callback(new a("connection pool closed"))}this[N]&&clearTimeout(this[N]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[x].toArray(),(t,n)=>{this.emit("connectionClosed",new v(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[x].clear(),this.emit("connectionPoolClosed",new g(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(24).Duplex,o=n(167),s=n(2).MongoParseError,i=n(27).decompress,a=n(22).Response,c=n(35).BinMsg,u=n(2).MongoError,l=n(7).opcodes.OP_COMPRESSED,p=n(7).opcodes.OP_MSG,h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(35).Msg,S=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[S]=new o}_write(e,t,n){this[S].append(e),function e(t,n){const r=t[S];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new s("Invalid message size: "+o));if(o>t.maxBsonMessageSize)return void n(new s(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const f=r.slice(0,o);r.consume(o);const d={length:f.readInt32LE(0),requestId:f.readInt32LE(4),responseTo:f.readInt32LE(8),opCode:f.readInt32LE(12)};let m=d.opCode===p?c:a;const y=t.responseOptions;if(d.opCode!==l){const o=f.slice(h);return t.emit("message",new m(t.bson,f,d,o,y)),void(r.length>=4?e(t,n):n())}d.fromCompressed=!0,d.opCode=f.readInt32LE(h),d.length=f.readInt32LE(h+4);const g=f[h+8],b=f.slice(h+9);m=d.opCode===p?c:a,i(g,b,(o,s)=>{o?n(o):s.length===d.length?(t.emit("message",new m(t.bson,f,d,s,y)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(h),o=n.readInt32LE(12);m({options:t},r,(n,s)=>{if(n)return void t.cb(n,null);const i=Buffer.alloc(h);i.writeInt32LE(h+f+s.length,0),i.writeInt32LE(e.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(d.OP_COMPRESSED,12);const a=Buffer.alloc(f);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(y[t.agreedCompressor],8),this.push(Buffer.concat([i,a,s]))})}}},function(e,t,n){"use strict";var r=n(168).Duplex,o=n(5),s=n(16).Buffer;function i(e){if(!(this instanceof i))return new i(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(i,r),i.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;rthis.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||s.alloc(0);if(r<=0)return e||s.alloc(0);var o,i,a=!!e,c=this._offset(n),u=r-n,l=u,p=a&&t||0,h=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:s.concat(this._bufs,this.length);for(i=0;i(o=this._bufs[i].length-h))){this._bufs[i].copy(e,p,h,h+l),p+=o;break}this._bufs[i].copy(e,p,h),p+=o,l-=o,h&&(h=0)}return e.length>p?e.slice(0,p):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new i;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new i(o)},i.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){for(var e=0,t=new i;ethis.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},i.prototype._match=function(e,t){if(this.length-e0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,s=r.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,n=s,o=a,t.copy(n,o),a+=i.data.length,i=i.next;return s},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=s;var r=n(111),o=Object.create(n(44));function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}o.inherits=n(45),o.inherits(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(34).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(2).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(10),s=n(76),i=n(105).Connection,a=n(15),c=n(4).makeStateMachine,u=n(2).MongoNetworkError,l=n(11).retrieveBSON(),p=n(0).makeInterruptableAsyncInterval,h=n(0).calculateDurationInMs,f=n(0).now,d=n(104),m=d.ServerHeartbeatStartedEvent,y=d.ServerHeartbeatSucceededEvent,g=d.ServerHeartbeatFailedEvent,b=Symbol("server"),S=Symbol("monitorId"),v=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,E=a.STATE_CLOSING,C=c({[E]:[E,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",E],monitoring:["monitoring","idle",E]}),x=new Set([E,T,"monitoring"]);function A(e){return e.s.state===T||e.s.state===E}function N(e){C(e,E),e[S]&&(e[S].stop(),e[S]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[S]&&(clearTimeout(e[S]),e[S]=void 0),e[v]&&e[v].destroy({force:!0})}function I(e){return t=>{function n(){A(e)||C(e,"idle"),t()}C(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),function(e,t){let n=f();function r(r){e[v]&&(e[v].destroy({force:!0}),e[v]=void 0),e.emit("serverHeartbeatFailed",new g(h(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[v]&&!e[v].closed){const s=e.options.connectTimeoutMS,i=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u=c?{ismaster:!0,maxAwaitTimeMS:i,topologyVersion:(o=a,{processId:o.processId,counter:l.Long.fromNumber(o.counter)})}:{ismaster:!0},p=c?{socketTimeout:s+i,exhaustAllowed:!0}:{socketTimeout:s};return c&&null==e[_]&&(e[_]=new k(e[w],e.connectOptions)),void e[v].command("admin.$cmd",u,p,(o,s)=>{if(o)return void r(o);const i=s.result,a=c?e[_].roundTripTime:h(n);e.emit("serverHeartbeatSucceeded",new y(a,i,e.address)),c&&i.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=f()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,i))})}var o;s(e.connectOptions,e[w],(o,s)=>{if(s&&A(e))s.destroy({force:!0});else{if(o)return e[v]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[v]=s,e.emit("serverHeartbeatSucceeded",new y(h(n),s.ismaster,e.address)),t(void 0,s.ismaster)}})}(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{A(e)||e[S].wake()}),n()})}}class k{constructor(e,t){this[v]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[S]=setTimeout(()=>function e(t,n){const r=f(),o=t[w],i=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[v]&&(t[v]=o),t[O]=h(r),t[S]=setTimeout(()=>e(t,n),i))}if(null==t[v])return void s(n,o,(e,n)=>{if(e)return t[v]=void 0,void(t[O]=0);a(n)});t[v].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[v]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[S]),this[S]=void 0,this[v]&&this[v].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[v]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[S]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){x.has(this.s.state)||this[S].wake()}reset(){if(A(this))return;C(this,E),N(this),C(this,"idle");const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t})}close(){A(this)||(C(this,E),N(this),this.emit("close"),C(this,T))}}}},function(e,t,n){"use strict";const r=n(19),o=n(10).EventEmitter,s=n(78);class i{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=i,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return"_mongodb._tcp."+this.srvHost}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new i(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;s.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(15).TopologyType,s=n(13),i=n(2).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function p(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function h(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(h));const f=e.mode;if(f===s.PRIMARY)return n.filter(u);if(f===s.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const d=f===s.NEAREST?p:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,s=(t.heartbeatFrequencyMS+1e4)/1e3;if(r((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(d))));return f===s.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(59),o=n(102),s=n(78),i=n(2).MongoParseError,a=n(13),c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;function u(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}function l(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=l(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>l(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const p=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),f=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),d={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function m(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),p.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!f.has(n))throw new i(`Value for authMechanism must be one of: ${Array.from(f).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new i("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&d[t]?e[d[t]]=n:e[t]=n}const y=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function g(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=b("tls",e,t),r=b("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new i("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new i("Incomplete key value pair for option");const s=e.toLowerCase();m(n,s,l(s,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,console.warn("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function b(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new i(`All values of ${e} must be the same.`)})}return o}const S="mongodb+srv",v=["mongodb",S];function w(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new i("URI malformed, cannot be parsed"))}const a=e.match(c);if(!a)return n(new i("Invalid connection string"));const l=a[1];if(-1===v.indexOf(l))return n(new i("Invalid protocol provided"));const p=a[4].split("?"),h=p.length>0?p[0]:null,f=p.length>1?p[1]:null;let d;try{d=g(f,t)}catch(e){return n(e)}if(d=Object.assign({},d,t),l===S)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new i("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new i("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new i("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new i(`Ports not accepted with '${S}' URIs`));const c=a.host;s.resolveSrv("_mongodb._tcp."+c,(e,l)=>{if(e)return n(e);if(0===l.length)return n(new i("No addresses found at host"));for(let e=0;e`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),s.resolveTxt(c,(e,s)=>{if(e){if("ENODATA"!==e.code)return n(e);s=null}if(s){if(s.length>1)return n(new i("Multiple text records not allowed"));if(s=o.parse(s[0].join("")),Object.keys(s).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new i("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);w(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,d,n);const m={username:null,password:null,db:h&&""!==h?o.unescape(h):null};if(d.auth?(d.auth.username&&(m.username=d.auth.username),d.auth.user&&(m.username=d.auth.user),d.auth.password&&(m.password=d.auth.password)):(d.username&&(m.username=d.username),d.user&&(m.username=d.user),d.password&&(m.password=d.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new i("Unescaped slash in userinfo section"));const b=a[3].split("@");if(b.length>2)return n(new i("Unescaped at-sign in authority section"));if(null==b[0]||""===b[0])return n(new i("No username provided in authority section"));if(b.length>1){const e=b.shift().split(":");if(e.length>2)return n(new i("Unescaped colon in authority section"));if(""===e[0])return n(new i("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let _=null;const O=b.shift().split(",").map(e=>{let t=r.parse("mongodb://"+e);if("/:"===t.path)return _=new i("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(_=new i("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)_=new i("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;_=new i("Invalid port (negative number)")}else _=new i("Invalid port (zero) with hostname")}).filter(e=>!!e);if(_)return n(_);if(0===O.length||""===O[0].host||null===O[0].host)return n(new i("No hostname or hostnames provided in connection string"));if(!!d.directConnection&&1!==O.length)return n(new i("directConnection option requires exactly one host"));null==d.directConnection&&1===O.length&&null==d.replicaSet&&(d.directConnection=!0);const T={hosts:O,auth:m.db||m.username?m:null,options:Object.keys(d).length?d:null};var E;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((E=T.options).tls&&(E.ssl=E.tls),E.tlsInsecure?(E.checkServerIdentity=!1,E.sslValidate=!1):Object.assign(E,{checkServerIdentity:!E.tlsAllowInvalidHostnames,sslValidate:!E.tlsAllowInvalidCertificates}),E.tlsCAFile&&(E.ssl=!0,E.sslCA=E.tlsCAFile),E.tlsCertificateKeyFile&&(E.ssl=!0,E.tlsCertificateFile?(E.sslCert=E.tlsCertificateFile,E.sslKey=E.tlsCertificateKeyFile):(E.sslKey=E.tlsCertificateKeyFile,E.sslCert=E.tlsCertificateKeyFile)),E.tlsCertificateKeyFilePassword&&(E.ssl=!0,E.sslPass=E.tlsCertificateKeyFilePassword),E);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(y.has(r)&&(!e.auth||null==e.auth.username))throw new i(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new i(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=w},function(e,t,n){"use strict";const r=n(10).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(46).buildCountCommand,o=n(0).handleCallback,s=n(1).MongoError,i=Array.prototype.push,a=n(20).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let s,i={};i.skip=n.skip,i.limit=n.limit,i.hint=n.hint,i.maxTimeMS=n.maxTimeMS,i.collectionName=e.namespace.collection;try{s=r(e,e.cmd.query,i)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),s,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw s.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,s.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,s)=>r?o(n,r):null==s?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,s)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((s,a)=>{if(s)return o(t,s);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),i.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(12).buildCountCommand,o=n(3).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let s,i={};i.skip=o.skip,i.limit=o.limit,i.hint=o.hint,i.maxTimeMS=o.maxTimeMS,i.collectionName=t.namespace.collection;try{s=r(t,t.cmd.query,i)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),s,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(63);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern;class c extends s{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,s=this.options,c={distinct:n.collectionName,key:r,query:o};"number"==typeof s.maxTimeMS&&(c.maxTimeMS=s.maxTimeMS),a(c,n,s);try{i(c,n,s)}catch(e){return t(e,null)}super.executeCommand(e,c,(e,n)=>{e?t(e):t(null,this.options.full?n:n.values)})}}o(c,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(115),i=n(0).handleCallback;class a extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return i(e,t,!1);i(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26);class i extends s{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(i,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(3).Aspect,s=n(3).defineAspects,i=n(1).ReadPreference,a=n(4).maxWireVersion,c=n(2).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=i.resolve(e,this.options)}execute(e,t){if(this.server=e,void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}s(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(3).OperationBase,s=n(0).toError;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,s(t),null);r(e,null,n)})}catch(t){e(t)}}}},function(e,t,n){"use strict";const r=n(64);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new=void 0!==r.returnOriginal&&!r.returnOriginal,s.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,s.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(3).OperationBase,i=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(14).executeCommand,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(0).toError;class h extends s{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,s={geoSearch:t.collectionName,near:[n,r]};s=i(s,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(s,t,o),c(t.s.db,s,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,p(n)),u(e,null,n)})}}o(h,r.READ_OPERATION),e.exports=h},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(14).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;s(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(3).OperationBase,s=n(12).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));s(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(117),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(i(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(85).loadDb,p=n(3).OperationBase,h=n(1).ReadPreference,f=n(0).toError,d=["readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];function m(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let s=t.length-1;s>=0;s--)n=t[s],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=m(e[n]);return r}e.exports=class extends p{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options;const p={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?p[e]=m(u[e]):-1===d.indexOf(e)&&(p[e]=u[e]);u=Object.assign({},u),u.readPreference=h.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(p,{db:t.s.db,collection:t},u)):i(p,t,u),!0===u.bypassDocumentValidation&&(p.bypassDocumentValidation=u.bypassDocumentValidation);try{s(p,t,u)}catch(t){return e(t,null)}a(t.s.db,p,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,f(r));const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let s=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;s=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else s=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,s);c(e,n,{collection:s,stats:o})})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback;let s;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,i=(s||(s=n(47)),s);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new i(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).defineAspects,s=n(3).Aspect;class i extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(i,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]),e.exports=i},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(85).loadCollection,c=n(1).MongoError,u=n(1).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class p extends s{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let s=Object.assign({nameOnly:!0,strict:!1},r);function l(s){if(s)return e(s);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(s){e(s)}}s=i(s,{db:t},s);s.strict?t.listCollections({name:n},s).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(p,r.WRITE_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion,a=n(80);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(i(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=e+".";return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}s(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(23),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;enull!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new i("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(15).serverType,a=n(15).ServerType,c=n(1).MongoError;class u extends s{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){i(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),s(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects;class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}s(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateCallback,s=n(12).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,s(t,n,r,i,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!s(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n){if(null==n)return;if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}(t,n,e))}}},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(59),s=n(5).format,i=n(1).Logger,a=n(78),c=n(36);function u(e,t){let n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return!!r.endsWith(o)}function l(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",p=o.parse(e,!0);if((null==p.hostname||""===p.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===p.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(p.port,10))&&parseInt(p.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(p.path&&p.path.length>0&&"/"!==p.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(p.query)for(let e in p.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===p.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(p.auth){let t=p.auth.split(":");if(-1!==e.indexOf(p.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(p.auth)&&-1!==p.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let h=e.split("?").shift().split(","),f=[];for(let e=0;e1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let d,m,y,g,b={},S=a||"",v=S.split(":",2),w=decodeURIComponent(v[0]);if(v[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(v[0]=w,v[1]){let e=decodeURIComponent(v[1]);if(v[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");v[1]=e}2===v.length&&(b.auth={user:v[0],password:v[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},E={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=E,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),y=[{domain_socket:t}]}else{d=n;let e={};y=d.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,E.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,E.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,E.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),E.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),E.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(S);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(S)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");g.zlibCompressionLevel=e,_.compression=g}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:i("URL Parser").warn(n+" is not supported as a connection string option")}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=y,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return l(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let s="_mongodb._tcp."+r.host;a.resolveSrv(s,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e1)return n(new Error("Multiple text records not allowed"));if(!(r=(r=r[0]).length>1?r.join(""):r[0]).includes("authSource")&&!r.includes("replicaSet"))return n(new Error("Text record must only set `authSource` or `replicaSet`"));c.push(r)}c.length&&(i+="?"+c.join("&")),l(i,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(95),r=e.mongodb.MongoTimeoutError,o=n(67),s=o.debug,i=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,i=e._client,a=e._keyVaultNamespace,l=e._keyVaultClient,p=e._mongocryptdClient,h=e._mongocryptdManager;switch(s(`[context#${t.id}] ${u.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(i,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(p,t.ns,o,(s,i)=>{if(s)return s instanceof r&&h&&!h.bypassSpawn?void h.spawn(()=>{this.markCommand(p,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(s,null);t.addMongoOperationResponse(i),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(l,a,r,(r,s)=>{if(r)return n(r,null);s.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c("Unknown state: "+t.state))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],port:r},s=e.message;return new Promise((n,r)=>{const i=t.connect(o,()=>{i.write(s)});i.once("timeout",()=>{i.removeAllListeners(),i.destroy(),r(new c("KMS request timed out"))}),i.once("error",e=>{i.removeAllListeners(),i.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),i.on("data",t=>{e.addResponse(t),e.bytesNeeded<=0&&i.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,s=i(t);e.db(s).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,s=i(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(s).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,s=i(t),c=a(t);n=o.deserialize(n),e.db(s).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67).databaseNamespace,o=e.stateMachine.StateMachine,s=n(221).MongocryptdManager,i=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(129);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new s(n.extraOptions),this._mongocryptdClient=new i(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=n.kmsProviders),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&t.message.match(/timed out after/)?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,s){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==s&&(s=n,n={}),this._bypassEncryption)return void s(void 0,t);const i=this._bson,a=Buffer.isBuffer(t)?t:i.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void s(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t;new o(Object.assign({bson:i},n)).execute(this,c,s)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,s=Buffer.isBuffer(e)?e:r.serialize(e,t);let i;try{i=this._mongocrypt.makeDecryptionContext(s)}catch(e){return void n(e,null)}i.id=this._contextCounter++;new o(Object.assign({bson:r},t)).execute(this,i,n)}}}}},function(e,t,n){var r=n(39).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),s=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);s=s.replace(/^(.+)\|/,"$1:"),"\\"==r&&(s=s.replace(/\//g,"\\"));/^.+\:/.test(s)||(s=r+s);return o+s}},function(e,t,n){"use strict";const r=n(222).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67),o=r.databaseNamespace,s=r.collectionNamespace,i=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(129);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r{u.execute(this,c,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),i=s(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(i).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),s=Object.assign({},t);if(t.keyId&&(s.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError('"options.keyAltName" must be of type string, but was of type '+n);s.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,s);return i(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),s=new a({bson:n});return i(t,e=>{s.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(130),o=n(1).BSON.ObjectID,s=n(1).ReadPreference,i=n(16).Buffer,a=n(40),c=n(5).format,u=n(5),l=n(1).MongoError,p=u.inherits,h=n(24).Duplex,f=n(0).shallowClone,d=n(0).executeLegacyOperation,m=n(5).deprecate;const y=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var g=function e(t,n,i,a,c){if(y(),!(this instanceof e))return new e(t,n,i,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=i,i=void 0):"object"==typeof a&&(c=a,a=i,i=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=i):void 0===i?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=i),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||s.primary,this.writeConcern=z(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};g.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return d(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=z(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=f(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};g.prototype.eof=function(){return this.position===this.length},g.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,S,[this,e,t],{skipSessions:!0})};var S=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?I(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};g.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return d(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},g.prototype.stream=function(){return new F(this)},g.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},d(this.db.s.topology,j,[this,e,t,n,r],{skipSessions:!0})},g.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},g.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},d(this.db.s.topology,v,[this,e,t,n],{skipSessions:!0})};var v=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,s){if(e)return o(e,n);var c=0,u=0,l=function(){var e=i.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,i,p){if(e)return o(e,n);c+=i,new r(n,{n:u++},n.writeConcern).write(p.slice(0,i),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+i,n.currentChunk=r,c>=s.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};g.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate||(e.uploadDate=new Date),N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};g.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},g.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};g.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},g.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},d(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var c=e.currentChunk.readSlice(s-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===s&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,I(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};g.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},g.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},d(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var s=null==n?g.IO_SEEK_SET:n,i=t,a=0;a=s===g.IO_SEEK_CUR?e.position+i:s===g.IO_SEEK_END?e.length+i:i;var c=Math.floor(a/e.chunkSize);I(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},x=function(e,t,n){var s=e.collection(),i=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}i=null==e.fileId&&null==e.filename?null:i,t.readPreference=e.readPreference,null!=i?s.findOne(i,t,(function(s,i){if(s)return a(s);if(null!=i)e.fileId=i._id,e.filename="r"===e.mode||void 0===e.filename?i.filename:e.filename,e.contentType=i.contentType,e.internalChunkSize=i.chunkSize,e.uploadDate=i.uploadDate,e.aliases=i.aliases,e.length=i.length,e.metadata=i.metadata,e.internalMd5=i.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?I(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&i?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var s="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),s?e.close((function(t){o(t,e)})):o(null,e);for(var i=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),p=t.slice(a),h=[e.currentChunk.write(u)];p.length>=e.chunkSize;){var f=new r(e,{n:i+1},e.writeConcern);u=p.slice(0,e.chunkSize),p=p.slice(e.chunkSize),i+=1,f.write(u),h.push(f)}e.currentChunk=new r(e,{n:i+1},e.writeConcern),p.length>0&&e.currentChunk.write(p),e.position=e.position+t.length;for(var d=h.length,m=0;m=t.length?s("offset larger than size of file",null):n&&n>t.length?s("length is larger than the size of the file",null):r&&n&&r+n>t.length?s("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return s(e);t.read(n,s)})):t.read(n,s))}))};g.readlines=function(e,t,n,r,o){var s=Array.prototype.slice.call(arguments,2);return o="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=(r=s.length?s.shift():null)||{},d(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var s=null==n?"\n":n;new g(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};g.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},d(e.s.topology,L,[this,e,t,n,r],{skipSessions:!0})};var L=function(e,t,n,r,o){var s=z(t,r);if(n.constructor===Array)for(var i=0,a=0;ae.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var s={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)},p.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,f,[this,e,t,n],{skipSessions:!0})},p.prototype.drop=function(e){return u(this.s.db.s.topology,d,[this,e],{skipSessions:!0})},p.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(24),o=n(5);function s(e,t,n,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:s,readPreference:n},r.Readable.call(this)}function i(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=s,o.inherits(s,r.Readable),s.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end0&&(s.n={$gte:i})}e.s.cursor=e.s.chunks.find(s).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,s=Math.min(e.s.file.chunkSize,r);if(n.n>o){var i="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(i))}if(n.n0;){var d=o.length-s;if(o.copy(e.bufToStore,e.pos,d,d+c),e.pos+=c,0===(i-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++p,y(e,r))return!1;e.chunks.insertOne(m,f(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--p||(e.emit("drain",m),r&&r(),h(e))})),i=e.chunkSizeBytes,e.pos=0,++e.n}s-=c,c=Math.min(i,s)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),y(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):d(this,(function(){m(r)})))}},function(e,t,n){var r,o; +/*! + * is.js 0.8.0 + * Author: Aras Atasaygin + */o=this,void 0===(r=function(){return o.is=function(){var e={VERSION:"0.8.0",not:{},all:{},any:{}},t=Object.prototype.toString,n=Array.prototype.slice,r=Object.prototype.hasOwnProperty;function o(e){return function(){return!e.apply(null,n.call(arguments))}}function s(e){return function(){for(var t=u(arguments),n=t.length,r=0;r":function(e,t){return e>t},">=":function(e,t){return e>=t}};function c(e,t){var n=t+"",r=+(n.match(/\d+/)||NaN),o=n.match(/^[<>]=?|/)[0];return a[o]?a[o](e,r):e==r||r!=r}function u(t){var r=n.call(t);return 1===r.length&&e.array(r[0])&&(r=r[0]),r}e.arguments=function(e){return"[object Arguments]"===t.call(e)||null!=e&&"object"==typeof e&&"callee"in e},e.array=Array.isArray||function(e){return"[object Array]"===t.call(e)},e.boolean=function(e){return!0===e||!1===e||"[object Boolean]"===t.call(e)},e.char=function(t){return e.string(t)&&1===t.length},e.date=function(e){return"[object Date]"===t.call(e)},e.domNode=function(t){return e.object(t)&&t.nodeType>0},e.error=function(e){return"[object Error]"===t.call(e)},e.function=function(e){return"[object Function]"===t.call(e)||"function"==typeof e},e.json=function(e){return"[object Object]"===t.call(e)},e.nan=function(e){return e!=e},e.null=function(e){return null===e},e.number=function(n){return e.not.nan(n)&&"[object Number]"===t.call(n)},e.object=function(e){return Object(e)===e},e.regexp=function(e){return"[object RegExp]"===t.call(e)},e.sameType=function(n,r){var o=t.call(n);return o===t.call(r)&&("[object Number]"!==o||!e.any.nan(n,r)||e.all.nan(n,r))},e.sameType.api=["not"],e.string=function(e){return"[object String]"===t.call(e)},e.undefined=function(e){return void 0===e},e.windowObject=function(e){return null!=e&&"object"==typeof e&&"setInterval"in e},e.empty=function(t){if(e.object(t)){var n=Object.getOwnPropertyNames(t).length;return!!(0===n||1===n&&e.array(t)||2===n&&e.arguments(t))}return""===t},e.existy=function(e){return null!=e},e.falsy=function(e){return!e},e.truthy=o(e.falsy),e.above=function(t,n){return e.all.number(t,n)&&t>n},e.above.api=["not"],e.decimal=function(t){return e.number(t)&&t%1!=0},e.equal=function(t,n){return e.all.number(t,n)?t===n&&1/t==1/n:e.all.string(t,n)||e.all.regexp(t,n)?""+t==""+n:!!e.all.boolean(t,n)&&t===n},e.equal.api=["not"],e.even=function(t){return e.number(t)&&t%2==0},e.finite=isFinite||function(t){return e.not.infinite(t)&&e.not.nan(t)},e.infinite=function(e){return e===1/0||e===-1/0},e.integer=function(t){return e.number(t)&&t%1==0},e.negative=function(t){return e.number(t)&&t<0},e.odd=function(t){return e.number(t)&&t%2==1},e.positive=function(t){return e.number(t)&&t>0},e.under=function(t,n){return e.all.number(t,n)&&tn&&t=0&&t.indexOf(n,r)===r},e.endWith.api=["not"],e.include=function(e,t){return e.indexOf(t)>-1},e.include.api=["not"],e.lowerCase=function(t){return e.string(t)&&t===t.toLowerCase()},e.palindrome=function(t){if(e.not.string(t))return!1;for(var n=(t=t.replace(/[^a-zA-Z0-9]+/g,"").toLowerCase()).length-1,r=0,o=Math.floor(n/2);r<=o;r++)if(t.charAt(r)!==t.charAt(n-r))return!1;return!0},e.space=function(t){if(e.not.char(t))return!1;var n=t.charCodeAt(0);return n>8&&n<14||32===n},e.startWith=function(t,n){return e.string(t)&&0===t.indexOf(n)},e.startWith.api=["not"],e.upperCase=function(t){return e.string(t)&&t===t.toUpperCase()};var f=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["january","february","march","april","may","june","july","august","september","october","november","december"];e.day=function(t,n){return e.date(t)&&n.toLowerCase()===f[t.getDay()]},e.day.api=["not"],e.dayLightSavingTime=function(e){var t=new Date(e.getFullYear(),0,1),n=new Date(e.getFullYear(),6,1),r=Math.max(t.getTimezoneOffset(),n.getTimezoneOffset());return e.getTimezoneOffset()n.getTime()},e.inDateRange=function(t,n,r){if(e.not.date(t)||e.not.date(n)||e.not.date(r))return!1;var o=t.getTime();return o>n.getTime()&&on)return!1;return o===n},e.propertyCount.api=["not"],e.propertyDefined=function(t,n){return e.object(t)&&e.string(n)&&n in t},e.propertyDefined.api=["not"],e.inArray=function(t,n){if(e.not.array(n))return!1;for(var r=0;r="],o=1;o>>0]},i=1;i<624;i++)s.x[i]=(t=1812433253,n=s.x[i-1]^s.x[i-1]>>>30,r=void 0,o=void 0,(((t>>>16)*(o=65535&n)+(r=65535&t)*(n>>>16)<<16)+r*o>>>0)+i);return s},t.randNext=function(e){var t=(e.i+1)%624,n=e.x[e.i]&o|e.x[t]&s,i={i:t,x:r(e.x,[e.x[(e.i+397)%624]^n>>>1^(0==(1&n)?0:2567483615)])},a=i.x[i.i];return a^=a>>>11,a^=a<<7&2636928640,a^=a<<15&4022730752,[(a^=a>>>18)>>>0,i]},t.randRange=function(e,n,r){var o=n-e;if(!(04294967296-(c-(c%=o));){var l=t.randNext(u);c=l[0],u=l[1]}return[c+e,u]}},function(e,t,n){"use strict"; +/*! + * shallow-clone + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */const r=Symbol.prototype.valueOf,o=n(131);e.exports=function(e,t){switch(o(e)){case"array":return e.slice();case"object":return Object.assign({},e);case"date":return new e.constructor(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return function(e){const t=e.length,n=Buffer.allocUnsafe?Buffer.allocUnsafe(t):Buffer.from(t);return e.copy(n),n}(e);case"symbol":return function(e){return r?Object(r.call(e)):{}}(e);case"arraybuffer":return function(e){const t=new e.constructor(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}(e);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return function(e,t){return new e.constructor(e.buffer,e.byteOffset,e.length)}(e);case"regexp":return function(e){const t=void 0!==e.flags?e.flags:/\w+$/.exec(e)||void 0,n=new e.constructor(e.source,t);return n.lastIndex=e.lastIndex,n}(e);case"error":return Object.create(e);default:return e}}},function(e,t,n){"use strict"; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */var r=n(232);function o(e){return!0===r(e)&&"[object Object]"===Object.prototype.toString.call(e)}e.exports=function(e){var t,n;return!1!==o(e)&&("function"==typeof(t=e.constructor)&&(!1!==o(n=t.prototype)&&!1!==n.hasOwnProperty("isPrototypeOf")))}},function(e,t,n){"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},function(e,t,n){"use strict";e.exports=(e,t)=>{let n;return function r(){const o=Math.floor(Math.random()*(t-e+1)+e);return n=o===n&&e!==t?r():o,n}}},function(e,t,n){"use strict";n.r(t);var r=n(18);exports=function(){Object(r.a)()}}]); \ No newline at end of file diff --git a/external-scripts/bin/generate-flights.js b/external-scripts/bin/generate-flights.js index 7c18c58..5aaa401 100644 --- a/external-scripts/bin/generate-flights.js +++ b/external-scripts/bin/generate-flights.js @@ -1,10 +1,10 @@ -!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=233)}([function(e,t,n){"use strict";const r=n(2).MongoError,o=n(27);var s=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},i=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;nprocess.emitWarning(e,"DeprecationWarning"):e=>console.error(e);function l(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(89),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class h{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new h(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new h(e.substring(0,t),e.substring(t+1))}}function f(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],s=0;s{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const s=e.s.promiseLibrary;let i,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),i=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:i})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(i&&i.owner===c&&!o.returnsCursor)i.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new s((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,s=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const i=o.fromOptions(n);return i?Object.assign(e,{writeConcern:i}):s&&s.writeConcern?Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const s=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!s||!s.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:l,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(o.hasOwnProperty(t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(u(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:h,emitDeprecationWarning:u,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:f,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=f()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,s=!1;const i=(t=t||{}).interval||1e3,a=t.minInterval||500;function c(e){s||(clearTimeout(n),n=setTimeout(u,e||i))}function u(){o=0,r=f(),e(e=>{if(e)throw e;c(i)})}return"boolean"==typeof t.immediate&&t.immediate?u():(r=f(),c()),{wake:function(){const e=f(),t=e-o,n=e-r,s=Math.max(i-n,0);o=e,ta&&c(a)},stop:function(){s=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){if(Array.isArray(t))return t.reduce((t,n)=>t||e(n),null);const n=Object.keys(t);return n.length>0&&"$"===n[0][0]}}},function(e,t,n){"use strict";let r=n(85);const o=n(69),s=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(2).MongoError,MongoNetworkError:n(2).MongoNetworkError,MongoParseError:n(2).MongoParseError,MongoTimeoutError:n(2).MongoTimeoutError,MongoServerSelectionError:n(2).MongoServerSelectionError,MongoWriteConcernError:n(2).MongoWriteConcernError,Connection:n(87),Server:n(72),ReplSet:n(159),Mongos:n(161),Logger:n(17),Cursor:n(18).CoreCursor,ReadPreference:n(12),Sessions:n(29),BSON:r,EJSON:s,Topology:n(162).Topology,Query:n(20).Query,MongoCredentials:n(98).MongoCredentials,defaultAuthProviders:n(93).defaultAuthProviders,MongoCR:n(94),X509:n(95),Plain:n(96),GSSAPI:n(97),ScramSHA1:n(56).ScramSHA1,ScramSHA256:n(56).ScramSHA256,parseConnectionString:n(178)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const s=Symbol("beforeHandshake");class i extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[s]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),p=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const h=new Set([91,189,11600,11602,13436]),f=new Set([10107,13435]),d=new Set([11600,91]);function m(e){return!(!e.code||!h.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:i,MongoNetworkTimeoutError:class extends i{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof i||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&f.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&d.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?p.has(e.code)||p.has(e.result.code):p.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[s]}}},function(e,t,n){"use strict";const r={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS")};e.exports={Aspect:r,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){this.options=Object.assign({},e)}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";const r=n(142),o=n(19),s=n(69);const i=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=null;try{e=s("mongodb-extjson")}catch(e){}return e||(e={parse:i,deserialize:i,serialize:i,stringify:i,setBSONModule:i,BSON:i}),e},retrieveKerberos:function(){let e;try{e=s("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;re===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(143).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";const r=n(12),o=n(2).MongoError,s=n(14).ServerType,i=n(88).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===s.Mongos)return!0;if(e.description&&e.description instanceof i){return Array.from(e.description.servers.values()).some(e=>e.type===s.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";e.exports=(e,t)=>{if(void 0===t&&(t=e,e=0),"number"!=typeof e||"number"!=typeof t)throw new TypeError("Expected all arguments to be numbers");return Math.floor(Math.random()*(t-e+1)+e)}},function(e,t,n){"use strict";const r=n(12),o=n(14).TopologyType,s=n(2).MongoError,i=n(2).isRetryableWriteError,a=n(4).maxWireVersion,c=n(2).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},p=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},h=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},f=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},d=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:s,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var s=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name}),function(e,t,n){var r=f(e,t);return f(e,n)!==r}(e,e.s.ismaster,o.result)&&p(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?f(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=s}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(d(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function y(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const g=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&y(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},inquireServerState:d,getTopologyType:f,emitServerDescriptionChanged:p,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:h(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:g,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new s({message:b,errmsg:b,originalError:e}):e},topologyType:y,legacyIsRetryableWriteError:function(e,t){return e instanceof s&&(g(t)&&(e instanceof c||a(t)<9&&i(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(69);function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){var e=n(85);e.native=!1;try{var t=r("bson-ext");if(t)return t.native=!0,t}catch(e){}return e},retrieveSnappy:function(){var e=null;try{e=r("snappy")}catch(e){}return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(13).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).MongoError,p=n(1).ReadPreference,h=n(0).toError,f=n(18).CursorState;function d(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),s(u,e,e.cmd)):s(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),i(u,e),u},deleteCallback:function(e,t,n){if(null!=n){if(e&&n)return n(e);if(null==t)return n(null,{result:{ok:1}});t.deletedCount=t.result.n,n&&n(null,t)}},findAndModify:function(e,t,n,i,l,h){const f={findAndModify:e.collectionName,query:t};(n=c(n))&&(f.sort=n),f.new=!!l.new,f.remove=!!l.remove,f.upsert=!!l.upsert;const d=l.projection||l.fields;d&&(f.fields=d),l.arrayFilters&&(f.arrayFilters=l.arrayFilters,delete l.arrayFilters),i&&!l.remove&&(f.update=i),l.maxTimeMS&&(f.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(f.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(f.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=p.primary;try{s(f,e,m)}catch(e){return h(e,null)}a(e.s.db,f,m,(e,t)=>e?u(h,e,null):u(h,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(h(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n{if(e.s.state=f.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:d,insertDocuments:function(e,t,n,s){"function"==typeof n&&(s=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},n);i=r(i,e.s.db),i=o(i,{db:e.s.db,collection:e},n),!0===i.keepGoing&&(i.ordered=!1),i.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=d(e,t,n),e.s.topology.insert(e.s.namespace,t,i,(e,n)=>{if(null!=s){if(e)return u(s,e);if(null==n)return u(s,null,null);if(n.result.code)return u(s,h(n.result));if(n.result.writeErrors)return u(s,h(n.result.writeErrors[0]));n.ops=t,u(s,null,n)}})},removeDocuments:function(e,t,n,i){"function"==typeof n?(i=n,n={}):"function"==typeof t&&(i=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{s(a,e,n)}catch(e){return i(e,null)}e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=i)return e?u(i,e,null):null==t?u(i,null,null):t.result.code?u(i,h(t.result)):t.result.writeErrors?u(i,h(t.result.writeErrors[0])):void u(i,null,t)})},updateDocuments:function(e,t,n,i,a){if("function"==typeof i&&(a=i,i=null),null==i&&(i={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(h("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(h("document must be a valid JavaScript object"));let c=Object.assign({},i);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},i),c.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const l={q:t,u:n};l.upsert=void 0!==i.upsert&&!!i.upsert,l.multi=void 0!==i.multi&&!!i.multi,i.hint&&(l.hint=i.hint),c.arrayFilters&&(l.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&l.multi&&(c.retryWrites=!1);try{s(c,e,i)}catch(e){return a(e,null)}e.s.topology.update(e.s.namespace,[l],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,h(t.result)):t.result.writeErrors?u(a,h(t.result.writeErrors[0])):void u(a,null,t)})},updateCallback:function(e,t,n){if(null!=n){if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}}}},function(e,t,n){"use strict";const r=function(e,t,n){if(!r.isValid(e))throw new TypeError("Invalid read preference mode "+e);if(t&&!Array.isArray(t)){console.warn("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,r=void 0!==t.hedge;e||r?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===r.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(r.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),r.PRIMARY="primary",r.PRIMARY_PREFERRED="primaryPreferred",r.SECONDARY="secondary",r.SECONDARY_PREFERRED="secondaryPreferred",r.NEAREST="nearest";const o=[r.PRIMARY,r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST,null];r.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,o=e.maxStalenessSeconds;if("string"==typeof t)return new r(t,n);if(!(t instanceof r)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new r(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||o,hedge:t.hedge})}return t},r.resolve=function(e,t){const n=(t=t||{}).session,o=e&&e.readPreference;let s;return s=t.readPreference?r.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=o?o:r.primary,"string"==typeof s?new r(s):s},r.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new r(t);else if(!t||t instanceof r||"object"!=typeof t){if(!(t instanceof r))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new r(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},r.isValid=function(e){return-1!==o.indexOf(e)},r.prototype.isValid=function(e){return r.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];r.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},r.prototype.equals=function(e){return e.mode===this.mode},r.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},r.primary=new r("primary"),r.primaryPreferred=new r("primaryPreferred"),r.secondary=new r("secondary"),r.secondaryPreferred=new r("secondaryPreferred"),r.nearest=new r("nearest"),e.exports=r},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).debugOptions,i=n(0).handleCallback,a=n(1).MongoError,c=n(0).parseIndexOptions,u=n(1).ReadPreference,l=n(0).toError,p=n(77),h=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function d(e,t,n,o,s){let h=Object.assign({},{readPreference:u.PRIMARY},o);if(h=r(h,{db:e},o),h.writeConcern&&"function"!=typeof s)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));!function(e,t,n,o,s){const p=c(n),h="string"==typeof o.name?o.name:p.name,f=[{name:h,key:p.fieldHash}],d=Object.keys(f[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===d.indexOf(e)&&(f[0][e]=o[e]);const y=e.s.topology.capabilities();if(f[0].collation&&y&&!y.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,s(e)}const g=r({createIndexes:t,indexes:f},{db:e},o);o.readPreference=u.PRIMARY,m(e,g,o,(e,t)=>e?i(s,e,null):0===t.ok?i(s,l(t),null):void i(s,null,h))}(e,t,n,h,(r,c)=>{if(null==r)return i(s,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return i(s,r,c);const u=g(e,t,n,o);h.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(p.SYSTEM_INDEX_COLLECTION),u,h,(e,t)=>{if(null!=s)return e?i(s,e):null==t?i(s,null,null):t.result.writeErrors?i(s,a.create(t.result.writeErrors[0]),null):void i(s,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(s(f,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?i(r,e):n.full?i(r,null,t):void i(r,null,t.result))}function y(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?i(r,null,t):void i(r,null,function(e){let t={};for(let n=0;n0){n.emit(t,r,e);for(let n=0;n{if(null!=r&&26!==r.code)return i(s,r,null);if(null!=a&&a[l]){if("function"==typeof s)return i(s,null,l)}else d(e,t,n,o,s)})},evaluate:function(e,t,n,r,s){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let p={$eval:c,args:l};r.nolock&&(p.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,p,r,(e,t)=>e?i(s,e,null):t&&1===t.ok?i(s,null,t.retval):t?i(s,a.create({message:"eval failed: "+t.errmsg,driver:!0}),null):void i(s,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new h("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?i(r,t):void i(r,null,n.result))},indexInformation:y,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",i={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(i={},t.forEach((function(e){i[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(17),o=n(10).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(4).collationNotSupported,c=n(12),u=n(4).isUnifiedTopology,l=n(41),p=n(22).Readable,h=n(0).SUPPORTS,f=n(0).MongoDBNamespace,d=n(3).OperationBase,m=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function g(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class b extends p{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof d&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=f.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const s=e.s.options;"boolean"==typeof s.promoteLongs?this.cursorState.promoteLongs=s.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof s.promoteValues?this.cursorState.promoteValues=s.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof s.promoteBuffers?this.cursorState.promoteBuffers=s.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),s.reconnect&&(this.cursorState.reconnect=s.reconnect),this.logger=r("Cursor",s),"number"==typeof n?(this.cursorState.cursorId=m.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof m&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return g(t,new s("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new s("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new s("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);if(t.cursorState.cursorIndex!==t.cursorState.documents.length||m.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId))return g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&m.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return t.kill(),S(t,(function(){g(n,new s(e?e.$err:void 0))}));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),g(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new i("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return w(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,i){return r?g(n,r):(t.connection=i,0===t.cursorState.documents.length&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId)?g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!m.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){return this.topology.cursor(this.ns,this.cmd,this.options)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return v(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new s(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new s(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?m.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const i=o.cursorId||0;t.cursorState.cursorId=i instanceof m?i:m.fromNumber(i),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,i)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=i,t.cursorState.init=!0,a(t.server,t.cmd))return e(new s(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void i.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);i.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,v(e,t)}function v(e,t){w(e,()=>g(t,null,null))}function w(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}h.ASYNC_ITERATOR&&(b.prototype[Symbol.asyncIterator]=n(89).asyncIterator),e.exports={CursorState:y,CoreCursor:b}},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(10).retrieveBSON)().Long;const o=n(15).Buffer;var s=0,i=n(6).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=s++},a.nextRequestId=function(){return s+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var s=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+s.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=i.OP_QUERY>>24&255,r[c+2]=i.OP_QUERY>>16&255,r[c+1]=i.OP_QUERY>>8&255,r[c]=255&i.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++s};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=s++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_GETMORE>>24&255,n[t+2]=i.OP_GETMORE>>16&255,n[t+1]=i.OP_GETMORE>>8&255,n[t]=255&i.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=s++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_KILL_CURSORS>>24&255,n[t+2]=i.OP_KILL_CURSORS>>16&255,n[t+1]=i.OP_KILL_CURSORS>>8&255,n[t]=255&i.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,s){s=s||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=s,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof s.promoteLongs||s.promoteLongs,this.promoteValues="boolean"!=typeof s.promoteValues||s.promoteValues,this.promoteBuffers="boolean"==typeof s.promoteBuffers&&s.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var s=0;st?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t){e.exports=require("stream")},function(e,t,n){"use strict";const r=n(22).Transform,o=n(22).PassThrough,s=n(5).deprecate,i=n(0).handleCallback,a=n(1).ReadPreference,c=n(1).MongoError,u=n(18).CoreCursor,l=n(18).CursorState,p=n(1).BSON.Map,h=n(0).maybePromise,f=n(41),d=n(0).formattedOrderClause,m=n(180).each,y=n(181),g=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],b=["numberOfRetries","tailableRetryInterval"];class S extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,s=r.tailableRetryInterval||500,i=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return h(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===S.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return h(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=d(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===b.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${b}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===g.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${g}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:e+" is not a valid query modifier",driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new p(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,m(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{m(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});m(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return h(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,s)=>{if(o)return i(e,o);if(null==s)return t.close({skipKillCursors:!0},()=>i(e,null,n));if(n.push(s),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new y(this,e,t);return f(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),h(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e){return this.operation&&null==this.operation.cmd?(this.operation.options.explain=!0,this.operation.fullResponse=!1,f(this.topology,this.operation,e)):(this.cmd.explain=!0,this.cmd.readConcern&&delete this.cmd.readConcern,h(this,e,e=>{u.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}S.prototype.maxTimeMs=S.prototype.maxTimeMS,s(S.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),s(S.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),s(S.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=S},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).OperationBase,s=n(1).ReadPreference,i=n(34),a=n(27),c=n(4).maxWireVersion,u=n(29).commandSupportsReadConcern,l=n(2).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=s.resolve(o,this.options),this.readConcern=function(e,t){return i.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),this.explain=!1,n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,s=c(e),i=this.session&&this.session.inTransaction();this.readConcern&&u(t)&&!i&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&s<5?n(new l(`Server ${e.name}, which reports wire version ${s}, does not support collation`)):(s>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t,n){"use strict";const r=n(10).retrieveSnappy(),o=n(144),s={snappy:1,zlib:2},i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:s,uncompressibleCommands:i,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var s={};e.options.zlibCompressionLevel&&(s.level=e.options.zlibCompressionLevel),o.deflate(t,s,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>s.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case s.snappy:r.uncompress(t,n);break;case s.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","fsync"]);class o{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new o(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new o(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j,e.writeConcern.fsync)}return new o(e.w,e.wtimeout,e.j,e.fsync)}}}e.exports=o},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(10).retrieveBSON,o=n(9),s=r(),i=s.Binary,a=n(4).uuidV4,c=n(2).MongoError,u=n(2).isRetryableError,l=n(2).MongoNetworkError,p=n(2).MongoWriteConcernError,h=n(39).Transaction,f=n(39).TxnState,d=n(4).isPromiseLike,m=n(12),y=n(39).isTransactionCommand,g=n(8).resolveClusterTime,b=n(6).isSharded,S=n(4).maxWireVersion,v=n(0).now,w=n(0).calculateDurationInMs;function _(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const O=Symbol("serverSession");class T extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof M))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[O]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new h}get id(){return this.serverSession.id}get serverSession(){return null==this[O]&&(this[O]=this.sessionPool.acquire()),this[O]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},this.hasEnded||(this.serverSession&&this.inTransaction()&&this.abortTransaction(),this.sessionPool.release(this.serverSession),this[O]=void 0,this.hasEnded=!0,this.emit("ended",this)),"function"==typeof t&&t(null,null)}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof T&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(_(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(b(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new h(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(f.STARTING_TRANSACTION)}commitTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"commitTransaction",(n,r)=>n?t(n):e(r))});I(this,"commitTransaction",e)}abortTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"abortTransaction",(n,r)=>n?t(n):e(r))});I(this,"abortTransaction",e)}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return N(this,v(),e,t)}}const E=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function C(e,t){return w(e){if(!function(e){return A.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(s=>{if(s instanceof c&&C(n,12e4)&&!x(s)){if(s.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(s.hasErrorLabel("TransientTransactionError"))return N(t,n,r,o)}throw s})}(e,t,n,r)}).catch(o=>{function s(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&C(t,12e4))return N(e,t,n,r);throw x(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>s(o)):s(o)})}function I(e,t,n){if(!_(e,n))return;let r=e.transaction.state;if(r===f.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===f.STARTING_TRANSACTION||r===f.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(f.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===f.STARTING_TRANSACTION)return e.transaction.transition(f.TRANSACTION_ABORTED),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===f.TRANSACTION_COMMITTED||r===f.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let s;function i(r,o){var s;"commitTransaction"===t?(e.transaction.transition(f.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof p||u(r)||x(r))&&(x(s=r)||!E.has(s.codeName)&&100!==s.code&&79!==s.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(f.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?s=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(s={w:e.clientOptions.w}),r===f.TRANSACTION_COMMITTED&&(s=Object.assign({wtimeout:1e4},s,{w:"majority"})),s&&Object.assign(o,{writeConcern:s}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>i(a(e),t));i(a(t),n)})}class k{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)},this.lastUse=v(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(w(this.lastUse)%864e5%36e5/6e4)>e-1}}class M{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new k}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function R(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:T,ServerSession:k,ServerSessionPool:M,TxnState:f,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=v(),t.lsid=r.id;const o=e.inTransaction()||y(t),i=n.willRetryWrite,a=R(t,n);if(r.txnNumber&&(i||o)&&(t.txnNumber=s.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==f.NO_TRANSACTION&&e.transaction.transition(f.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c("Read preference in a transaction must be primary, not: "+n.readPreference.mode);if(t.autocommit=!1,e.transaction.state===f.STARTING_TRANSACTION){e.transaction.transition(f.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&g(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:R}},function(e,t,n){"use strict";const r=n(9),o=n(1).MongoError,s=n(5).format,i=n(1).ReadPreference,a=n(1).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:i})},c.prototype.addObjectAndMethod=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:i})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?(n&&r||n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)||!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode))&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):(n&&r||n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)||!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode))&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var p=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,s=!1,i=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,s=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(i=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",s),t(this,"hasListCollectionsCommand",i),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class h extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new p(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,i.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=i.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=i.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(h.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(h.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(h.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(h.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=p,t.TopologyBase=h},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===i.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=(":"+this.port).length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===h(this.topologyVersion,e.topologyVersion);return null!=e&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:p,compareTopologyVersion:h}},function(e,t,n){"use strict";const r=n(15).Buffer,o=n(6).opcodes,s=n(6).databaseNamespace,i=n(12);let a=0;class c{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=s(t),r.readPreference&&r.readPreference.mode!==i.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:c.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let s=n.length;const i=this.command;return s+=this.makeDocumentSegment(e,i),n.writeInt32LE(s,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}c.getRequestId=function(){return a=a+1&2147483647,a};e.exports={Msg:c,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(s.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(s.BUFFER_SIZE+this.buffer.length)):new Array(s.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(s=0;sthis.position?t:this.position}else if("string"==typeof e){for(s=0;sthis.position?t:this.position}},s.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r=6&&null==t.__nodejs_mock_server__}(e),b=h.session;let S=e.clusterTime,v=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(S.clusterTime)&&(S=b.clusterTime);const e=l(b,v,h);if(e)return f(e)}S&&(v.$clusterTime=S),a(e)&&!g&&y&&"primary"!==y.mode&&(v={$query:v,$readPreference:y.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},h);w.slaveOk=y.slaveOk();const _=c(t)+".$cmd",O=g?new o(d,_,v,w):new r(d,_,v,w),T=b&&(b.inTransaction()||u(v))?function(e){return e&&e instanceof p&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),f.apply(null,arguments)}:f;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new s(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return h(e)&&e.autoEncrypter}(e))return void f(e,t,n,r,o);const i=h(e);"number"!=typeof i||i<8?o(new s("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const s=e.autoEncrypter;function i(e,t){e||null==t?o(e,t):s.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}s.encrypt(t,n,r,(n,s)=>{n?o(n,null):f(e,t,s,r,i)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(3).Aspect,s=n(3).OperationBase,i=n(12),a=n(2).isRetryableError,c=n(4).maxWireVersion,u=n(4).isUnifiedTopology;function l(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");if(u(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){const r=e.s.promiseLibrary;let o;"function"!=typeof n&&(o=new r((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));return e.selectServer(i.primaryPreferred,r=>{r?n(r):l(e,t,n)}),o}(e,t,n);const c=e.s.promiseLibrary;let h,f,d;if(e.hasSessionSupport())if(null==t.session)f=Symbol(),h=e.startSession({owner:f}),t.session=h;else if(t.session.hasEnded)throw new r("Use of expired sessions is not permitted");function m(e,r){h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),n(e,r)}"function"!=typeof n&&(d=new c((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));try{t.hasAspect(o.EXECUTE_WITH_SELECTION)?function(e,t,n){const s=t.readPreference||i.primary,c=t.session&&t.session.inTransaction();if(c&&!s.equals(i.primary))return void n(new r("Read preference in a transaction must be primary, not: "+s.mode));const u={readPreference:s,session:t.session};function l(r,o){return null==r?n(null,o):a(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,s)=>{if(r)return void n(r,null);const i=!1!==e.s.options.retryReads&&t.session&&!c&&p(s)&&t.canRetryRead;t.hasAspect(o.RETRYABLE)&&i?t.execute(s,l):t.execute(s,n)})}(e,t,m):t.execute(m)}catch(e){throw h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),e}return d}function p(e){return c(e)>=6}e.exports=l},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(169)}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(13).createIndex,i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(13).ensureIndex,u=n(13).evaluate,l=n(13).executeCommand,p=n(0).handleCallback,h=n(13).indexInformation,f=n(1).BSON.Long,d=n(1).MongoError,m=n(1).ReadPreference,y=n(11).insertDocuments,g=n(11).updateDocuments;function b(e,t,n){h(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){s(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}),h.group.key=e}(f=Object.assign({},f)).readPreference=m.resolve(e,f),a(h,e,f);try{i(h,e,f)}catch(e){return d(e,null)}l(e.s.db,h,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.retval)})}else{const i=null!=s&&"Code"===s._bsontype?s.scope:{};i.ns=e.collectionName,i.keys=t,i.condition=n,i.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,s.toString()+";");u(e.s.db,new o(a,i),null,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),h(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return p(r,e,null);if(!Array.isArray(t))return p(r,null,null!=n[t]);for(let e=0;e{if(r)return p(n,r,null);if(null==s)return p(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const i=[];o&&(t.raw=o);for(let n=0;n{if(null!=o)return null==t?p(o,null,null):e?p(o,e,null):void p(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,s=n(0).checkCollectionName,i=n(1).BSON.ObjectID,a=n(1).MongoError,c=n(0).normalizeHintField,u=n(0).decorateCommand,l=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,h=n(0).formattedOrderClause,f=n(1).ReadPreference,d=n(182),m=n(183),y=n(76),g=n(0).executeLegacyOperation,b=n(27),S=n(34),v=n(0).MongoDBNamespace,w=n(79),_=n(80),O=n(44).ensureIndex,T=n(44).group,E=n(44).parallelCollectionScan,C=n(11).removeDocuments,x=n(44).save,A=n(11).updateDocuments,N=n(61),I=n(110),k=n(184),M=n(111),R=n(185),D=n(186),B=n(187),P=n(81).DropCollectionOperation,L=n(112),j=n(188),U=n(189),z=n(190),F=n(191),W=n(62),q=n(192),$=n(193),H=n(194),V=n(195),Y=n(196),G=n(197),K=n(113),X=n(198),J=n(199),Z=n(200),Q=n(201),ee=n(202),te=n(114),ne=n(118),re=n(211),oe=n(212),se=n(213),ie=n(214),ae=n(215),ce=n(41),ue=["ignoreUndefined"];function le(e,t,n,r,o,a){s(r);const c=null==a||null==a.slaveOk?e.slaveOk:a.slaveOk,u=null==a||null==a.serializeFunctions?e.s.options.serializeFunctions:a.serializeFunctions,l=null==a||null==a.raw?e.s.options.raw:a.raw,p=null==a||null==a.promoteLongs?e.s.options.promoteLongs:a.promoteLongs,h=null==a||null==a.promoteValues?e.s.options.promoteValues:a.promoteValues,d=null==a||null==a.promoteBuffers?e.s.options.promoteBuffers:a.promoteBuffers,m=new v(n,r),y=a.promiseLibrary||Promise;o=null==o?i:o,this.s={pkFactory:o,db:e,topology:t,options:a,namespace:m,readPreference:f.fromOptions(a),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:p,promoteValues:h,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:y,readConcern:S.fromOptions(a),writeConcern:b.fromOptions(a)}}Object.defineProperty(le.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(le.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(le.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(le.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(le.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(le.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(le.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function he(e,t,n,r,o){const s=Array.prototype.slice.call(arguments,1);return o="function"==typeof s[s.length-1]?s.pop():void 0,t=s.length&&s.shift()||[],n=s.length?s.shift():null,r=s.length&&s.shift()||{},(r=Object.assign({},r)).readPreference=f.PRIMARY,ce(this.s.topology,new W(this,e,t,n,r),o)}le.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let i=Object.assign({},t);for(let e in this.s.options)-1!==ue.indexOf(e)&&(i[e]=this.s.options[e]);if(i.skip=t.skip?t.skip:0,i.limit=t.limit?t.limit:0,i.raw="boolean"==typeof t.raw?t.raw:this.s.raw,i.hint=null!=t.hint?c(t.hint):this.s.collectionHint,i.timeout=void 0===t.timeout?void 0:t.timeout,i.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,i.readPreference=f.resolve(this,i),null==i.readPreference||"primary"===i.readPreference&&"primary"===i.readPreference.mode||(i.slaveOk=!0),null!=r&&"object"!=typeof r)throw a.create({message:"query selector must be an object",driver:!0});const d={find:this.s.namespace.toString(),limit:i.limit,skip:i.skip,query:r};"boolean"==typeof t.allowDiskUse&&(d.allowDiskUse=t.allowDiskUse),"boolean"==typeof i.awaitdata&&(i.awaitData=i.awaitdata),"boolean"==typeof i.timeout&&(i.noCursorTimeout=i.timeout),u(d,i,["session","collation"]),s&&(d.fields=s),i.db=this.s.db,i.promiseLibrary=this.s.promiseLibrary,null==i.raw&&"boolean"==typeof this.s.raw&&(i.raw=this.s.raw),null==i.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(i.promoteLongs=this.s.promoteLongs),null==i.promoteValues&&"boolean"==typeof this.s.promoteValues&&(i.promoteValues=this.s.promoteValues),null==i.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(i.promoteBuffers=this.s.promoteBuffers),d.sort&&(d.sort=h(d.sort)),p(d,this,t);try{l(d,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const m=this.s.topology.cursor(new z(this,this.s.namespace,d,i),i);if("function"!=typeof n)return m;n(null,m)})),le.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new J(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ce(this.s.topology,r,n)},le.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw a.create({message:"operations must be an array of documents",driver:!0});const r=new I(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),le.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ae(this,e,t,n),r)},le.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new oe(this,e,t,n),r)},le.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ie(this,e,t,n),r)},le.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,A,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),le.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeOne=le.prototype.deleteOne,le.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new R(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeMany=le.prototype.deleteMany,le.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,C,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),le.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,x,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),le.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new F(this,e=e||{},t=t||{});return ce(this.s.topology,r,n)})),le.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:f.PRIMARY});const r=new ne(this,e,t);return ce(this.s.topology,r,n)},le.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new P(this.s.db,this.collectionName,e);return ce(this.s.topology,n,t)},le.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new te(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Z(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=f.PRIMARY;const o=new L(this,e,t);return ce(this.s.topology,o,n)},le.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new j(this,e);return ce(this.s.topology,n,t)},le.prototype.dropAllIndexes=r(le.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),le.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new re(this,e=e||{});return ce(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),le.prototype.listIndexes=function(e){return new _(this.s.topology,new Q(this,e),e)},le.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},g(this.s.topology,O,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),le.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ce(this.s.topology,r,n)},le.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new K(this.s.db,this.collectionName,e);return ce(this.s.topology,r,t)},le.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ce(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),le.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new k(this,e,t);return ce(this.s.topology,o,n)},le.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const s=o.length&&o.shift()||{},i=o.length&&o.shift()||{},a=new B(this,e,s,i);return ce(this.s.topology,a,r)},le.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ce(this.s.topology,r,t)},le.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},ce(this.s.topology,new q(this,e,t),n)},le.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new $(this,e,t,n),r)},le.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new H(this,e,t,n),r)},le.prototype.findAndModify=r(he,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),le.prototype._findAndModify=he,le.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ce(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),le.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new w(this.s.topology,new N(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},le.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},le.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=f.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),g(this.s.topology,E,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),le.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const s=new V(this,e,t,n);return ce(this.s.topology,s,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),le.prototype.group=r((function(e,t,n,r,o,s,i,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,s=c.length?c.shift():null,i=c.length&&c.shift()||{},"function"!=typeof o&&(s=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),s=null==s||s,g(this.s.topology,T,[this,e,t,n,r,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),le.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new ee(this,e,t,n);return ce(this.s.topology,o,r)},le.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,d(this.s.topology,this,e)},le.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},le.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=le},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&s,r[5]=s>>8&255,r[4]=s>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof h?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var p=[];for(l=0;l<10;)p[48+l]=l++;for(;l<16;)p[55+l]=p[87+l]=l++;var h=Buffer,f=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new h(12),n=0,r=0;r<24;)t[n++]=p[e.charCodeAt(r++)]<<4|p[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&i.test(e):e instanceof c||(e instanceof h||"function"==typeof e.toHexString&&(e.id instanceof h||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&i.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(s),D=e.match(i);if(!M&&!R&&!D||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!f(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(h.toBuffer(n?u:l));if("N"===e[k])return new m(h.toBuffer(c))}for(;f(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||y)&&(y||(w=b),y=!0,_[T++]=parseInt(e[k],10),O+=1),y&&(S+=1),d&&(v+=1),b+=1,k+=1;else{if(d)return new m(h.toBuffer(c));d=!0,k+=1}if(d&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var B=e.substr(++k).match(p);if(!B||!B[2])return new m(h.toBuffer(c));x=parseInt(B[0],10),k+=B[0].length}if(e[k])return new m(h.toBuffer(c));if(E=0,O){if(C=O-1,g=S,0!==x&&1!==g)for(;"0"===e[w+g-1];)g-=1}else E=0,C=0,_[0]=0,S=1,O=1,g=0;for(x<=v&&v-x>16384?x=-6176:x-=v;x>6111;){if((C+=1)-E>34){var P=_.join("");if(P.match(/^0+$/)){x=6111;break}return new m(h.toBuffer(n?u:l))}x-=1}for(;x<-6176||O=5&&(U=1,5===j))for(U=_[C]%2==1,A=w+C+2;A=0&&++_[z]>9;z--)if(_[z]=0,0===z){if(!(x<6111))return new m(h.toBuffer(n?u:l));x+=1,_[z]=1}}if(N=r.fromNumber(0),I=r.fromNumber(0),0===g)N=r.fromNumber(0),I=r.fromNumber(0);else if(C-E<17)for(z=E,I=r.fromNumber(_[z++]),N=new r(0,0);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));else{for(z=E,N=r.fromNumber(_[z++]);z<=C-17;z++)N=(N=N.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));for(I=r.fromNumber(_[z++]);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]))}var F,W,q,$,H=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new r(t.getLowBits(),0),a=n.multiply(s),c=n.multiply(i),u=o.multiply(s),l=o.multiply(i);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(N,r.fromString("100000000000000000"));H.low=H.low.add(I),F=H.low,W=I,q=F.high_>>>0,$=W.high_>>>0,(q<$||q===$&&F.low_>>>0>>0)&&(H.high=H.high.add(r.fromNumber(1))),t=x+a;var V={low:r.fromNumber(0),high:r.fromNumber(0)};H.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(V.high=V.high.or(r.fromNumber(3).shiftLeft(61)),V.high=V.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),V.high=V.high.or(H.high.and(r.fromNumber(0x7fffffffffff)))):(V.high=V.high.or(r.fromNumber(16383&t).shiftLeft(49)),V.high=V.high.or(H.high.and(r.fromNumber(562949953421311)))),V.low=H.low,n&&(V.high=V.high.or(r.fromString("9223372036854775808")));var Y=h.allocBuffer(16);return k=0,Y[k++]=255&V.low.low_,Y[k++]=V.low.low_>>8&255,Y[k++]=V.low.low_>>16&255,Y[k++]=V.low.low_>>24&255,Y[k++]=255&V.low.high_,Y[k++]=V.low.high_>>8&255,Y[k++]=V.low.high_>>16&255,Y[k++]=V.low.high_>>24&255,Y[k++]=255&V.high.low_,Y[k++]=V.high.low_>>8&255,Y[k++]=V.high.low_>>16&255,Y[k++]=V.high.low_>>24&255,Y[k++]=255&V.high.high_,Y[k++]=V.high.high_>>8&255,Y[k++]=V.high.high_>>16&255,Y[k++]=V.high.high_>>24&255,new m(Y)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,s,i,c=0,u=new Array(36),l=0;l>26&31)>>3==3){if(30===s)return v.join("")+"Infinity";if(31===s)return"NaN";i=e>>15&16383,f=8+(e>>14&1)}else f=e>>14&7,i=e>>17&16383;if(p=i-a,S.parts[0]=(16383&e)+((15&f)<<14),S.parts[1]=t,S.parts[2]=n,S.parts[3]=o,0===S.parts[0]&&0===S.parts[1]&&0===S.parts[2]&&0===S.parts[3])b=!0;else for(y=3;y>=0;y--){var _=0,O=d(S);if(S=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*y+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[g]=0;else for(c=36,l=0;!u[g];)l++,c-=1,g+=1;if((h=c-1+p)>=34||h<=-7||p>0){for(v.push(u[g++]),(c-=1)&&v.push("."),l=0;l0?v.push("+"+h):v.push(h)}else if(p>=0)for(l=0;l0)for(l=0;l{if(r)return n(r);Object.assign(t,{nonce:s});const i=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(f(o,i,s),{db:i.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?d(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,s=t.nonce,i=o.source,a=f(e,o,s);r.command(i+".$cmd",a,(r,o)=>{const s=v(r,o);if(s)return n(s);d(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function h(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function f(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new c(o.concat([o.from("n,,","utf8"),h(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function d(e,t,n,s){const a=n.connection,l=n.credentials,f=n.nonce,d=l.source,w=p(l.username),_=l.password;let O;if("sha256"===e)O=u?u(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new i("username must be a string");if("string"!=typeof t)throw new i("password must be a string");if(0===t.length)throw new i("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(w,_)}catch(e){return s(e)}const T=o.isBuffer(t.payload)?new c(t.payload):t.payload,E=m(T.value()),C=parseInt(E.i,10);if(C&&C<4096)return void s(new i("Server returned an invalid iteration count "+C),!1);const x=E.s,A=E.r;if(A.startsWith("nonce"))return void s(new i("Server returned an invalid nonce: "+A),!1);const N="c=biws,r="+A,I=function(e,t,n,o){const s=[e,t.toString("base64"),n].join("_");if(void 0!==g[s])return g[s];const i=r.pbkdf2Sync(e,t,n,S[o],o);b>=200&&(g={},b=0);return g[s]=i,b+=1,i}(O,o.from(x,"base64"),C,e),k=y(e,I,"Client Key"),M=y(e,I,"Server Key"),R=(D=e,B=k,r.createHash(D).update(B).digest());var D,B;const P=[h(w,f),T.value().toString("base64"),N].join(","),L=[N,"p="+function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o{const n=v(e,t);if(n)return s(n);const c=t.result,u=m(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r{const n=m(t.s.options);if(n)return e(n);d(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},y.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),y.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return h(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof f))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.autoEncrypter;o?o.teardown(e,e=>r(t||e)):r(t)}):r()})},y.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},y.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},y.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new y(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},y.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");if(!this.topology.hasSessionSupport())throw new a("Current topology does not support sessions");return this.topology.startSession(e,this.s.options)},y.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},y.prototype.getLogger=function(){return this.s.options.logger},e.exports=y},function(e,t,n){"use strict";const r=n(24),o=n(1).MongoError,s=n(4).maxWireVersion,i=n(1).ReadPreference,a=n(3).Aspect,c=n(3).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=i.primary),n.explain&&(this.readConcern||this.writeConcern))throw new o('"explain" cannot be used on an aggregate call with readConcern/writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=s(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),n.explain&&(n.full=!1,o.explain=n.explain),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyRetryableWrites,s=n(0).applyWriteConcern,i=n(0).decorateWithCollation,a=n(13).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(4).maxWireVersion,h=n(109).MongoError;e.exports=class extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),f=this.doc;let d=this.options;const m={findAndModify:t.collectionName,query:n};r&&(m.sort=r),m.new=!!d.new,m.remove=!!d.remove,m.upsert=!!d.upsert;const y=d.projection||d.fields;y&&(m.fields=y),d.arrayFilters&&(m.arrayFilters=d.arrayFilters),f&&!d.remove&&(m.update=f),d.maxTimeMS&&(m.maxTimeMS=d.maxTimeMS),d.serializeFunctions=d.serializeFunctions||t.s.serializeFunctions,d.checkKeys=!1,d=o(d,t.s.db),d=s(d,{db:t.s.db,collection:t},d),d.writeConcern&&(m.writeConcern=d.writeConcern),!0===d.bypassDocumentValidation&&(m.bypassDocumentValidation=d.bypassDocumentValidation),d.readPreference=l.primary;try{i(m,t,d)}catch(t){return e(t,null)}if(d.hint){if(d.writeConcern&&0===d.writeConcern.w||p(t.s.topology)<8)return void e(new h("The current topology does not support a hint on findAndModify commands"));m.hint=d.hint}a(t.s.db,m,d,(t,n)=>t?u(e,t,null):u(e,null,n))}}},function(e,t,n){"use strict";const r=n(9).EventEmitter,o=n(5).inherits,s=n(0).getSingleProperty,i=n(80),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(1).ReadPreference,p=n(1).MongoError,h=n(1).ObjectID,f=n(1).Logger,d=n(45),m=n(0).mergeOptionsAndWriteConcern,y=n(0).executeLegacyOperation,g=n(76),b=n(5).deprecate,S=n(0).deprecateOptions,v=n(0).MongoDBNamespace,w=n(77),_=n(27),O=n(34),T=n(79),E=n(13).createListener,C=n(13).ensureIndex,x=n(13).evaluate,A=n(13).profilingInfo,N=n(13).validateDatabaseName,I=n(61),k=n(115),M=n(203),R=n(21),D=n(204),B=n(205),P=n(111),L=n(81).DropCollectionOperation,j=n(81).DropDatabaseOperation,U=n(116),z=n(113),F=n(206),W=n(207),q=n(117),$=n(118),H=n(208),V=n(41),Y=["w","wtimeout","fsync","j","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function G(e,t,n){if(n=n||{},!(this instanceof G))return new G(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,Y)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:f("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||h,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new v(e)},N(e),s(this,"serverConfig",this.s.topology),s(this,"bufferMaxEntries",this.s.bufferMaxEntries),s(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",E(this,"error",this)),t.on("timeout",E(this,"timeout",this)),t.on("close",E(this,"close",this)),t.on("parseError",E(this,"parseError",this)),t.once("open",E(this,"open",this)),t.once("fullsetup",E(this,"fullsetup",this)),t.once("all",E(this,"all",this)),t.on("reconnect",E(this,"reconnect",this)))}o(G,r),Object.defineProperty(G.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(G.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(G.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(G.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(G.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(G.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(G.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),G.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new D(this,e,t);return V(this.s.topology,r,n)},G.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new I(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},G.prototype.admin=function(){return new(n(119))(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];G.prototype.collection=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined),null==(t=m(t,this.s.options,K,!0))||!t.strict)try{const r=new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof p&&n)return n(e);throw e}if("function"!=typeof n)throw u("A callback is required in strict mode. While getting collection "+e);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new p("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},G.prototype.createCollection=S({name:"Db.createCollection",deprecatedOptions:["autoIndexId"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new B(this,e,t);return V(this.s.topology,r,n)})),G.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return V(this.s.topology,r,t)},G.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new i(this.s.topology,new F(this,e,t),t)},G.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},y(this.s.topology,x,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),G.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new $(this.collection(e),t,n);return V(this.s.topology,o,r)},G.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new L(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new j(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new U(this,e,t);return V(this.s.topology,r,n)},G.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},y(this.s.topology,C,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),G.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},G.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new q(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new H(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},y(this.s.topology,A,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),G.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new W(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new z(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.unref=function(){this.s.topology.unref()},G.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new g(this,e,t)},G.prototype.getLogger=function(){return this.s.logger},G.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,G.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,G.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,G.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,G.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,G.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=G},function(e,t,n){"use strict";const r=n(1).Server,o=n(23),s=n(30).TopologyBase,i=n(30).Store,a=n(1).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,p=n(0).mergeOptions;var h=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class f extends s{constructor(e,t,n){super();const s=(n=l(n,h)).promiseLibrary;var f={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},d=n.store||new i(this,f);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var y=p({},{host:e,port:t,disconnectHandler:d,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});y=u(y,n);var g=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;y=u(y,g),this.s={coreTopology:new r(y),sCapabilities:null,clonedOptions:y,reconnect:y.reconnect,emitError:y.emitError,poolSize:y.size,storeOptions:f,store:d,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:s||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(){n.s.store.flush()},i=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",s),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("attemptReconnect",i("attemptReconnect")),n.s.coreTopology.on("monitoring",i("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(f.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(f.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(f.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(f.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=f},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.shuffle=void 0;var r=n(228);function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,s=void 0;try{for(var i,a=e[Symbol.iterator]();!(r=(i=a.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw s}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return i(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else{if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete E[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new p("server instance pool was destroyed"):void 0:new p("server instance is not connected")}A.prototype.connect=function(e){if(e=e||{},T&&(E[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new p(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",I(this,"close")),this.s.pool.on("error",I(this,"error")),this.s.pool.on("timeout",I(this,"timeout")),this.s.pool.on("parseError",I(this,"parseError")),this.s.pool.on("connect",I(this,"connect")),this.s.pool.on("reconnect",I(this,"reconnect")),this.s.pool.on("reconnectFailed",I(this,"reconnectFailed")),S(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:x(this)}),this.emit("serverOpening",{topologyId:x(this),address:this.name}),this.s.pool.connect()},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},A.prototype.lastIsMaster=function(){return this.ismaster},A.prototype.unref=function(){this.s.pool.unref()},A.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},A.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},A.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var s=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof i))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return s?r(s):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),N(this,"command",e,t,n,r)?void 0:v(this,t)?r(new p(`server ${this.name} does not support collation`)):void f.command(this,e,t,n,r))},A.prototype.query=function(e,t,n,r,o){f.query(this,e,t,n,r,o)},A.prototype.getMore=function(e,t,n,r,o){f.getMore(this,e,t,n,r,o)},A.prototype.killCursors=function(e,t,n){f.killCursors(this,e,t,n)},A.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],f.insert(this,e,t,n,r))},A.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"update",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.update(this,e,t,n,r))},A.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"remove",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.remove(this,e,t,n,r))},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},A.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},A.prototype.connections=function(){return this.s.pool.allConnections()},A.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];A.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete E[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool)return this._destroyed=!0,void("function"==typeof t&&t(null,null));e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:x(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:x(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t),this._destroyed=!0}},e.exports=A},function(e,t,n){"use strict";const r=n(146),o=n(92),s=n(87),i=n(2).MongoError,a=n(2).MongoNetworkError,c=n(2).MongoNetworkTimeoutError,u=n(93).defaultAuthProviders,l=n(28).AuthContext,p=n(90),h=n(4).makeClientMetadata,f=p.MAX_SUPPORTED_WIRE_VERSION,d=p.MAX_SUPPORTED_SERVER_VERSION,m=p.MIN_SUPPORTED_WIRE_VERSION,y=p.MIN_SUPPORTED_SERVER_VERSION;let g;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function S(e,t){const n="string"==typeof t.host?t.host:"localhost";if(-1!==n.indexOf("/"))return{path:n};return{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const v=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const p=e&&e.connectionType?e.connectionType:s;null==g&&(g=u(e.bson)),function(e,t,n,s){const i="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const p="boolean"!=typeof t.noDelay||t.noDelay,h="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,f="number"==typeof t.socketTimeout?t.socketTimeout:36e4,d="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>f&&(l=Math.round(f/2));let m;const y=function(e,t){e&&m&&m.destroy(),s(e,t)};try{i?(m=o.connect(function(e,t){const n=S(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null==n.servername&&(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(S(e,t))}catch(e){return y(e)}m.setKeepAlive(u,l),m.setTimeout(h),m.setNoDelay(p);const g=i?"secureConnect":"connect";let w;function _(e){return t=>{v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(g,O),y(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&d)return y(m.authorizationError);m.setTimeout(f),y(null,m)}v.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(g,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!g[o.mechanism])return void r(new i(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||h(n),compression:r},s=e.credentials;if(s){if(s.mechanism.match(/DEFAULT/i)&&s.username)return Object.assign(o,{saslSupportedMechs:`${s.source}.${s.username}`}),void g["scram-sha-256"].prepare(o,e,t);return void g[s.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const p=u.result;if(0===p.ok)return void r(new i(p));const h=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=f;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${f} (MongoDB ${d})`;return new i(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${y})`;return new i(o)}(p,t);if(h)r(h);else{if(!function(e){return!(e instanceof s)}(e)&&p.compression){const n=c.compression.filter(e=>-1!==p.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=p,e.lastIsMasterMS=(new Date).getTime()-l,p.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:p});const t=o.resolveAuthMechanism(p);g[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new p(r,e),e,n)})}},function(e,t,n){"use strict";function r(e){this._head=0,this._tail=0,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,s=this._list[t];if(e0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return s}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var s=this.size(),i=this._list.length;if(!(r>=s||r<-s||t<1)){if(r<0&&(r+=s),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=s)return n=this.toArray(),this.clear(),n;var a;for(r+t>s&&(t=s-r),n=new Array(t),a=0;a0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+i&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(r0;a--)this.unshift(this._list[r=r-1+i&this._capacityMask]);for(r=this._head-1+i&this._capacityMask;o>0;)this._list[r=r-1+i&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+i&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+i&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=i>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,s,i,a=arguments.length,c=this._list.length,u=2;if(!r||n0&&(this._head=this._head+n+c&this._capacityMask)):(i=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{var l=(s=new Array(r-(n+t))).length;for(o=0;othis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(74),o=n(9),s=n(109).isResumableError,i=n(1).MongoError,a=n(23),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,p=n(0).now,h=n(0).calculateDurationInMs,f=n(61),d=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],y=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),g={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of y)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function S(e,t){const n={fullDocument:t.fullDocument||"default"};v(n,t,m),e.type===g.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=v({},t,y),s=new b(e.topology,new f(e.parent,r,t),o);if(c(s,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&s.on("data",(function(t){w(e,t)})),s.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=s.stream(e.streamOptions);for(let n in e.pipeDestinations)t.pipe(n)}return s}function v(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new i("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&s(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=p());const o=n.start||p(),s=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():h(o)>s?r(new i("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=S(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new i("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new i("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[d].push(t)}function T(e,t){for(;e[d].length;){const n=e[d].pop();if(e.isClosed()&&!t)return void n(new i("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const s=n(45),i=n(63),a=n(60);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof s)this.type=g.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof i)this.type=g.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=g.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[d]=new r,this.cursor=S(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[d].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(1).BSON.Long,o=n(1).MongoError,s=n(1).BSON.ObjectID,i=n(1).BSON,a=n(1).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,p=n(0).applyWriteConcern,h=n(0).executeLegacyOperation,f=n(0).isPromiseLike,d=n(0).hasAtomicOperators,m=n(4).maxWireVersion,y=new i([i.Binary,i.Code,i.DBRef,i.Decimal128,i.Double,i.Int32,i.Long,i.Map,i.MaxKey,i.MinKey,i.ObjectId,i.BSONRegExp,i.Symbol,i.Timestamp]);class g{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return ee.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,v(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:y,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(23),s=n(18).CursorState,i=n(5).deprecate;class a extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,i(a.prototype.geoNear,"The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2."),e.exports=a},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(1).MongoError,s=n(23),i=n(18).CursorState;class a extends s{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==i.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(21),s=n(3).defineAspects,i=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?i(e,t):n.ok?i(e,null,!0):void i(e,null,!1))}}s(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,s;e.exports={loadCollection:function(){return r||(r=n(45)),r},loadCursor:function(){return o||(o=n(23)),o},loadDb:function(){return s||(s=n(63)),s}}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=n(227);function s(e){if(!o.existy(e))return null;if(o.not.string(e))throw new TypeError('Expected a string, got "'.concat(r(e),'"'));return e.split(",").map((function(e){var t=e.trim();if(t.includes(":")){var n=t.split(":");if(2===n.length)return n[0]}return t})).find(o.ip)}function i(e){if(e.headers){if(o.ip(e.headers["x-client-ip"]))return e.headers["x-client-ip"];var t=s(e.headers["x-forwarded-for"]);if(o.ip(t))return t;if(o.ip(e.headers["cf-connecting-ip"]))return e.headers["cf-connecting-ip"];if(o.ip(e.headers["fastly-client-ip"]))return e.headers["fastly-client-ip"];if(o.ip(e.headers["true-client-ip"]))return e.headers["true-client-ip"];if(o.ip(e.headers["x-real-ip"]))return e.headers["x-real-ip"];if(o.ip(e.headers["x-cluster-client-ip"]))return e.headers["x-cluster-client-ip"];if(o.ip(e.headers["x-forwarded"]))return e.headers["x-forwarded"];if(o.ip(e.headers["forwarded-for"]))return e.headers["forwarded-for"];if(o.ip(e.headers.forwarded))return e.headers.forwarded}if(o.existy(e.connection)){if(o.ip(e.connection.remoteAddress))return e.connection.remoteAddress;if(o.existy(e.connection.socket)&&o.ip(e.connection.socket.remoteAddress))return e.connection.socket.remoteAddress}return o.existy(e.socket)&&o.ip(e.socket.remoteAddress)?e.socket.remoteAddress:o.existy(e.info)&&o.ip(e.info.remoteAddress)?e.info.remoteAddress:o.existy(e.requestContext)&&o.existy(e.requestContext.identity)&&o.ip(e.requestContext.identity.sourceIp)?e.requestContext.identity.sourceIp:null}e.exports={getClientIpFromXForwardedFor:s,getClientIp:i,mw:function(e){var t=o.not.existy(e)?{}:e;if(o.not.object(t))throw new TypeError("Options must be an object!");var n=t.attributeName||"clientIp";return function(e,t,r){var o=i(e);Object.defineProperty(e,n,{get:function(){return o},configurable:!0}),r()}}}},function(e,t,n){"use strict";const r=n(229),o=n(128),s=n(230);function i(e,t){switch(o(e)){case"object":return function(e,t){if("function"==typeof t)return t(e);if(t||s(e)){const n=new e.constructor;for(let r in e)n[r]=i(e[r],t);return n}return e}(e,t);case"array":return function(e,t){const n=new e.constructor(e.length);for(let r=0;r{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));const s=n.opCode===m?u:c;e.emit("message",new s(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=v++,this.options=t,this.logger=f("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,i,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&C(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new p(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=g.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,x(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=g.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&nt.length)e.buffer=g.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=g.alloc(0);else if(n>4&&ne.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=g.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),x(e,r)}}else e.stubBuffer=g.alloc(t.length),t.copy(e.stubBuffer,0),t=g.alloc(0)}}(this)),O&&(i=this.id,a=this,T[i]=a,_&&_.addConnection(i,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&C(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),null==e&&(e=new h(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function p(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new h(t)):u(void 0,new S(t,this,e))}o.setSocketTimeout(s),E.forEach(e=>o.once(e,l)),o.on("message",p),o.write(a.toBin())}}},function(e,t,n){"use strict";const r=n(14).ServerType,o=n(32).ServerDescription,s=n(90),i=n(14).TopologyType,a=s.MIN_SUPPORTED_SERVER_VERSION,c=s.MAX_SUPPORTED_SERVER_VERSION,u=s.MIN_SUPPORTED_WIRE_VERSION,l=s.MAX_SUPPORTED_WIRE_VERSION;class p{constructor(e,t,n,o,s,p,h){h=h||{},this.type=e||i.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=s||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0,this.localThresholdMS=h.localThresholdMS||0,this.commonWireVersion=p||null,Object.defineProperty(this,"options",{value:h,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersione.isReadable);this.logicalSessionTimeoutMinutes=f.reduce((e,t)=>null==t.logicalSessionTimeoutMinutes?null:null==e?t.logicalSessionTimeoutMinutes:Math.min(e,t.logicalSessionTimeoutMinutes),null)}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new p(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,s=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&s&&e.setName!==s&&(e=new o(t,null));const l=e.type;let d=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),d.set(t,e),n===i.Single)return new p(i.Single,d,s,a,c,u,this.options);if(n===i.Unknown&&(l===r.Standalone&&1!==this.servers.size?d.delete(t):n=function(e){if(e===r.Standalone)return i.Single;if(e===r.Mongos)return i.Sharded;if(e===r.RSPrimary)return i.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return i.Unknown;return i.ReplicaSetNoPrimary}(l)),n===i.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&d.delete(t),n===i.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&d.delete(t),l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=i.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(d,s,e);n=t[0],s=t[1]}if(n===i.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)d.delete(t),n=f(d);else if(l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return f(e)}(d,s,e):f(d);return new p(n,d,s,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function h(e,t,n,s,i){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[f(e),t,s,i];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(s&&i&&(s>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(i,a)>0))return e.set(n.address,new o(n.address)),[f(e),t,s,i];i=n.electionId}null!=n.setVersion&&(null==s||n.setVersion>s)&&(s=n.setVersion);for(const t of e.keys()){const s=e.get(t);if(s.type===r.RSPrimary&&s.address!==n.address){e.set(t,new o(s.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[f(e),t,s,i]}function f(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return i.ReplicaSetWithPrimary;return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:p}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(33).Msg,o=n(20).KillCursor,s=n(20).GetMore,i=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],p=e=>e.ns.split(".")[1],h=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,f=(e,t)=>a.has(e)?{}:t,d={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},y=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],g=e=>{if(e instanceof s)return{getMore:e.cursorId,collection:p(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:p(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:p(e)},Object.keys(d).forEach(n=>{void 0!==e.query[n]&&(t[d[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),y.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof s?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,S=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:h(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=g(t),r=c(n),o=S(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),reply:f(s,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),failure:f(s,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(94),o=n(95),s=n(96),i=n(97),a=n(56).ScramSHA1,c=n(56).ScramSHA256,u=n(151);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(19),o=n(28).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,s=o.username,i=o.password,a=o.source;n.command(a+".$cmd",{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(s+":mongo:"+i,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+s+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:s,nonce:c,key:u};n.command(a+".$cmd",l,t)})}}},function(e,t,n){"use strict";const r=n(28).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.apply(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(10).retrieveBSON,o=n(28).AuthProvider,s=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,i=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new s(`\0${o}\0${i}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(28).AuthProvider,o=n(4).retrieveKerberos;let s;e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(null==s)try{s=o()}catch(e){return t(e,null)}const i=r.username,a=r.password,c=r.mechanismProperties,u=c.gssapiservicename||c.gssapiServiceName||"mongodb",l=new(0,s.processes.MongoAuthProcess)(n.host,n.port,u,c);l.init(i,a,e=>{if(e)return t(e,!1);l.transition("",(e,r)=>{if(e)return t(e,!1);const o={saslStart:1,mechanism:"GSSAPI",payload:r,autoAuthorize:1};n.command("$external.$cmd",o,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,n)=>{if(e)return t(e,!1);const r=n.result;l.transition(null,e=>{if(e)return t(e,null);t(null,r)})})})})})})})})}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";const r=n(155);e.exports={insert:function(e,t,n,o,s){r(e,"insert","documents",t,n,o,s)},update:function(e,t,n,o,s){r(e,"update","updates",t,n,o,s)},remove:function(e,t,n,o,s){r(e,"delete","deletes",t,n,o,s)},killCursors:n(156),getMore:n(157),query:n(158),command:n(40)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(9),o=n(165),s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(2).MongoNetworkTimeoutError,c=n(2).MongoWriteConcernError,u=n(71),l=n(173).StreamDescription,p=n(100),h=n(91),f=n(29).updateSessionFromResponse,d=n(4).uuidV4,m=n(0).now,y=n(0).calculateDurationInMs,g=Symbol("stream"),b=Symbol("queue"),S=Symbol("messageStream"),v=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),E=Symbol("autoEncrypter");function C(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:x.bind(e),isConnected:()=>!0}}};return e[E]&&(t.autoEncrypter=e[E]),t}function x(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[g].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new h.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[S].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return d().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[v]=t.generation,this[w]=m(),t.autoEncrypter&&(this[E]=t.autoEncrypter),this[b]=new Map,this[S]=new o(t),this[S].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[g].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new s(e))}if(e.documents[0]){const o=e.documents[0],i=t.session;if(i&&f(i,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new s(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[g]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new i(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[S]),this[S].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[v]||0}get idleTime(){return y(this[w])}get clusterTime(){return this[_]}get stream(){return this[g]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[g]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[g].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[g].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){p.command(C(this),e,t,n,r)}query(e,t,n,r,o){p.query(C(this),e,t,n,r,o)}getMore(e,t,n,r,o){p.getMore(C(this),e,t,n,r,o)}killCursors(e,t,n){p.killCursors(C(this),e,t,n)}insert(e,t,n,r){p.insert(C(this),e,t,n,r)}update(e,t,n,r){p.update(C(this),e,t,n,r)}remove(e,t,n,r){p.remove(C(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(58);e.exports=b;var o,s=n(168);b.ReadableState=g;n(9).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=n(104),c=n(15).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(42));l.inherits=n(43);var p=n(5),h=void 0;h=p&&p.debuglog?p.debuglog("stream"):function(){};var f,d=n(170),m=n(105);l.inherits(b,a);var y=["error","close","destroy","pause","resume"];function g(e,t){e=e||{};var r=t instanceof(o=o||n(35));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var s=e.highWaterMark,i=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=s||0===s?s:r&&(i||0===i)?i:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=n(107).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(35),!(this instanceof b))return new b(e);this._readableState=new g(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function S(e,t,n,r,o){var s,i=e._readableState;null===t?(i.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,i)):(o||(s=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(i,t)),s?e.emit("error",s):i.objectMode||t&&t.length>0?("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?i.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):v(e,i,t,!0):i.ended?e.emit("error",new Error("stream.push() after EOF")):(i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?v(e,i,t,!1):T(e,i)):v(e,i,t,!1))):r||(i.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(h("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){h("emit readable"),e.emit("readable"),A(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(E,e,t))}function E(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;es.length?s.length:e;if(i===s.length?o+=s:o+=s.slice(0,e),0===(e-=i)){i===s.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(i));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var s=r.data,i=e>s.length?s.length:e;if(s.copy(n,n.length-e,0,i),0===(e-=i)){i===s.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(i));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function I(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return h("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?I(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&I(this),null;var r,o=t.needReadable;return h("need readable",o),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&I(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,h("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){h("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),e.removeListener("close",y),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",d),p=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){h("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,A(e))}}(n);e.on("drain",l);var p=!1;var f=!1;function d(t){h("ondata"),f=!1,!1!==e.write(t)||f||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!p&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,f=!0),n.pause())}function m(t){h("onerror",t),b(),e.removeListener("error",m),0===i(e,"error")&&e.emit("error",t)}function y(){e.removeListener("finish",g),b()}function g(){h("onfinish"),e.removeListener("close",y),b()}function b(){h("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",y),e.once("finish",g),e.emit("pipe",n),o.flowing||(h("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s-1?setImmediate:r.nextTick;y.WritableState=m;var a=Object.create(n(42));a.inherits=n(43);var c={deprecate:n(171)},u=n(104),l=n(15).Buffer,p=global.Uint8Array||function(){};var h,f=n(105);function d(){}function m(e,t){s=s||n(35),e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var p=!1===e.decodeStrings;this.decodeStrings=!p,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,s=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,s){--t.pendingcb,n?(r.nextTick(s,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(s(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,s);else{var a=v(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||S(e,n),o?i(b,e,n,a,s):b(e,n,a,s)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function y(e){if(s=s||n(35),!(h.call(y,this)||this instanceof s))return new y(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function g(e,t,n,r,o,s,i){t.writelen=r,t.writecb=i,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function S(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),i=t.corkedRequestsFree;i.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,g(e,t,!0,t.length,s,"",i.finish),t.pendingcb++,t.lastBufferedRequest=null,i.next?(t.corkedRequestsFree=i.next,i.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,p=n.callback;if(g(e,t,!1,t.objectMode?1:u.length,u,l,p),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function v(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=v(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(y,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===y&&(e&&e._writableState instanceof m)}})):h=function(e){return e instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(e,t,n){var o,s=this._writableState,i=!1,a=!s.objectMode&&(o=e,l.isBuffer(o)||o instanceof p);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=s.defaultEncoding),"function"!=typeof n&&(n=d),s.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var s=!0,i=!1;return null===n?i=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(i=new TypeError("Invalid non-string/buffer chunk")),i&&(e.emit("error",i),r.nextTick(o,i),s=!1),s}(this,s,e,n))&&(s.pendingcb++,i=function(e,t,n,r,o,s){if(!n){var i=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==i&&(n=!0,o="buffer",r=i)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),y.prototype.destroy=f.destroy,y.prototype._undestroy=f.undestroy,y.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(15).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=p,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function i(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return o>0&&(e.lastNeed=o-1),o;if(--r=0)return o>0&&(e.lastNeed=o-2),o;if(--r=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=i;var r=n(35),o=Object.create(n(42));function s(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(1).MongoError,i=n(3).OperationBase;e.exports=class extends i{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let i=this.options;t.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===i.ordered||null==i.ordered?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let c=!1;try{for(let e=0;e{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(21),i=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends s{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=i(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,s.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(21),s=n(3).defineAspects,i=n(19),a=n(0).handleCallback,c=n(0).toError;class u extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=Array.isArray(r.roles)?r.roles:[];0===o.length&&console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:s};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}s(u,r.WRITE_OPERATION),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError,i=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new i("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new s("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(21),s=n(3).defineAspects,i=n(0).handleCallback,a=n(27);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return i(e,t,null);i(e,t,!!n.ok)})}}s(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyWriteConcern,s=n(0).checkCollectionName,i=n(13).executeDbAdminCommand,a=n(0).handleCallback,c=n(82).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();s(n);const p={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(p,{db:t.s.db,collection:t},r),i(t.s.db.admin().s.db,p,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(115),s=n(116),i=n(117),a=n(209),c=n(210),u=n(41);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new s(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,s){const i=Array.prototype.slice.call(arguments,2);s="function"==typeof i[i.length-1]?i.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=i.length?i.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,s)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const s=new i(this.s.db,e,t);return u(this.s.db.s.topology,s,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(1).Topology,o=n(30).ServerCapabilities,s=n(23),i=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:s,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=i(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=i(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(1).Logger,s=n(1).MongoCredentials,i=n(1).MongoError,a=n(122),c=n(120),u=n(1).parseConnectionString,l=n(34),p=n(1).ReadPreference,h=n(123),f=n(64),d=n(1).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,y=n(38),g=n(10).retrieveBSON(),b=n(59).CMAP_EVENT_NAMES;let S;const v=r(n(216),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),w={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},_=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],O=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),T=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],E=["native_parser"],C=["server","replset","replSet","mongos","db"];const x=T.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function A(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function N(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new d(t.s.coreTopology))}function I(e,t){let r=(S||(S=n(60)),S);const o=[];return e instanceof r&&_.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}const k=r(()=>{},"current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.");function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function D(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const s={};"unified"===t&&(s.createServers=!1);const u=F(r,s);if(null!=r.autoEncryption){let t;try{let e=n(124);"function"!=typeof e.extension&&o(new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`")),t=e.extension(n(16)).AutoEncrypter}catch(e){return void o(e)}const s=Object.assign({bson:r.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp])},r.autoEncryption);r.autoEncrypter=new t(e,s)}let l;"mongos"===t?l=new a(u,r):"replicaset"===t?l=new h(u,r):"unified"===t&&(l=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),A(e,l),U(e,l),N(e,l),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):l.connect(r,e=>{if(e)return l.close(!0),void o(e);o(void 0,l)})}):l.connect(r,e=>{if(e)return l.close(!0),o(e);o(void 0,l)})}function B(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"];for(const o in t)-1!==r.indexOf(o.toLowerCase())?e[o]=t[o]:-1!==n.indexOf(o.toLowerCase())?e=j(e,t[o],!1):!t[o]||"object"!=typeof t[o]||Buffer.isBuffer(t[o])||Array.isArray(t[o])?e[o]=t[o]:e=j(e,t[o],!0);return e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!O.has(c))throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new s({mechanism:w[c],mechanismProperties:u,source:o,username:t,password:n})}function L(e){return j(B({},e),e,!1)}function j(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=j(e,t[r],n):e[r]=t[r];return e}function U(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(b).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function z(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=x[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;return(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS),e.srvHost&&(t.srvHost=e.srvHost),t}function F(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new p(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=36e4),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new f(t.domain_socket,27017,e):new f(t.host,t.port,e))}e.exports={validOptions:function(e){const t=T.concat(C);for(const n in e)if(-1===E.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new i(`option ${n} is not supported`);console.warn(`the options [${n}] is not supported`)}-1!==C.indexOf(n)&&console.warn(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${T}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let s=!1;const c=o("MongoClient",n);if(t instanceof f||t instanceof h||t instanceof a)return function(e,t,n,r){N(e,t),A(e,t),U(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new p(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,d=l?z:L;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new i(o));s&&e.emit("authenticated",null,!0),r(t,n)}(l?u:v)(t,n,(t,o)=>{if(t)return r(t);const i=d(o),a=B(i,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=36e4),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,null!=a.journal&&(a.j=a.journal,a.journal=void 0),function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,0===i.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{s=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?D(e,"unified",a,m):(k(),a.replicaSet||a.rs_name?D(e,"replicaset",a,m):i.servers.length>1?D(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=F(t)[0],o=I(e,r);r.connect(t,(s,i)=>{if(s)return r.close(!0),n(s);!function(e){_.forEach(t=>e.removeAllListeners(t))}(r),U(e,r),A(e,r);const a=i.lastIsMaster();if(N(e,i),a&&"isdbgrid"===a.msg)return i.close(),D(e,"mongos",t,n);!function(e,t){for(let n=0;n0?t.socketOptions:t;g=l(g,b),this.s={coreTopology:new s(m,g),sCapabilities:null,debug:g.debug,storeOptions:r,clonedOptions:g,store:d,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",s("joined")),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";const r=n(64),o=n(23),s=n(1).MongoError,i=n(30).TopologyBase,a=n(30).Store,c=n(1).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,p=n(0).filterOptions,h=n(0).mergeOptions;var f=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class d extends i{constructor(e,t){super();var n=this;t=p(t=t||{},f);for(var i=0;i0?t.socketOptions:t;g=l(g,b);var S=new c(y,g);S.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:S,sCapabilities:null,tag:t.tag,storeOptions:d,clonedOptions:g,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},g.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return S}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,s=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("ping",s("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var i=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,i)})),n.s.coreTopology.removeListener("connect",i),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";let r;function o(){return r||(r=i(n(16))),r}const s=n(65).MongoCryptError;function i(e){const t={mongodb:e};return t.stateMachine=n(217)(t),t.autoEncrypter=n(218)(t),t.clientEncryption=n(222)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:s}}e.exports={extension:i,MongoCryptError:s,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(38),s=n(37),i=n(219),a=s.join,c=s.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||s.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=s.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,i=require,c=[],u=0,p=e.try.length;u{let s;try{s=r.createHmac(e,t).update(n).digest()}catch(e){return e}return s.copy(o),s.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let s;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},aes256CbcDecryptHook:function(e,t,n,o){let s;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length}}},function(e,t,n){"use strict";var r=n(1).BSON.Binary,o=n(1).BSON.ObjectID,s=n(15).Buffer,i=function(e,t,n){if(!(this instanceof i))return new i(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=s.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=s.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!s.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};i.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},i.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},i.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=s.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},i.prototype.eof=function(){return this.internalPosition===this.length()},i.prototype.getc=function(){return this.read(1)},i.prototype.rewind=function(){this.internalPosition=0,this.data=new r},i.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var s={upsert:!0};for(var i in e)s[i]=e[i];for(i in n.writeConcern)s[i]=n.writeConcern[i];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var i in n.writeConcern)r[i]=n.writeConcern[i];o.replaceOne({_id:n.objectId},e,s,(function(e){t(e,n)}))})):t(null,n)}))},i.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},i.prototype.length=function(){return this.data.length()},Object.defineProperty(i.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),i.DEFAULT_CHUNK_SIZE=261120,e.exports=i},function(e,t){var n=Object.prototype.toString;function r(e){return"function"==typeof e.constructor?e.constructor.name:null}e.exports=function(e){if(void 0===e)return"undefined";if(null===e)return"null";var t=typeof e;if("boolean"===t)return"boolean";if("string"===t)return"string";if("number"===t)return"number";if("symbol"===t)return"symbol";if("function"===t)return"GeneratorFunction"===r(e)?"generatorfunction":"function";if(function(e){return Array.isArray?Array.isArray(e):e instanceof Array}(e))return"array";if(function(e){if(e.constructor&&"function"==typeof e.constructor.isBuffer)return e.constructor.isBuffer(e);return!1}(e))return"buffer";if(function(e){try{if("number"==typeof e.length&&"function"==typeof e.callee)return!0}catch(e){if(-1!==e.message.indexOf("callee"))return!0}return!1}(e))return"arguments";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";if(function(e){return e instanceof RegExp||"string"==typeof e.flags&&"boolean"==typeof e.ignoreCase&&"boolean"==typeof e.multiline&&"boolean"==typeof e.global}(e))return"regexp";switch(r(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(function(e){return"function"==typeof e.throw&&"function"==typeof e.return&&"function"==typeof e.next}(e))return"generator";switch(t=n.call(e)){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")}},function(e,t,n){"use strict"; +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=236)}([function(e,t,n){"use strict";const r=n(2).MongoError,o=n(29);var s=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},i=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;nprocess.emitWarning(e,"DeprecationWarning"):e=>console.error(e);function l(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(92),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class h{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new h(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new h(e.substring(0,t),e.substring(t+1))}}function f(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],s=0;s{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const s=e.s.promiseLibrary;let i,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),i=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:i})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(i&&i.owner===c&&!o.returnsCursor)i.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new s((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,s=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const i=o.fromOptions(n);return i?Object.assign(e,{writeConcern:i}):s&&s.writeConcern?Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const s=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!s||!s.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:l,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(o.hasOwnProperty(t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(u(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:h,emitDeprecationWarning:u,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:f,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=f()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,s=!1;const i=(t=t||{}).interval||1e3,a=t.minInterval||500;function c(e){s||(clearTimeout(n),n=setTimeout(u,e||i))}function u(){o=0,r=f(),e(e=>{if(e)throw e;c(i)})}return"boolean"==typeof t.immediate&&t.immediate?u():(r=f(),c()),{wake:function(){const e=f(),t=e-o,n=e-r,s=Math.max(i-n,0);o=e,ta&&c(a)},stop:function(){s=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){if(Array.isArray(t))return t.reduce((t,n)=>t||e(n),null);const n=Object.keys(t);return n.length>0&&"$"===n[0][0]}}},function(e,t,n){"use strict";let r=n(88);const o=n(72),s=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(2).MongoError,MongoNetworkError:n(2).MongoNetworkError,MongoParseError:n(2).MongoParseError,MongoTimeoutError:n(2).MongoTimeoutError,MongoServerSelectionError:n(2).MongoServerSelectionError,MongoWriteConcernError:n(2).MongoWriteConcernError,Connection:n(90),Server:n(75),ReplSet:n(160),Mongos:n(162),Logger:n(19),Cursor:n(20).CoreCursor,ReadPreference:n(13),Sessions:n(31),BSON:r,EJSON:s,Topology:n(163).Topology,Query:n(22).Query,MongoCredentials:n(101).MongoCredentials,defaultAuthProviders:n(96).defaultAuthProviders,MongoCR:n(97),X509:n(98),Plain:n(99),GSSAPI:n(100),ScramSHA1:n(58).ScramSHA1,ScramSHA256:n(58).ScramSHA256,parseConnectionString:n(179)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const s=Symbol("beforeHandshake");class i extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[s]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),p=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const h=new Set([91,189,11600,11602,13436]),f=new Set([10107,13435]),d=new Set([11600,91]);function m(e){return!(!e.code||!h.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:i,MongoNetworkTimeoutError:class extends i{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof i||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&f.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&d.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?p.has(e.code)||p.has(e.result.code):p.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[s]}}},function(e,t,n){"use strict";const r={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS")};e.exports={Aspect:r,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){this.options=Object.assign({},e)}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";const r=n(143),o=n(21),s=n(72);const i=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=null;try{e=s("mongodb-extjson")}catch(e){}return e||(e={parse:i,deserialize:i,serialize:i,stringify:i,setBSONModule:i,BSON:i}),e},retrieveKerberos:function(){let e;try{e=s("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;re===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(144).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"d",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"a",(function(){return c})),n.d(t,"f",(function(){return u}));class r extends Error{}class o extends r{constructor(e,t){super(`${e}${t=t?": "+t:""}`)}}class s extends o{constructor(e){super(s.name,e)}}class i extends o{constructor(e){super(i.name,e||"data upsert failed")}}class a extends o{constructor(e){super(a.name,e?`expected valid ObjectId instance, got "${e}" instead`:"invalid ObjectId encountered")}}class c extends o{constructor(){super(c.name,"invalid API key encountered")}}class u extends o{constructor(e){super(u.name,null!=e?e:"validation failed")}}},function(e,t,n){"use strict";const r=n(13),o=n(2).MongoError,s=n(15).ServerType,i=n(91).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===s.Mongos)return!0;if(e.description&&e.description instanceof i){return Array.from(e.description.servers.values()).some(e=>e.type===s.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";e.exports=(e,t)=>{if(void 0===t&&(t=e,e=0),"number"!=typeof e||"number"!=typeof t)throw new TypeError("Expected all arguments to be numbers");return Math.floor(Math.random()*(t-e+1)+e)}},function(e,t,n){"use strict";const r=n(13),o=n(15).TopologyType,s=n(2).MongoError,i=n(2).isRetryableWriteError,a=n(4).maxWireVersion,c=n(2).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},p=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},h=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},f=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},d=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:s,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var s=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name}),function(e,t,n){var r=f(e,t);return f(e,n)!==r}(e,e.s.ismaster,o.result)&&p(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?f(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=s}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(d(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function y(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const g=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&y(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},inquireServerState:d,getTopologyType:f,emitServerDescriptionChanged:p,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:h(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:g,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new s({message:b,errmsg:b,originalError:e}):e},topologyType:y,legacyIsRetryableWriteError:function(e,t){return e instanceof s&&(g(t)&&(e instanceof c||a(t)<9&&i(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(72);function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){var e=n(88);e.native=!1;try{var t=r("bson-ext");if(t)return t.native=!0,t}catch(e){}return e},retrieveSnappy:function(){var e=null;try{e=r("snappy")}catch(e){}return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).MongoError,p=n(1).ReadPreference,h=n(0).toError,f=n(20).CursorState;function d(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),s(u,e,e.cmd)):s(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),i(u,e),u},deleteCallback:function(e,t,n){if(null!=n){if(e&&n)return n(e);if(null==t)return n(null,{result:{ok:1}});t.deletedCount=t.result.n,n&&n(null,t)}},findAndModify:function(e,t,n,i,l,h){const f={findAndModify:e.collectionName,query:t};(n=c(n))&&(f.sort=n),f.new=!!l.new,f.remove=!!l.remove,f.upsert=!!l.upsert;const d=l.projection||l.fields;d&&(f.fields=d),l.arrayFilters&&(f.arrayFilters=l.arrayFilters,delete l.arrayFilters),i&&!l.remove&&(f.update=i),l.maxTimeMS&&(f.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(f.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(f.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=p.primary;try{s(f,e,m)}catch(e){return h(e,null)}a(e.s.db,f,m,(e,t)=>e?u(h,e,null):u(h,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(h(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n{if(e.s.state=f.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:d,insertDocuments:function(e,t,n,s){"function"==typeof n&&(s=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},n);i=r(i,e.s.db),i=o(i,{db:e.s.db,collection:e},n),!0===i.keepGoing&&(i.ordered=!1),i.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=d(e,t,n),e.s.topology.insert(e.s.namespace,t,i,(e,n)=>{if(null!=s){if(e)return u(s,e);if(null==n)return u(s,null,null);if(n.result.code)return u(s,h(n.result));if(n.result.writeErrors)return u(s,h(n.result.writeErrors[0]));n.ops=t,u(s,null,n)}})},removeDocuments:function(e,t,n,i){"function"==typeof n?(i=n,n={}):"function"==typeof t&&(i=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{s(a,e,n)}catch(e){return i(e,null)}e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=i)return e?u(i,e,null):null==t?u(i,null,null):t.result.code?u(i,h(t.result)):t.result.writeErrors?u(i,h(t.result.writeErrors[0])):void u(i,null,t)})},updateDocuments:function(e,t,n,i,a){if("function"==typeof i&&(a=i,i=null),null==i&&(i={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(h("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(h("document must be a valid JavaScript object"));let c=Object.assign({},i);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},i),c.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const l={q:t,u:n};l.upsert=void 0!==i.upsert&&!!i.upsert,l.multi=void 0!==i.multi&&!!i.multi,i.hint&&(l.hint=i.hint),c.arrayFilters&&(l.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&l.multi&&(c.retryWrites=!1);try{s(c,e,i)}catch(e){return a(e,null)}e.s.topology.update(e.s.namespace,[l],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,h(t.result)):t.result.writeErrors?u(a,h(t.result.writeErrors[0])):void u(a,null,t)})},updateCallback:function(e,t,n){if(null!=n){if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}}}},function(e,t,n){"use strict";const r=function(e,t,n){if(!r.isValid(e))throw new TypeError("Invalid read preference mode "+e);if(t&&!Array.isArray(t)){console.warn("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,r=void 0!==t.hedge;e||r?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===r.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(r.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),r.PRIMARY="primary",r.PRIMARY_PREFERRED="primaryPreferred",r.SECONDARY="secondary",r.SECONDARY_PREFERRED="secondaryPreferred",r.NEAREST="nearest";const o=[r.PRIMARY,r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST,null];r.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,o=e.maxStalenessSeconds;if("string"==typeof t)return new r(t,n);if(!(t instanceof r)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new r(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||o,hedge:t.hedge})}return t},r.resolve=function(e,t){const n=(t=t||{}).session,o=e&&e.readPreference;let s;return s=t.readPreference?r.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=o?o:r.primary,"string"==typeof s?new r(s):s},r.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new r(t);else if(!t||t instanceof r||"object"!=typeof t){if(!(t instanceof r))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new r(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},r.isValid=function(e){return-1!==o.indexOf(e)},r.prototype.isValid=function(e){return r.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];r.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},r.prototype.equals=function(e){return e.mode===this.mode},r.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},r.primary=new r("primary"),r.primaryPreferred=new r("primaryPreferred"),r.secondary=new r("secondary"),r.secondaryPreferred=new r("secondaryPreferred"),r.nearest=new r("nearest"),e.exports=r},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).debugOptions,i=n(0).handleCallback,a=n(1).MongoError,c=n(0).parseIndexOptions,u=n(1).ReadPreference,l=n(0).toError,p=n(80),h=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function d(e,t,n,o,s){let h=Object.assign({},{readPreference:u.PRIMARY},o);if(h=r(h,{db:e},o),h.writeConcern&&"function"!=typeof s)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));!function(e,t,n,o,s){const p=c(n),h="string"==typeof o.name?o.name:p.name,f=[{name:h,key:p.fieldHash}],d=Object.keys(f[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===d.indexOf(e)&&(f[0][e]=o[e]);const y=e.s.topology.capabilities();if(f[0].collation&&y&&!y.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,s(e)}const g=r({createIndexes:t,indexes:f},{db:e},o);o.readPreference=u.PRIMARY,m(e,g,o,(e,t)=>e?i(s,e,null):0===t.ok?i(s,l(t),null):void i(s,null,h))}(e,t,n,h,(r,c)=>{if(null==r)return i(s,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return i(s,r,c);const u=g(e,t,n,o);h.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(p.SYSTEM_INDEX_COLLECTION),u,h,(e,t)=>{if(null!=s)return e?i(s,e):null==t?i(s,null,null):t.result.writeErrors?i(s,a.create(t.result.writeErrors[0]),null):void i(s,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(s(f,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?i(r,e):n.full?i(r,null,t):void i(r,null,t.result))}function y(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?i(r,null,t):void i(r,null,function(e){let t={};for(let n=0;n0){n.emit(t,r,e);for(let n=0;n{if(null!=r&&26!==r.code)return i(s,r,null);if(null!=a&&a[l]){if("function"==typeof s)return i(s,null,l)}else d(e,t,n,o,s)})},evaluate:function(e,t,n,r,s){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let p={$eval:c,args:l};r.nolock&&(p.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,p,r,(e,t)=>e?i(s,e,null):t&&1===t.ok?i(s,null,t.retval):t?i(s,a.create({message:"eval failed: "+t.errmsg,driver:!0}),null):void i(s,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new h("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?i(r,t):void i(r,null,n.result))},indexInformation:y,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n"undefined"==typeof window,i=n(69),a=n(6);function c(e=!1){const t={NODE_ENV:"development",MONGODB_URI:"mongodb://127.0.0.1:27017/hscc-api-airports".toString(),MONGODB_MS_PORT:parseInt(null!=="6666"?"6666":"-Infinity"),DISABLED_API_VERSIONS:[],FLIGHTS_GENERATE_DAYS:parseInt(null!=="1"?"1":"-Infinity"),AIRPORT_NUM_OF_GATE_LETTERS:parseInt(null!=="4"?"4":"-Infinity"),AIRPORT_GATE_NUMBERS_PER_LETTER:parseInt(null!=="20"?"20":"-Infinity"),AIRPORT_PAIR_USED_PERCENT:parseInt(null!=="75"?"75":"-Infinity"),FLIGHT_HOUR_HAS_FLIGHTS_PERCENT:parseInt(null!=="66"?"66":"-Infinity"),RESULTS_PER_PAGE:parseInt(null!=="100"?"100":"-Infinity"),IGNORE_RATE_LIMITS:!1,LOCKOUT_ALL_KEYS:!1,DISALLOWED_METHODS:[],REQUESTS_PER_CONTRIVED_ERROR:parseInt(null!=="10"?"10":"-Infinity"),MAX_CONTENT_LENGTH_BYTES:Object(o.parse)("100kb"),HYDRATE_DB_ON_STARTUP:!Object(r.isUndefined)("true")&&!0,DEBUG_MODE:/--debug|--inspect/.test(process.execArgv.join(" "))},n=e=>s()?[e]:[],c=[t.FLIGHTS_GENERATE_DAYS,t.AIRPORT_NUM_OF_GATE_LETTERS,t.AIRPORT_GATE_NUMBERS_PER_LETTER,...n(t.AIRPORT_PAIR_USED_PERCENT),...n(t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT),t.RESULTS_PER_PAGE,t.REQUESTS_PER_CONTRIVED_ERROR,t.MAX_CONTENT_LENGTH_BYTES];e&&"development"==t.NODE_ENV&&console.info("debug - "+t);if("unknown"==t.NODE_ENV||s()&&""===t.MONGODB_URI||c.some(e=>!Object(r.isNumber)(e)||e<0))throw new a.b("illegal environment detected, check environment variables");if(t.RESULTS_PER_PAGE= "+i.a);if(t.AIRPORT_NUM_OF_GATE_LETTERS>26)throw new a.b("AIRPORT_NUM_OF_GATE_LETTERS must be <= 26");if(s()&&t.AIRPORT_PAIR_USED_PERCENT>100)throw new a.b("AIRPORT_PAIR_USED_PERCENT must between 0 and 100");if(s()&&t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT>100)throw new a.b("FLIGHT_HOUR_HAS_FLIGHTS_PERCENT must between 0 and 100");if(s()&&t.MONGODB_MS_PORT&&t.MONGODB_MS_PORT<=1024)throw new a.b("optional environment variable MONGODB_MS_PORT must be > 1024");return t}},function(e,t,n){"use strict";var r=n(5).format,o=n(2).MongoError,s={},i={},a=null,c=process.pid,u=null,l=function(e,t){if(!(this instanceof l))return new l(e,t);t=t||{},this.className=e,t.logger?u=t.logger:null==u&&(u=console.log),t.loggerLevel&&(a=t.loggerLevel||"error"),null==i[this.className]&&(s[this.className]=!0)};l.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",i={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(i={},t.forEach((function(e){i[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(19),o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(4).collationNotSupported,c=n(13),u=n(4).isUnifiedTopology,l=n(43),p=n(24).Readable,h=n(0).SUPPORTS,f=n(0).MongoDBNamespace,d=n(3).OperationBase,m=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function g(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class b extends p{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof d&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=f.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const s=e.s.options;"boolean"==typeof s.promoteLongs?this.cursorState.promoteLongs=s.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof s.promoteValues?this.cursorState.promoteValues=s.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof s.promoteBuffers?this.cursorState.promoteBuffers=s.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),s.reconnect&&(this.cursorState.reconnect=s.reconnect),this.logger=r("Cursor",s),"number"==typeof n?(this.cursorState.cursorId=m.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof m&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return g(t,new s("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new s("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new s("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);if(t.cursorState.cursorIndex!==t.cursorState.documents.length||m.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId))return g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&m.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return t.kill(),S(t,(function(){g(n,new s(e?e.$err:void 0))}));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),g(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new i("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return w(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,i){return r?g(n,r):(t.connection=i,0===t.cursorState.documents.length&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId)?g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!m.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){return this.topology.cursor(this.ns,this.cmd,this.options)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return v(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new s(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new s(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?m.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const i=o.cursorId||0;t.cursorState.cursorId=i instanceof m?i:m.fromNumber(i),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,i)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=i,t.cursorState.init=!0,a(t.server,t.cmd))return e(new s(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void i.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);i.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,v(e,t)}function v(e,t){w(e,()=>g(t,null,null))}function w(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}h.ASYNC_ITERATOR&&(b.prototype[Symbol.asyncIterator]=n(92).asyncIterator),e.exports={CursorState:y,CoreCursor:b}},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(11).retrieveBSON)().Long;const o=n(16).Buffer;var s=0,i=n(7).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=s++},a.nextRequestId=function(){return s+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var s=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+s.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=i.OP_QUERY>>24&255,r[c+2]=i.OP_QUERY>>16&255,r[c+1]=i.OP_QUERY>>8&255,r[c]=255&i.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++s};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=s++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_GETMORE>>24&255,n[t+2]=i.OP_GETMORE>>16&255,n[t+1]=i.OP_GETMORE>>8&255,n[t]=255&i.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=s++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_KILL_CURSORS>>24&255,n[t+2]=i.OP_KILL_CURSORS>>16&255,n[t+1]=i.OP_KILL_CURSORS>>8&255,n[t]=255&i.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,s){s=s||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=s,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof s.promoteLongs||s.promoteLongs,this.promoteValues="boolean"!=typeof s.promoteValues||s.promoteValues,this.promoteBuffers="boolean"==typeof s.promoteBuffers&&s.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var s=0;st?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t){e.exports=require("stream")},function(e,t,n){"use strict";const r=n(24).Transform,o=n(24).PassThrough,s=n(5).deprecate,i=n(0).handleCallback,a=n(1).ReadPreference,c=n(1).MongoError,u=n(20).CoreCursor,l=n(20).CursorState,p=n(1).BSON.Map,h=n(0).maybePromise,f=n(43),d=n(0).formattedOrderClause,m=n(181).each,y=n(182),g=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],b=["numberOfRetries","tailableRetryInterval"];class S extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,s=r.tailableRetryInterval||500,i=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return h(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===S.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return h(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=d(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===b.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${b}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===g.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${g}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:e+" is not a valid query modifier",driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new p(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,m(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{m(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});m(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return h(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,s)=>{if(o)return i(e,o);if(null==s)return t.close({skipKillCursors:!0},()=>i(e,null,n));if(n.push(s),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new y(this,e,t);return f(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),h(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e){return this.operation&&null==this.operation.cmd?(this.operation.options.explain=!0,this.operation.fullResponse=!1,f(this.topology,this.operation,e)):(this.cmd.explain=!0,this.cmd.readConcern&&delete this.cmd.readConcern,h(this,e,e=>{u.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}S.prototype.maxTimeMs=S.prototype.maxTimeMS,s(S.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),s(S.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),s(S.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=S},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).OperationBase,s=n(1).ReadPreference,i=n(36),a=n(29),c=n(4).maxWireVersion,u=n(31).commandSupportsReadConcern,l=n(2).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=s.resolve(o,this.options),this.readConcern=function(e,t){return i.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),this.explain=!1,n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,s=c(e),i=this.session&&this.session.inTransaction();this.readConcern&&u(t)&&!i&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&s<5?n(new l(`Server ${e.name}, which reports wire version ${s}, does not support collation`)):(s>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t,n){"use strict";const r=n(11).retrieveSnappy(),o=n(145),s={snappy:1,zlib:2},i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:s,uncompressibleCommands:i,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var s={};e.options.zlibCompressionLevel&&(s.level=e.options.zlibCompressionLevel),o.deflate(t,s,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>s.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case s.snappy:r.uncompress(t,n);break;case s.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","fsync"]);class o{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new o(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new o(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j,e.writeConcern.fsync)}return new o(e.w,e.wtimeout,e.j,e.fsync)}}}e.exports=o},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(10),s=r(),i=s.Binary,a=n(4).uuidV4,c=n(2).MongoError,u=n(2).isRetryableError,l=n(2).MongoNetworkError,p=n(2).MongoWriteConcernError,h=n(41).Transaction,f=n(41).TxnState,d=n(4).isPromiseLike,m=n(13),y=n(41).isTransactionCommand,g=n(9).resolveClusterTime,b=n(7).isSharded,S=n(4).maxWireVersion,v=n(0).now,w=n(0).calculateDurationInMs;function _(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const O=Symbol("serverSession");class T extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof M))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[O]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new h}get id(){return this.serverSession.id}get serverSession(){return null==this[O]&&(this[O]=this.sessionPool.acquire()),this[O]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},this.hasEnded||(this.serverSession&&this.inTransaction()&&this.abortTransaction(),this.sessionPool.release(this.serverSession),this[O]=void 0,this.hasEnded=!0,this.emit("ended",this)),"function"==typeof t&&t(null,null)}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof T&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(_(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(b(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new h(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(f.STARTING_TRANSACTION)}commitTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"commitTransaction",(n,r)=>n?t(n):e(r))});I(this,"commitTransaction",e)}abortTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"abortTransaction",(n,r)=>n?t(n):e(r))});I(this,"abortTransaction",e)}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return N(this,v(),e,t)}}const E=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function C(e,t){return w(e){if(!function(e){return A.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(s=>{if(s instanceof c&&C(n,12e4)&&!x(s)){if(s.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(s.hasErrorLabel("TransientTransactionError"))return N(t,n,r,o)}throw s})}(e,t,n,r)}).catch(o=>{function s(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&C(t,12e4))return N(e,t,n,r);throw x(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>s(o)):s(o)})}function I(e,t,n){if(!_(e,n))return;let r=e.transaction.state;if(r===f.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===f.STARTING_TRANSACTION||r===f.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(f.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===f.STARTING_TRANSACTION)return e.transaction.transition(f.TRANSACTION_ABORTED),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===f.TRANSACTION_COMMITTED||r===f.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let s;function i(r,o){var s;"commitTransaction"===t?(e.transaction.transition(f.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof p||u(r)||x(r))&&(x(s=r)||!E.has(s.codeName)&&100!==s.code&&79!==s.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(f.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?s=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(s={w:e.clientOptions.w}),r===f.TRANSACTION_COMMITTED&&(s=Object.assign({wtimeout:1e4},s,{w:"majority"})),s&&Object.assign(o,{writeConcern:s}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>i(a(e),t));i(a(t),n)})}class k{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)},this.lastUse=v(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(w(this.lastUse)%864e5%36e5/6e4)>e-1}}class M{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new k}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function R(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:T,ServerSession:k,ServerSessionPool:M,TxnState:f,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=v(),t.lsid=r.id;const o=e.inTransaction()||y(t),i=n.willRetryWrite,a=R(t,n);if(r.txnNumber&&(i||o)&&(t.txnNumber=s.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==f.NO_TRANSACTION&&e.transaction.transition(f.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c("Read preference in a transaction must be primary, not: "+n.readPreference.mode);if(t.autocommit=!1,e.transaction.state===f.STARTING_TRANSACTION){e.transaction.transition(f.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&g(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:R}},function(e,t,n){"use strict";const r=n(10),o=n(1).MongoError,s=n(5).format,i=n(1).ReadPreference,a=n(1).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:i})},c.prototype.addObjectAndMethod=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:i})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?(n&&r||n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)||!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode))&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):(n&&r||n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)||!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode))&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var p=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,s=!1,i=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,s=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(i=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",s),t(this,"hasListCollectionsCommand",i),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class h extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new p(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,i.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=i.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=i.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(h.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(h.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(h.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(h.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=p,t.TopologyBase=h},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===i.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=(":"+this.port).length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===h(this.topologyVersion,e.topologyVersion);return null!=e&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:p,compareTopologyVersion:h}},function(e,t,n){"use strict";const r=n(16).Buffer,o=n(7).opcodes,s=n(7).databaseNamespace,i=n(13);let a=0;class c{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=s(t),r.readPreference&&r.readPreference.mode!==i.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:c.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let s=n.length;const i=this.command;return s+=this.makeDocumentSegment(e,i),n.writeInt32LE(s,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}c.getRequestId=function(){return a=a+1&2147483647,a};e.exports={Msg:c,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(s.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(s.BUFFER_SIZE+this.buffer.length)):new Array(s.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(s=0;sthis.position?t:this.position}else if("string"==typeof e){for(s=0;sthis.position?t:this.position}},s.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r=6&&null==t.__nodejs_mock_server__}(e),b=h.session;let S=e.clusterTime,v=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(S.clusterTime)&&(S=b.clusterTime);const e=l(b,v,h);if(e)return f(e)}S&&(v.$clusterTime=S),a(e)&&!g&&y&&"primary"!==y.mode&&(v={$query:v,$readPreference:y.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},h);w.slaveOk=y.slaveOk();const _=c(t)+".$cmd",O=g?new o(d,_,v,w):new r(d,_,v,w),T=b&&(b.inTransaction()||u(v))?function(e){return e&&e instanceof p&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),f.apply(null,arguments)}:f;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new s(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return h(e)&&e.autoEncrypter}(e))return void f(e,t,n,r,o);const i=h(e);"number"!=typeof i||i<8?o(new s("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const s=e.autoEncrypter;function i(e,t){e||null==t?o(e,t):s.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}s.encrypt(t,n,r,(n,s)=>{n?o(n,null):f(e,t,s,r,i)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(3).Aspect,s=n(3).OperationBase,i=n(13),a=n(2).isRetryableError,c=n(4).maxWireVersion,u=n(4).isUnifiedTopology;function l(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");if(u(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){const r=e.s.promiseLibrary;let o;"function"!=typeof n&&(o=new r((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));return e.selectServer(i.primaryPreferred,r=>{r?n(r):l(e,t,n)}),o}(e,t,n);const c=e.s.promiseLibrary;let h,f,d;if(e.hasSessionSupport())if(null==t.session)f=Symbol(),h=e.startSession({owner:f}),t.session=h;else if(t.session.hasEnded)throw new r("Use of expired sessions is not permitted");function m(e,r){h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),n(e,r)}"function"!=typeof n&&(d=new c((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));try{t.hasAspect(o.EXECUTE_WITH_SELECTION)?function(e,t,n){const s=t.readPreference||i.primary,c=t.session&&t.session.inTransaction();if(c&&!s.equals(i.primary))return void n(new r("Read preference in a transaction must be primary, not: "+s.mode));const u={readPreference:s,session:t.session};function l(r,o){return null==r?n(null,o):a(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,s)=>{if(r)return void n(r,null);const i=!1!==e.s.options.retryReads&&t.session&&!c&&p(s)&&t.canRetryRead;t.hasAspect(o.RETRYABLE)&&i?t.execute(s,l):t.execute(s,n)})}(e,t,m):t.execute(m)}catch(e){throw h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),e}return d}function p(e){return c(e)>=6}e.exports=l},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(170)}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(14).createIndex,i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(14).ensureIndex,u=n(14).evaluate,l=n(14).executeCommand,p=n(0).handleCallback,h=n(14).indexInformation,f=n(1).BSON.Long,d=n(1).MongoError,m=n(1).ReadPreference,y=n(12).insertDocuments,g=n(12).updateDocuments;function b(e,t,n){h(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){s(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}),h.group.key=e}(f=Object.assign({},f)).readPreference=m.resolve(e,f),a(h,e,f);try{i(h,e,f)}catch(e){return d(e,null)}l(e.s.db,h,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.retval)})}else{const i=null!=s&&"Code"===s._bsontype?s.scope:{};i.ns=e.collectionName,i.keys=t,i.condition=n,i.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,s.toString()+";");u(e.s.db,new o(a,i),null,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),h(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return p(r,e,null);if(!Array.isArray(t))return p(r,null,null!=n[t]);for(let e=0;e{if(r)return p(n,r,null);if(null==s)return p(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const i=[];o&&(t.raw=o);for(let n=0;n{if(null!=o)return null==t?p(o,null,null):e?p(o,e,null):void p(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,s=n(0).checkCollectionName,i=n(1).BSON.ObjectID,a=n(1).MongoError,c=n(0).normalizeHintField,u=n(0).decorateCommand,l=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,h=n(0).formattedOrderClause,f=n(1).ReadPreference,d=n(183),m=n(184),y=n(79),g=n(0).executeLegacyOperation,b=n(29),S=n(36),v=n(0).MongoDBNamespace,w=n(82),_=n(83),O=n(46).ensureIndex,T=n(46).group,E=n(46).parallelCollectionScan,C=n(12).removeDocuments,x=n(46).save,A=n(12).updateDocuments,N=n(63),I=n(113),k=n(185),M=n(114),R=n(186),D=n(187),B=n(188),P=n(84).DropCollectionOperation,L=n(115),j=n(189),U=n(190),z=n(191),F=n(192),W=n(64),q=n(193),$=n(194),H=n(195),V=n(196),Y=n(197),G=n(198),K=n(116),X=n(199),J=n(200),Z=n(201),Q=n(202),ee=n(203),te=n(117),ne=n(121),re=n(212),oe=n(213),se=n(214),ie=n(215),ae=n(216),ce=n(43),ue=["ignoreUndefined"];function le(e,t,n,r,o,a){s(r);const c=null==a||null==a.slaveOk?e.slaveOk:a.slaveOk,u=null==a||null==a.serializeFunctions?e.s.options.serializeFunctions:a.serializeFunctions,l=null==a||null==a.raw?e.s.options.raw:a.raw,p=null==a||null==a.promoteLongs?e.s.options.promoteLongs:a.promoteLongs,h=null==a||null==a.promoteValues?e.s.options.promoteValues:a.promoteValues,d=null==a||null==a.promoteBuffers?e.s.options.promoteBuffers:a.promoteBuffers,m=new v(n,r),y=a.promiseLibrary||Promise;o=null==o?i:o,this.s={pkFactory:o,db:e,topology:t,options:a,namespace:m,readPreference:f.fromOptions(a),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:p,promoteValues:h,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:y,readConcern:S.fromOptions(a),writeConcern:b.fromOptions(a)}}Object.defineProperty(le.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(le.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(le.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(le.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(le.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(le.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(le.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function he(e,t,n,r,o){const s=Array.prototype.slice.call(arguments,1);return o="function"==typeof s[s.length-1]?s.pop():void 0,t=s.length&&s.shift()||[],n=s.length?s.shift():null,r=s.length&&s.shift()||{},(r=Object.assign({},r)).readPreference=f.PRIMARY,ce(this.s.topology,new W(this,e,t,n,r),o)}le.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let i=Object.assign({},t);for(let e in this.s.options)-1!==ue.indexOf(e)&&(i[e]=this.s.options[e]);if(i.skip=t.skip?t.skip:0,i.limit=t.limit?t.limit:0,i.raw="boolean"==typeof t.raw?t.raw:this.s.raw,i.hint=null!=t.hint?c(t.hint):this.s.collectionHint,i.timeout=void 0===t.timeout?void 0:t.timeout,i.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,i.readPreference=f.resolve(this,i),null==i.readPreference||"primary"===i.readPreference&&"primary"===i.readPreference.mode||(i.slaveOk=!0),null!=r&&"object"!=typeof r)throw a.create({message:"query selector must be an object",driver:!0});const d={find:this.s.namespace.toString(),limit:i.limit,skip:i.skip,query:r};"boolean"==typeof t.allowDiskUse&&(d.allowDiskUse=t.allowDiskUse),"boolean"==typeof i.awaitdata&&(i.awaitData=i.awaitdata),"boolean"==typeof i.timeout&&(i.noCursorTimeout=i.timeout),u(d,i,["session","collation"]),s&&(d.fields=s),i.db=this.s.db,i.promiseLibrary=this.s.promiseLibrary,null==i.raw&&"boolean"==typeof this.s.raw&&(i.raw=this.s.raw),null==i.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(i.promoteLongs=this.s.promoteLongs),null==i.promoteValues&&"boolean"==typeof this.s.promoteValues&&(i.promoteValues=this.s.promoteValues),null==i.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(i.promoteBuffers=this.s.promoteBuffers),d.sort&&(d.sort=h(d.sort)),p(d,this,t);try{l(d,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const m=this.s.topology.cursor(new z(this,this.s.namespace,d,i),i);if("function"!=typeof n)return m;n(null,m)})),le.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new J(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ce(this.s.topology,r,n)},le.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw a.create({message:"operations must be an array of documents",driver:!0});const r=new I(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),le.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ae(this,e,t,n),r)},le.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new oe(this,e,t,n),r)},le.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ie(this,e,t,n),r)},le.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,A,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),le.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeOne=le.prototype.deleteOne,le.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new R(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeMany=le.prototype.deleteMany,le.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,C,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),le.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,x,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),le.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new F(this,e=e||{},t=t||{});return ce(this.s.topology,r,n)})),le.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:f.PRIMARY});const r=new ne(this,e,t);return ce(this.s.topology,r,n)},le.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new P(this.s.db,this.collectionName,e);return ce(this.s.topology,n,t)},le.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new te(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Z(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=f.PRIMARY;const o=new L(this,e,t);return ce(this.s.topology,o,n)},le.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new j(this,e);return ce(this.s.topology,n,t)},le.prototype.dropAllIndexes=r(le.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),le.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new re(this,e=e||{});return ce(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),le.prototype.listIndexes=function(e){return new _(this.s.topology,new Q(this,e),e)},le.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},g(this.s.topology,O,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),le.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ce(this.s.topology,r,n)},le.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new K(this.s.db,this.collectionName,e);return ce(this.s.topology,r,t)},le.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ce(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),le.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new k(this,e,t);return ce(this.s.topology,o,n)},le.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const s=o.length&&o.shift()||{},i=o.length&&o.shift()||{},a=new B(this,e,s,i);return ce(this.s.topology,a,r)},le.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ce(this.s.topology,r,t)},le.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},ce(this.s.topology,new q(this,e,t),n)},le.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new $(this,e,t,n),r)},le.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new H(this,e,t,n),r)},le.prototype.findAndModify=r(he,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),le.prototype._findAndModify=he,le.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ce(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),le.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new w(this.s.topology,new N(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},le.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},le.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=f.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),g(this.s.topology,E,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),le.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const s=new V(this,e,t,n);return ce(this.s.topology,s,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),le.prototype.group=r((function(e,t,n,r,o,s,i,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,s=c.length?c.shift():null,i=c.length&&c.shift()||{},"function"!=typeof o&&(s=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),s=null==s||s,g(this.s.topology,T,[this,e,t,n,r,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),le.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new ee(this,e,t,n);return ce(this.s.topology,o,r)},le.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,d(this.s.topology,this,e)},le.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},le.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=le},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&s,r[5]=s>>8&255,r[4]=s>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof h?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var p=[];for(l=0;l<10;)p[48+l]=l++;for(;l<16;)p[55+l]=p[87+l]=l++;var h=Buffer,f=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new h(12),n=0,r=0;r<24;)t[n++]=p[e.charCodeAt(r++)]<<4|p[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&i.test(e):e instanceof c||(e instanceof h||"function"==typeof e.toHexString&&(e.id instanceof h||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&i.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(s),D=e.match(i);if(!M&&!R&&!D||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!f(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(h.toBuffer(n?u:l));if("N"===e[k])return new m(h.toBuffer(c))}for(;f(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||y)&&(y||(w=b),y=!0,_[T++]=parseInt(e[k],10),O+=1),y&&(S+=1),d&&(v+=1),b+=1,k+=1;else{if(d)return new m(h.toBuffer(c));d=!0,k+=1}if(d&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var B=e.substr(++k).match(p);if(!B||!B[2])return new m(h.toBuffer(c));x=parseInt(B[0],10),k+=B[0].length}if(e[k])return new m(h.toBuffer(c));if(E=0,O){if(C=O-1,g=S,0!==x&&1!==g)for(;"0"===e[w+g-1];)g-=1}else E=0,C=0,_[0]=0,S=1,O=1,g=0;for(x<=v&&v-x>16384?x=-6176:x-=v;x>6111;){if((C+=1)-E>34){var P=_.join("");if(P.match(/^0+$/)){x=6111;break}return new m(h.toBuffer(n?u:l))}x-=1}for(;x<-6176||O=5&&(U=1,5===j))for(U=_[C]%2==1,A=w+C+2;A=0&&++_[z]>9;z--)if(_[z]=0,0===z){if(!(x<6111))return new m(h.toBuffer(n?u:l));x+=1,_[z]=1}}if(N=r.fromNumber(0),I=r.fromNumber(0),0===g)N=r.fromNumber(0),I=r.fromNumber(0);else if(C-E<17)for(z=E,I=r.fromNumber(_[z++]),N=new r(0,0);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));else{for(z=E,N=r.fromNumber(_[z++]);z<=C-17;z++)N=(N=N.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));for(I=r.fromNumber(_[z++]);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]))}var F,W,q,$,H=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new r(t.getLowBits(),0),a=n.multiply(s),c=n.multiply(i),u=o.multiply(s),l=o.multiply(i);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(N,r.fromString("100000000000000000"));H.low=H.low.add(I),F=H.low,W=I,q=F.high_>>>0,$=W.high_>>>0,(q<$||q===$&&F.low_>>>0>>0)&&(H.high=H.high.add(r.fromNumber(1))),t=x+a;var V={low:r.fromNumber(0),high:r.fromNumber(0)};H.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(V.high=V.high.or(r.fromNumber(3).shiftLeft(61)),V.high=V.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),V.high=V.high.or(H.high.and(r.fromNumber(0x7fffffffffff)))):(V.high=V.high.or(r.fromNumber(16383&t).shiftLeft(49)),V.high=V.high.or(H.high.and(r.fromNumber(562949953421311)))),V.low=H.low,n&&(V.high=V.high.or(r.fromString("9223372036854775808")));var Y=h.allocBuffer(16);return k=0,Y[k++]=255&V.low.low_,Y[k++]=V.low.low_>>8&255,Y[k++]=V.low.low_>>16&255,Y[k++]=V.low.low_>>24&255,Y[k++]=255&V.low.high_,Y[k++]=V.low.high_>>8&255,Y[k++]=V.low.high_>>16&255,Y[k++]=V.low.high_>>24&255,Y[k++]=255&V.high.low_,Y[k++]=V.high.low_>>8&255,Y[k++]=V.high.low_>>16&255,Y[k++]=V.high.low_>>24&255,Y[k++]=255&V.high.high_,Y[k++]=V.high.high_>>8&255,Y[k++]=V.high.high_>>16&255,Y[k++]=V.high.high_>>24&255,new m(Y)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,s,i,c=0,u=new Array(36),l=0;l>26&31)>>3==3){if(30===s)return v.join("")+"Infinity";if(31===s)return"NaN";i=e>>15&16383,f=8+(e>>14&1)}else f=e>>14&7,i=e>>17&16383;if(p=i-a,S.parts[0]=(16383&e)+((15&f)<<14),S.parts[1]=t,S.parts[2]=n,S.parts[3]=o,0===S.parts[0]&&0===S.parts[1]&&0===S.parts[2]&&0===S.parts[3])b=!0;else for(y=3;y>=0;y--){var _=0,O=d(S);if(S=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*y+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[g]=0;else for(c=36,l=0;!u[g];)l++,c-=1,g+=1;if((h=c-1+p)>=34||h<=-7||p>0){for(v.push(u[g++]),(c-=1)&&v.push("."),l=0;l0?v.push("+"+h):v.push(h)}else if(p>=0)for(l=0;l0)for(l=0;l{if(r)return n(r);Object.assign(t,{nonce:s});const i=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(f(o,i,s),{db:i.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?d(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,s=t.nonce,i=o.source,a=f(e,o,s);r.command(i+".$cmd",a,(r,o)=>{const s=v(r,o);if(s)return n(s);d(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function h(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function f(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new c(o.concat([o.from("n,,","utf8"),h(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function d(e,t,n,s){const a=n.connection,l=n.credentials,f=n.nonce,d=l.source,w=p(l.username),_=l.password;let O;if("sha256"===e)O=u?u(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new i("username must be a string");if("string"!=typeof t)throw new i("password must be a string");if(0===t.length)throw new i("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(w,_)}catch(e){return s(e)}const T=o.isBuffer(t.payload)?new c(t.payload):t.payload,E=m(T.value()),C=parseInt(E.i,10);if(C&&C<4096)return void s(new i("Server returned an invalid iteration count "+C),!1);const x=E.s,A=E.r;if(A.startsWith("nonce"))return void s(new i("Server returned an invalid nonce: "+A),!1);const N="c=biws,r="+A,I=function(e,t,n,o){const s=[e,t.toString("base64"),n].join("_");if(void 0!==g[s])return g[s];const i=r.pbkdf2Sync(e,t,n,S[o],o);b>=200&&(g={},b=0);return g[s]=i,b+=1,i}(O,o.from(x,"base64"),C,e),k=y(e,I,"Client Key"),M=y(e,I,"Server Key"),R=(D=e,B=k,r.createHash(D).update(B).digest());var D,B;const P=[h(w,f),T.value().toString("base64"),N].join(","),L=[N,"p="+function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o{const n=v(e,t);if(n)return s(n);const c=t.result,u=m(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r{const n=m(t.s.options);if(n)return e(n);d(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},y.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),y.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return h(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof f))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.autoEncrypter;o?o.teardown(e,e=>r(t||e)):r(t)}):r()})},y.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},y.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},y.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new y(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},y.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");if(!this.topology.hasSessionSupport())throw new a("Current topology does not support sessions");return this.topology.startSession(e,this.s.options)},y.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},y.prototype.getLogger=function(){return this.s.options.logger},e.exports=y},function(e,t,n){"use strict";const r=n(26),o=n(1).MongoError,s=n(4).maxWireVersion,i=n(1).ReadPreference,a=n(3).Aspect,c=n(3).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=i.primary),n.explain&&(this.readConcern||this.writeConcern))throw new o('"explain" cannot be used on an aggregate call with readConcern/writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=s(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),n.explain&&(n.full=!1,o.explain=n.explain),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyRetryableWrites,s=n(0).applyWriteConcern,i=n(0).decorateWithCollation,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(4).maxWireVersion,h=n(112).MongoError;e.exports=class extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),f=this.doc;let d=this.options;const m={findAndModify:t.collectionName,query:n};r&&(m.sort=r),m.new=!!d.new,m.remove=!!d.remove,m.upsert=!!d.upsert;const y=d.projection||d.fields;y&&(m.fields=y),d.arrayFilters&&(m.arrayFilters=d.arrayFilters),f&&!d.remove&&(m.update=f),d.maxTimeMS&&(m.maxTimeMS=d.maxTimeMS),d.serializeFunctions=d.serializeFunctions||t.s.serializeFunctions,d.checkKeys=!1,d=o(d,t.s.db),d=s(d,{db:t.s.db,collection:t},d),d.writeConcern&&(m.writeConcern=d.writeConcern),!0===d.bypassDocumentValidation&&(m.bypassDocumentValidation=d.bypassDocumentValidation),d.readPreference=l.primary;try{i(m,t,d)}catch(t){return e(t,null)}if(d.hint){if(d.writeConcern&&0===d.writeConcern.w||p(t.s.topology)<8)return void e(new h("The current topology does not support a hint on findAndModify commands"));m.hint=d.hint}a(t.s.db,m,d,(t,n)=>t?u(e,t,null):u(e,null,n))}}},function(e,t,n){"use strict";const r=n(10).EventEmitter,o=n(5).inherits,s=n(0).getSingleProperty,i=n(83),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(1).ReadPreference,p=n(1).MongoError,h=n(1).ObjectID,f=n(1).Logger,d=n(47),m=n(0).mergeOptionsAndWriteConcern,y=n(0).executeLegacyOperation,g=n(79),b=n(5).deprecate,S=n(0).deprecateOptions,v=n(0).MongoDBNamespace,w=n(80),_=n(29),O=n(36),T=n(82),E=n(14).createListener,C=n(14).ensureIndex,x=n(14).evaluate,A=n(14).profilingInfo,N=n(14).validateDatabaseName,I=n(63),k=n(118),M=n(204),R=n(23),D=n(205),B=n(206),P=n(114),L=n(84).DropCollectionOperation,j=n(84).DropDatabaseOperation,U=n(119),z=n(116),F=n(207),W=n(208),q=n(120),$=n(121),H=n(209),V=n(43),Y=["w","wtimeout","fsync","j","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function G(e,t,n){if(n=n||{},!(this instanceof G))return new G(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,Y)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:f("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||h,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new v(e)},N(e),s(this,"serverConfig",this.s.topology),s(this,"bufferMaxEntries",this.s.bufferMaxEntries),s(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",E(this,"error",this)),t.on("timeout",E(this,"timeout",this)),t.on("close",E(this,"close",this)),t.on("parseError",E(this,"parseError",this)),t.once("open",E(this,"open",this)),t.once("fullsetup",E(this,"fullsetup",this)),t.once("all",E(this,"all",this)),t.on("reconnect",E(this,"reconnect",this)))}o(G,r),Object.defineProperty(G.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(G.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(G.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(G.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(G.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(G.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(G.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),G.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new D(this,e,t);return V(this.s.topology,r,n)},G.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new I(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},G.prototype.admin=function(){return new(n(122))(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];G.prototype.collection=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined),null==(t=m(t,this.s.options,K,!0))||!t.strict)try{const r=new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof p&&n)return n(e);throw e}if("function"!=typeof n)throw u("A callback is required in strict mode. While getting collection "+e);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new p("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},G.prototype.createCollection=S({name:"Db.createCollection",deprecatedOptions:["autoIndexId"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new B(this,e,t);return V(this.s.topology,r,n)})),G.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return V(this.s.topology,r,t)},G.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new i(this.s.topology,new F(this,e,t),t)},G.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},y(this.s.topology,x,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),G.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new $(this.collection(e),t,n);return V(this.s.topology,o,r)},G.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new L(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new j(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new U(this,e,t);return V(this.s.topology,r,n)},G.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},y(this.s.topology,C,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),G.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},G.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new q(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new H(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},y(this.s.topology,A,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),G.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new W(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new z(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.unref=function(){this.s.topology.unref()},G.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new g(this,e,t)},G.prototype.getLogger=function(){return this.s.logger},G.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,G.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,G.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,G.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,G.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,G.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=G},function(e,t,n){"use strict";const r=n(1).Server,o=n(25),s=n(32).TopologyBase,i=n(32).Store,a=n(1).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,p=n(0).mergeOptions;var h=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class f extends s{constructor(e,t,n){super();const s=(n=l(n,h)).promiseLibrary;var f={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},d=n.store||new i(this,f);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var y=p({},{host:e,port:t,disconnectHandler:d,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});y=u(y,n);var g=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;y=u(y,g),this.s={coreTopology:new r(y),sCapabilities:null,clonedOptions:y,reconnect:y.reconnect,emitError:y.emitError,poolSize:y.size,storeOptions:f,store:d,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:s||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(){n.s.store.flush()},i=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",s),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("attemptReconnect",i("attemptReconnect")),n.s.coreTopology.on("monitoring",i("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(f.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(f.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(f.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(f.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=f},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.shuffle=void 0;var r=n(229);function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,s=void 0;try{for(var i,a=e[Symbol.iterator]();!(r=(i=a.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw s}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return i(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);np()(1,100),w=e=>36e5*Math.floor(e/36e5),_=e=>{const t=(Math.floor(e/1e3).toString(16)+b+(++g).toString(16)).padEnd(24,"0");return new r.ObjectId(t)},O=await y.deleteMany({_id:{$lt:_(Date.now()-6048e5)}});!e&&console.info(`api - Deleted ${O.deletedCount} flights older than 7 days`);const T=w((null!==(t=null===(n=await y.find().sort({_id:-1}).limit(1).next())||void 0===n?void 0:n._id)&&void 0!==t?t:new r.ObjectId).getTimestamp().getTime()),E=(w(Date.now()+S)-T)/36e5;if(!e&&console.info(`api - Generating ${E} hours worth of flights...`),!E)return 0;const C=[...Array(9999)].map((e,t)=>t+1),x="abcdefghijklmnopqrstuvwxyz".split("").slice(0,Object(o.a)().AIRPORT_NUM_OF_GATE_LETTERS).map(e=>[...Array(Object(o.a)().AIRPORT_GATE_NUMBERS_PER_LETTER)].map((t,n)=>`${e}${n+1}`)).flat(),A=[];let N=!1;[...Array(E)].forEach((t,n)=>{if(v()>Object(o.a)().FLIGHT_HOUR_HAS_FLIGHTS_PERCENT)return;const r=T+36e5+36e5*n,s=Object(a.shuffle)(l).slice(0,p()(2,l.length)),i=s.reduce((e,t)=>({...e,[t._id.toHexString()]:f()(u()(C))}),{});!e&&console.info(`api ↳ Generating flights for hour ${r} (${n+1}/${E})`),c.forEach(e=>{const t=Object(a.shuffle)(u()(x)),n=e=>t.push(e),l=()=>{const e=t.shift();if(!e)throw new d.d("ran out of gates");return e},f=[];c.forEach(t=>{e._id.equals(t._id)||v()>Object(o.a)().AIRPORT_PAIR_USED_PERCENT||s.forEach(n=>{N=!N;const o=p()(0,10),s=p()(0,4),u={};let l=p()(60,150),d=p()(5e3,8e3);const m=[...Array(h.seatClasses.length)].map(e=>p()(10,100/h.seatClasses.length)).sort((e,t)=>t-e);m[0]+=100-m.reduce((e,t)=>e+t,0);for(const[e,t]of Object.entries(h.seatClasses))l=p()(l,2*l)+Number(Math.random().toFixed(2)),d=p()(d,2*d),u[t]={total:m[Number(e)],priceDollars:l,priceFfms:d};const y={};let g=1,b=p()(10,150);for(const e of h.allExtras)v()>75||(g=p()(g,2.5*g)+Number(Math.random().toFixed(2)),b=p()(b,2*b),y[e]={priceDollars:g,priceFfms:b});f.push({_id:_(r),bookerKey:N?null:e.chapterKey,type:N?"arrival":"departure",airline:n.name,comingFrom:N?t.shortName:Object(a.shuffle)(c).filter(t=>t.shortName!=e.shortName)[0].shortName,landingAt:e.shortName,departingTo:N?null:t.shortName,flightNumber:n.codePrefix+i[n._id.toHexString()]().toString(),baggage:{checked:{max:o,prices:[...Array(o)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||35))]},[])},carry:{max:s,prices:[...Array(s)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||15))]},[])}},ffms:p()(2e3,6e3),seats:u,extras:y})})});const m=e=>{if(!e.stochasticStates)throw new d.d("expected stochastic state to exist");return Object.values(e.stochasticStates).slice(-1)[0]};f.forEach(e=>{let t=0,n=!1;const o="arrival"==e.type,s=p()(r,r+36e5-(o?96e4:186e4));e.stochasticStates={0:{arriveAtReceiver:s,departFromSender:s-p()(72e5,18e6),departFromReceiver:o?null:s+9e5,status:"scheduled",gate:null}};for(let r=1;!n&&r<3;++r){const o={...m(e)};switch(r){case 1:t=o.departFromSender,v()>80?(o.status="cancelled",n=!0):o.status="on time",e.stochasticStates[t.toString()]=o;break;case 2:v()>75&&(t=p()(o.arriveAtReceiver-72e5,o.departFromSender+9e5),o.status="delayed",o.arriveAtReceiver+=p()(3e5,9e5),o.departFromReceiver&&(o.departFromReceiver+=p()(3e5,9e5)),e.stochasticStates[t.toString()]=o);break;default:throw new d.d("unreachable stage encountered (1)")}}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 3 encountered impossible condition");const t=m(e);"cancelled"!=t.status&&(e.stochasticStates[p()(t.arriveAtReceiver-72e5,t.arriveAtReceiver-9e5).toString()]={...t,gate:l()})}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 4 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>50&&(n(r),r=l()),e.stochasticStates[p()(t.arriveAtReceiver-18e5,t.arriveAtReceiver-3e5).toString()]={...t,gate:r,status:"landed"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 5 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>85&&(n(r),r=l()),e.stochasticStates[t.arriveAtReceiver]={...t,gate:r,status:"arrived"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 6-9 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let n=0,o=!1;const s="arrival"==e.type;for(let i=6;!o&&i<10;++i){const a={...t};switch(i){case 6:if(!s)continue;n=r+36e5,a.status="past",a.gate=null,o=!0;break;case 7:if(s)throw new d.d("arrival type encountered in departure-only model");n=a.arriveAtReceiver+p()(18e4,6e5),a.status="boarding";break;case 8:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (1)");n=a.departFromReceiver,a.status="departed";break;case 9:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (2)");n=a.departFromReceiver+p()(72e5,18e6),a.status="past",a.gate=null;break;default:throw new d.d("unreachable stage encountered (2)")}e.stochasticStates[n.toString()]=a}}),A.push(...f)})});try{if(!A.length)return 0;!e&&console.info(`api - Committing ${A.length} flights into database...`);const t=await y.insertMany(A);if(!t.result.ok)throw new d.c("flight insertion failed");if(t.insertedCount!=A.length)throw new d.d("assert failed: operation.insertedCount != totalHoursToGenerate");return!e&&console.info("api - Operation completed successfully!"),t.insertedCount}catch(e){throw e instanceof d.b?e:new d.c(e)}}},function(e,t,n){"use strict";if(void 0!==global.Map)e.exports=global.Map,e.exports.Map=global.Map;else{var r=function(e){this._keys=[],this._values={};for(var t=0;t{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else{if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete E[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new p("server instance pool was destroyed"):void 0:new p("server instance is not connected")}A.prototype.connect=function(e){if(e=e||{},T&&(E[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new p(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",I(this,"close")),this.s.pool.on("error",I(this,"error")),this.s.pool.on("timeout",I(this,"timeout")),this.s.pool.on("parseError",I(this,"parseError")),this.s.pool.on("connect",I(this,"connect")),this.s.pool.on("reconnect",I(this,"reconnect")),this.s.pool.on("reconnectFailed",I(this,"reconnectFailed")),S(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:x(this)}),this.emit("serverOpening",{topologyId:x(this),address:this.name}),this.s.pool.connect()},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},A.prototype.lastIsMaster=function(){return this.ismaster},A.prototype.unref=function(){this.s.pool.unref()},A.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},A.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},A.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var s=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof i))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return s?r(s):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),N(this,"command",e,t,n,r)?void 0:v(this,t)?r(new p(`server ${this.name} does not support collation`)):void f.command(this,e,t,n,r))},A.prototype.query=function(e,t,n,r,o){f.query(this,e,t,n,r,o)},A.prototype.getMore=function(e,t,n,r,o){f.getMore(this,e,t,n,r,o)},A.prototype.killCursors=function(e,t,n){f.killCursors(this,e,t,n)},A.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],f.insert(this,e,t,n,r))},A.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"update",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.update(this,e,t,n,r))},A.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"remove",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.remove(this,e,t,n,r))},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},A.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},A.prototype.connections=function(){return this.s.pool.allConnections()},A.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];A.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete E[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool)return this._destroyed=!0,void("function"==typeof t&&t(null,null));e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:x(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:x(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t),this._destroyed=!0}},e.exports=A},function(e,t,n){"use strict";const r=n(147),o=n(95),s=n(90),i=n(2).MongoError,a=n(2).MongoNetworkError,c=n(2).MongoNetworkTimeoutError,u=n(96).defaultAuthProviders,l=n(30).AuthContext,p=n(93),h=n(4).makeClientMetadata,f=p.MAX_SUPPORTED_WIRE_VERSION,d=p.MAX_SUPPORTED_SERVER_VERSION,m=p.MIN_SUPPORTED_WIRE_VERSION,y=p.MIN_SUPPORTED_SERVER_VERSION;let g;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function S(e,t){const n="string"==typeof t.host?t.host:"localhost";if(-1!==n.indexOf("/"))return{path:n};return{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const v=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const p=e&&e.connectionType?e.connectionType:s;null==g&&(g=u(e.bson)),function(e,t,n,s){const i="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const p="boolean"!=typeof t.noDelay||t.noDelay,h="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,f="number"==typeof t.socketTimeout?t.socketTimeout:36e4,d="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>f&&(l=Math.round(f/2));let m;const y=function(e,t){e&&m&&m.destroy(),s(e,t)};try{i?(m=o.connect(function(e,t){const n=S(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null==n.servername&&(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(S(e,t))}catch(e){return y(e)}m.setKeepAlive(u,l),m.setTimeout(h),m.setNoDelay(p);const g=i?"secureConnect":"connect";let w;function _(e){return t=>{v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(g,O),y(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&d)return y(m.authorizationError);m.setTimeout(f),y(null,m)}v.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(g,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!g[o.mechanism])return void r(new i(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||h(n),compression:r},s=e.credentials;if(s){if(s.mechanism.match(/DEFAULT/i)&&s.username)return Object.assign(o,{saslSupportedMechs:`${s.source}.${s.username}`}),void g["scram-sha-256"].prepare(o,e,t);return void g[s.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const p=u.result;if(0===p.ok)return void r(new i(p));const h=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=f;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${f} (MongoDB ${d})`;return new i(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${y})`;return new i(o)}(p,t);if(h)r(h);else{if(!function(e){return!(e instanceof s)}(e)&&p.compression){const n=c.compression.filter(e=>-1!==p.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=p,e.lastIsMasterMS=(new Date).getTime()-l,p.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:p});const t=o.resolveAuthMechanism(p);g[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new p(r,e),e,n)})}},function(e,t,n){"use strict";function r(e){this._head=0,this._tail=0,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,s=this._list[t];if(e0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return s}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var s=this.size(),i=this._list.length;if(!(r>=s||r<-s||t<1)){if(r<0&&(r+=s),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=s)return n=this.toArray(),this.clear(),n;var a;for(r+t>s&&(t=s-r),n=new Array(t),a=0;a0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+i&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(r0;a--)this.unshift(this._list[r=r-1+i&this._capacityMask]);for(r=this._head-1+i&this._capacityMask;o>0;)this._list[r=r-1+i&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+i&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+i&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=i>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,s,i,a=arguments.length,c=this._list.length,u=2;if(!r||n0&&(this._head=this._head+n+c&this._capacityMask)):(i=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{var l=(s=new Array(r-(n+t))).length;for(o=0;othis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(77),o=n(10),s=n(112).isResumableError,i=n(1).MongoError,a=n(25),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,p=n(0).now,h=n(0).calculateDurationInMs,f=n(63),d=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],y=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),g={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of y)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function S(e,t){const n={fullDocument:t.fullDocument||"default"};v(n,t,m),e.type===g.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=v({},t,y),s=new b(e.topology,new f(e.parent,r,t),o);if(c(s,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&s.on("data",(function(t){w(e,t)})),s.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=s.stream(e.streamOptions);for(let n in e.pipeDestinations)t.pipe(n)}return s}function v(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new i("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&s(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=p());const o=n.start||p(),s=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():h(o)>s?r(new i("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=S(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new i("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new i("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[d].push(t)}function T(e,t){for(;e[d].length;){const n=e[d].pop();if(e.isClosed()&&!t)return void n(new i("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const s=n(47),i=n(65),a=n(62);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof s)this.type=g.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof i)this.type=g.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=g.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[d]=new r,this.cursor=S(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[d].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(1).BSON.Long,o=n(1).MongoError,s=n(1).BSON.ObjectID,i=n(1).BSON,a=n(1).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,p=n(0).applyWriteConcern,h=n(0).executeLegacyOperation,f=n(0).isPromiseLike,d=n(0).hasAtomicOperators,m=n(4).maxWireVersion,y=new i([i.Binary,i.Code,i.DBRef,i.Decimal128,i.Double,i.Int32,i.Long,i.Map,i.MaxKey,i.MinKey,i.ObjectId,i.BSONRegExp,i.Symbol,i.Timestamp]);class g{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return ee.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,v(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:y,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(25),s=n(20).CursorState,i=n(5).deprecate;class a extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,i(a.prototype.geoNear,"The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2."),e.exports=a},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(1).MongoError,s=n(25),i=n(20).CursorState;class a extends s{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==i.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?i(e,t):n.ok?i(e,null,!0):void i(e,null,!1))}}s(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,s;e.exports={loadCollection:function(){return r||(r=n(47)),r},loadCursor:function(){return o||(o=n(25)),o},loadDb:function(){return s||(s=n(65)),s}}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=n(228);function s(e){if(!o.existy(e))return null;if(o.not.string(e))throw new TypeError('Expected a string, got "'.concat(r(e),'"'));return e.split(",").map((function(e){var t=e.trim();if(t.includes(":")){var n=t.split(":");if(2===n.length)return n[0]}return t})).find(o.ip)}function i(e){if(e.headers){if(o.ip(e.headers["x-client-ip"]))return e.headers["x-client-ip"];var t=s(e.headers["x-forwarded-for"]);if(o.ip(t))return t;if(o.ip(e.headers["cf-connecting-ip"]))return e.headers["cf-connecting-ip"];if(o.ip(e.headers["fastly-client-ip"]))return e.headers["fastly-client-ip"];if(o.ip(e.headers["true-client-ip"]))return e.headers["true-client-ip"];if(o.ip(e.headers["x-real-ip"]))return e.headers["x-real-ip"];if(o.ip(e.headers["x-cluster-client-ip"]))return e.headers["x-cluster-client-ip"];if(o.ip(e.headers["x-forwarded"]))return e.headers["x-forwarded"];if(o.ip(e.headers["forwarded-for"]))return e.headers["forwarded-for"];if(o.ip(e.headers.forwarded))return e.headers.forwarded}if(o.existy(e.connection)){if(o.ip(e.connection.remoteAddress))return e.connection.remoteAddress;if(o.existy(e.connection.socket)&&o.ip(e.connection.socket.remoteAddress))return e.connection.socket.remoteAddress}return o.existy(e.socket)&&o.ip(e.socket.remoteAddress)?e.socket.remoteAddress:o.existy(e.info)&&o.ip(e.info.remoteAddress)?e.info.remoteAddress:o.existy(e.requestContext)&&o.existy(e.requestContext.identity)&&o.ip(e.requestContext.identity.sourceIp)?e.requestContext.identity.sourceIp:null}e.exports={getClientIpFromXForwardedFor:s,getClientIp:i,mw:function(e){var t=o.not.existy(e)?{}:e;if(o.not.object(t))throw new TypeError("Options must be an object!");var n=t.attributeName||"clientIp";return function(e,t,r){var o=i(e);Object.defineProperty(e,n,{get:function(){return o},configurable:!0}),r()}}}},function(e,t,n){"use strict";const r=n(230),o=n(131),s=n(231);function i(e,t){switch(o(e)){case"object":return function(e,t){if("function"==typeof t)return t(e);if(t||s(e)){const n=new e.constructor;for(let r in e)n[r]=i(e[r],t);return n}return e}(e,t);case"array":return function(e,t){const n=new e.constructor(e.length);for(let r=0;r{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));const s=n.opCode===m?u:c;e.emit("message",new s(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=v++,this.options=t,this.logger=f("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,i,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&C(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new p(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=g.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,x(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=g.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&nt.length)e.buffer=g.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=g.alloc(0);else if(n>4&&ne.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=g.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),x(e,r)}}else e.stubBuffer=g.alloc(t.length),t.copy(e.stubBuffer,0),t=g.alloc(0)}}(this)),O&&(i=this.id,a=this,T[i]=a,_&&_.addConnection(i,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&C(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),null==e&&(e=new h(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function p(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new h(t)):u(void 0,new S(t,this,e))}o.setSocketTimeout(s),E.forEach(e=>o.once(e,l)),o.on("message",p),o.write(a.toBin())}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(34).ServerDescription,s=n(93),i=n(15).TopologyType,a=s.MIN_SUPPORTED_SERVER_VERSION,c=s.MAX_SUPPORTED_SERVER_VERSION,u=s.MIN_SUPPORTED_WIRE_VERSION,l=s.MAX_SUPPORTED_WIRE_VERSION;class p{constructor(e,t,n,o,s,p,h){h=h||{},this.type=e||i.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=s||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0,this.localThresholdMS=h.localThresholdMS||0,this.commonWireVersion=p||null,Object.defineProperty(this,"options",{value:h,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersione.isReadable);this.logicalSessionTimeoutMinutes=f.reduce((e,t)=>null==t.logicalSessionTimeoutMinutes?null:null==e?t.logicalSessionTimeoutMinutes:Math.min(e,t.logicalSessionTimeoutMinutes),null)}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new p(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,s=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&s&&e.setName!==s&&(e=new o(t,null));const l=e.type;let d=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),d.set(t,e),n===i.Single)return new p(i.Single,d,s,a,c,u,this.options);if(n===i.Unknown&&(l===r.Standalone&&1!==this.servers.size?d.delete(t):n=function(e){if(e===r.Standalone)return i.Single;if(e===r.Mongos)return i.Sharded;if(e===r.RSPrimary)return i.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return i.Unknown;return i.ReplicaSetNoPrimary}(l)),n===i.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&d.delete(t),n===i.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&d.delete(t),l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=i.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(d,s,e);n=t[0],s=t[1]}if(n===i.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)d.delete(t),n=f(d);else if(l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return f(e)}(d,s,e):f(d);return new p(n,d,s,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function h(e,t,n,s,i){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[f(e),t,s,i];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(s&&i&&(s>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(i,a)>0))return e.set(n.address,new o(n.address)),[f(e),t,s,i];i=n.electionId}null!=n.setVersion&&(null==s||n.setVersion>s)&&(s=n.setVersion);for(const t of e.keys()){const s=e.get(t);if(s.type===r.RSPrimary&&s.address!==n.address){e.set(t,new o(s.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[f(e),t,s,i]}function f(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return i.ReplicaSetWithPrimary;return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:p}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(35).Msg,o=n(22).KillCursor,s=n(22).GetMore,i=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],p=e=>e.ns.split(".")[1],h=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,f=(e,t)=>a.has(e)?{}:t,d={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},y=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],g=e=>{if(e instanceof s)return{getMore:e.cursorId,collection:p(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:p(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:p(e)},Object.keys(d).forEach(n=>{void 0!==e.query[n]&&(t[d[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),y.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof s?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,S=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:h(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=g(t),r=c(n),o=S(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),reply:f(s,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),failure:f(s,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(97),o=n(98),s=n(99),i=n(100),a=n(58).ScramSHA1,c=n(58).ScramSHA256,u=n(152);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(21),o=n(30).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,s=o.username,i=o.password,a=o.source;n.command(a+".$cmd",{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(s+":mongo:"+i,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+s+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:s,nonce:c,key:u};n.command(a+".$cmd",l,t)})}}},function(e,t,n){"use strict";const r=n(30).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.apply(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(30).AuthProvider,s=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,i=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new s(`\0${o}\0${i}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(30).AuthProvider,o=n(4).retrieveKerberos;let s;e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(null==s)try{s=o()}catch(e){return t(e,null)}const i=r.username,a=r.password,c=r.mechanismProperties,u=c.gssapiservicename||c.gssapiServiceName||"mongodb",l=new(0,s.processes.MongoAuthProcess)(n.host,n.port,u,c);l.init(i,a,e=>{if(e)return t(e,!1);l.transition("",(e,r)=>{if(e)return t(e,!1);const o={saslStart:1,mechanism:"GSSAPI",payload:r,autoAuthorize:1};n.command("$external.$cmd",o,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,n)=>{if(e)return t(e,!1);const r=n.result;l.transition(null,e=>{if(e)return t(e,null);t(null,r)})})})})})})})})}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";const r=n(156);e.exports={insert:function(e,t,n,o,s){r(e,"insert","documents",t,n,o,s)},update:function(e,t,n,o,s){r(e,"update","updates",t,n,o,s)},remove:function(e,t,n,o,s){r(e,"delete","deletes",t,n,o,s)},killCursors:n(157),getMore:n(158),query:n(159),command:n(42)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(10),o=n(166),s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(2).MongoNetworkTimeoutError,c=n(2).MongoWriteConcernError,u=n(74),l=n(174).StreamDescription,p=n(103),h=n(94),f=n(31).updateSessionFromResponse,d=n(4).uuidV4,m=n(0).now,y=n(0).calculateDurationInMs,g=Symbol("stream"),b=Symbol("queue"),S=Symbol("messageStream"),v=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),E=Symbol("autoEncrypter");function C(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:x.bind(e),isConnected:()=>!0}}};return e[E]&&(t.autoEncrypter=e[E]),t}function x(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[g].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new h.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[S].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return d().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[v]=t.generation,this[w]=m(),t.autoEncrypter&&(this[E]=t.autoEncrypter),this[b]=new Map,this[S]=new o(t),this[S].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[g].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new s(e))}if(e.documents[0]){const o=e.documents[0],i=t.session;if(i&&f(i,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new s(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[g]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new i(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[S]),this[S].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[v]||0}get idleTime(){return y(this[w])}get clusterTime(){return this[_]}get stream(){return this[g]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[g]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[g].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[g].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){p.command(C(this),e,t,n,r)}query(e,t,n,r,o){p.query(C(this),e,t,n,r,o)}getMore(e,t,n,r,o){p.getMore(C(this),e,t,n,r,o)}killCursors(e,t,n){p.killCursors(C(this),e,t,n)}insert(e,t,n,r){p.insert(C(this),e,t,n,r)}update(e,t,n,r){p.update(C(this),e,t,n,r)}remove(e,t,n,r){p.remove(C(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(60);e.exports=b;var o,s=n(169);b.ReadableState=g;n(10).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=n(107),c=n(16).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(44));l.inherits=n(45);var p=n(5),h=void 0;h=p&&p.debuglog?p.debuglog("stream"):function(){};var f,d=n(171),m=n(108);l.inherits(b,a);var y=["error","close","destroy","pause","resume"];function g(e,t){e=e||{};var r=t instanceof(o=o||n(37));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var s=e.highWaterMark,i=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=s||0===s?s:r&&(i||0===i)?i:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=n(110).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(37),!(this instanceof b))return new b(e);this._readableState=new g(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function S(e,t,n,r,o){var s,i=e._readableState;null===t?(i.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,i)):(o||(s=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(i,t)),s?e.emit("error",s):i.objectMode||t&&t.length>0?("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?i.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):v(e,i,t,!0):i.ended?e.emit("error",new Error("stream.push() after EOF")):(i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?v(e,i,t,!1):T(e,i)):v(e,i,t,!1))):r||(i.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(h("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){h("emit readable"),e.emit("readable"),A(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(E,e,t))}function E(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;es.length?s.length:e;if(i===s.length?o+=s:o+=s.slice(0,e),0===(e-=i)){i===s.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(i));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var s=r.data,i=e>s.length?s.length:e;if(s.copy(n,n.length-e,0,i),0===(e-=i)){i===s.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(i));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function I(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return h("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?I(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&I(this),null;var r,o=t.needReadable;return h("need readable",o),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&I(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,h("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){h("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),e.removeListener("close",y),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",d),p=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){h("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,A(e))}}(n);e.on("drain",l);var p=!1;var f=!1;function d(t){h("ondata"),f=!1,!1!==e.write(t)||f||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!p&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,f=!0),n.pause())}function m(t){h("onerror",t),b(),e.removeListener("error",m),0===i(e,"error")&&e.emit("error",t)}function y(){e.removeListener("finish",g),b()}function g(){h("onfinish"),e.removeListener("close",y),b()}function b(){h("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",y),e.once("finish",g),e.emit("pipe",n),o.flowing||(h("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s-1?setImmediate:r.nextTick;y.WritableState=m;var a=Object.create(n(44));a.inherits=n(45);var c={deprecate:n(172)},u=n(107),l=n(16).Buffer,p=global.Uint8Array||function(){};var h,f=n(108);function d(){}function m(e,t){s=s||n(37),e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var p=!1===e.decodeStrings;this.decodeStrings=!p,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,s=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,s){--t.pendingcb,n?(r.nextTick(s,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(s(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,s);else{var a=v(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||S(e,n),o?i(b,e,n,a,s):b(e,n,a,s)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function y(e){if(s=s||n(37),!(h.call(y,this)||this instanceof s))return new y(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function g(e,t,n,r,o,s,i){t.writelen=r,t.writecb=i,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function S(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),i=t.corkedRequestsFree;i.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,g(e,t,!0,t.length,s,"",i.finish),t.pendingcb++,t.lastBufferedRequest=null,i.next?(t.corkedRequestsFree=i.next,i.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,p=n.callback;if(g(e,t,!1,t.objectMode?1:u.length,u,l,p),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function v(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=v(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(y,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===y&&(e&&e._writableState instanceof m)}})):h=function(e){return e instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(e,t,n){var o,s=this._writableState,i=!1,a=!s.objectMode&&(o=e,l.isBuffer(o)||o instanceof p);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=s.defaultEncoding),"function"!=typeof n&&(n=d),s.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var s=!0,i=!1;return null===n?i=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(i=new TypeError("Invalid non-string/buffer chunk")),i&&(e.emit("error",i),r.nextTick(o,i),s=!1),s}(this,s,e,n))&&(s.pendingcb++,i=function(e,t,n,r,o,s){if(!n){var i=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==i&&(n=!0,o="buffer",r=i)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),y.prototype.destroy=f.destroy,y.prototype._undestroy=f.undestroy,y.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(16).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=p,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function i(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return o>0&&(e.lastNeed=o-1),o;if(--r=0)return o>0&&(e.lastNeed=o-2),o;if(--r=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=i;var r=n(37),o=Object.create(n(44));function s(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(1).MongoError,i=n(3).OperationBase;e.exports=class extends i{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let i=this.options;t.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===i.ordered||null==i.ordered?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let c=!1;try{for(let e=0;e{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends s{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=i(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,s.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(21),a=n(0).handleCallback,c=n(0).toError;class u extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=Array.isArray(r.roles)?r.roles:[];0===o.length&&console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:s};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}s(u,r.WRITE_OPERATION),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError,i=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new i("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new s("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback,a=n(29);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return i(e,t,null);i(e,t,!!n.ok)})}}s(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyWriteConcern,s=n(0).checkCollectionName,i=n(14).executeDbAdminCommand,a=n(0).handleCallback,c=n(85).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();s(n);const p={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(p,{db:t.s.db,collection:t},r),i(t.s.db.admin().s.db,p,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(118),s=n(119),i=n(120),a=n(210),c=n(211),u=n(43);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new s(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,s){const i=Array.prototype.slice.call(arguments,2);s="function"==typeof i[i.length-1]?i.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=i.length?i.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,s)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const s=new i(this.s.db,e,t);return u(this.s.db.s.topology,s,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(1).Topology,o=n(32).ServerCapabilities,s=n(25),i=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:s,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=i(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=i(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(1).Logger,s=n(1).MongoCredentials,i=n(1).MongoError,a=n(125),c=n(123),u=n(1).parseConnectionString,l=n(36),p=n(1).ReadPreference,h=n(126),f=n(66),d=n(1).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,y=n(40),g=n(11).retrieveBSON(),b=n(61).CMAP_EVENT_NAMES;let S;const v=r(n(217),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),w={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},_=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],O=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),T=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],E=["native_parser"],C=["server","replset","replSet","mongos","db"];const x=T.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function A(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function N(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new d(t.s.coreTopology))}function I(e,t){let r=(S||(S=n(62)),S);const o=[];return e instanceof r&&_.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}const k=r(()=>{},"current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.");function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function D(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const s={};"unified"===t&&(s.createServers=!1);const u=F(r,s);if(null!=r.autoEncryption){let t;try{let e=n(127);"function"!=typeof e.extension&&o(new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`")),t=e.extension(n(17)).AutoEncrypter}catch(e){return void o(e)}const s=Object.assign({bson:r.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp])},r.autoEncryption);r.autoEncrypter=new t(e,s)}let l;"mongos"===t?l=new a(u,r):"replicaset"===t?l=new h(u,r):"unified"===t&&(l=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),A(e,l),U(e,l),N(e,l),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):l.connect(r,e=>{if(e)return l.close(!0),void o(e);o(void 0,l)})}):l.connect(r,e=>{if(e)return l.close(!0),o(e);o(void 0,l)})}function B(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"];for(const o in t)-1!==r.indexOf(o.toLowerCase())?e[o]=t[o]:-1!==n.indexOf(o.toLowerCase())?e=j(e,t[o],!1):!t[o]||"object"!=typeof t[o]||Buffer.isBuffer(t[o])||Array.isArray(t[o])?e[o]=t[o]:e=j(e,t[o],!0);return e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!O.has(c))throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new s({mechanism:w[c],mechanismProperties:u,source:o,username:t,password:n})}function L(e){return j(B({},e),e,!1)}function j(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=j(e,t[r],n):e[r]=t[r];return e}function U(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(b).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function z(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=x[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;return(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS),e.srvHost&&(t.srvHost=e.srvHost),t}function F(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new p(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=36e4),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new f(t.domain_socket,27017,e):new f(t.host,t.port,e))}e.exports={validOptions:function(e){const t=T.concat(C);for(const n in e)if(-1===E.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new i(`option ${n} is not supported`);console.warn(`the options [${n}] is not supported`)}-1!==C.indexOf(n)&&console.warn(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${T}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let s=!1;const c=o("MongoClient",n);if(t instanceof f||t instanceof h||t instanceof a)return function(e,t,n,r){N(e,t),A(e,t),U(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new p(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,d=l?z:L;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new i(o));s&&e.emit("authenticated",null,!0),r(t,n)}(l?u:v)(t,n,(t,o)=>{if(t)return r(t);const i=d(o),a=B(i,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=36e4),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,null!=a.journal&&(a.j=a.journal,a.journal=void 0),function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,0===i.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{s=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?D(e,"unified",a,m):(k(),a.replicaSet||a.rs_name?D(e,"replicaset",a,m):i.servers.length>1?D(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=F(t)[0],o=I(e,r);r.connect(t,(s,i)=>{if(s)return r.close(!0),n(s);!function(e){_.forEach(t=>e.removeAllListeners(t))}(r),U(e,r),A(e,r);const a=i.lastIsMaster();if(N(e,i),a&&"isdbgrid"===a.msg)return i.close(),D(e,"mongos",t,n);!function(e,t){for(let n=0;n0?t.socketOptions:t;g=l(g,b),this.s={coreTopology:new s(m,g),sCapabilities:null,debug:g.debug,storeOptions:r,clonedOptions:g,store:d,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",s("joined")),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";const r=n(66),o=n(25),s=n(1).MongoError,i=n(32).TopologyBase,a=n(32).Store,c=n(1).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,p=n(0).filterOptions,h=n(0).mergeOptions;var f=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class d extends i{constructor(e,t){super();var n=this;t=p(t=t||{},f);for(var i=0;i0?t.socketOptions:t;g=l(g,b);var S=new c(y,g);S.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:S,sCapabilities:null,tag:t.tag,storeOptions:d,clonedOptions:g,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},g.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return S}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,s=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("ping",s("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var i=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,i)})),n.s.coreTopology.removeListener("connect",i),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";let r;function o(){return r||(r=i(n(17))),r}const s=n(67).MongoCryptError;function i(e){const t={mongodb:e};return t.stateMachine=n(218)(t),t.autoEncrypter=n(219)(t),t.clientEncryption=n(223)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:s}}e.exports={extension:i,MongoCryptError:s,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(40),s=n(39),i=n(220),a=s.join,c=s.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||s.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=s.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,i=require,c=[],u=0,p=e.try.length;u{let s;try{s=r.createHmac(e,t).update(n).digest()}catch(e){return e}return s.copy(o),s.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let s;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},aes256CbcDecryptHook:function(e,t,n,o){let s;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length}}},function(e,t,n){"use strict";var r=n(1).BSON.Binary,o=n(1).BSON.ObjectID,s=n(16).Buffer,i=function(e,t,n){if(!(this instanceof i))return new i(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=s.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=s.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!s.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};i.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},i.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},i.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=s.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},i.prototype.eof=function(){return this.internalPosition===this.length()},i.prototype.getc=function(){return this.read(1)},i.prototype.rewind=function(){this.internalPosition=0,this.data=new r},i.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var s={upsert:!0};for(var i in e)s[i]=e[i];for(i in n.writeConcern)s[i]=n.writeConcern[i];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var i in n.writeConcern)r[i]=n.writeConcern[i];o.replaceOne({_id:n.objectId},e,s,(function(e){t(e,n)}))})):t(null,n)}))},i.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},i.prototype.length=function(){return this.data.length()},Object.defineProperty(i.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),i.DEFAULT_CHUNK_SIZE=261120,e.exports=i},function(e,t){var n=Object.prototype.toString;function r(e){return"function"==typeof e.constructor?e.constructor.name:null}e.exports=function(e){if(void 0===e)return"undefined";if(null===e)return"null";var t=typeof e;if("boolean"===t)return"boolean";if("string"===t)return"string";if("number"===t)return"number";if("symbol"===t)return"symbol";if("function"===t)return"GeneratorFunction"===r(e)?"generatorfunction":"function";if(function(e){return Array.isArray?Array.isArray(e):e instanceof Array}(e))return"array";if(function(e){if(e.constructor&&"function"==typeof e.constructor.isBuffer)return e.constructor.isBuffer(e);return!1}(e))return"buffer";if(function(e){try{if("number"==typeof e.length&&"function"==typeof e.callee)return!0}catch(e){if(-1!==e.message.indexOf("callee"))return!0}return!1}(e))return"arguments";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";if(function(e){return e instanceof RegExp||"string"==typeof e.flags&&"boolean"==typeof e.ignoreCase&&"boolean"==typeof e.multiline&&"boolean"==typeof e.global}(e))return"regexp";switch(r(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(function(e){return"function"==typeof e.throw&&"function"==typeof e.return&&"function"==typeof e.next}(e))return"generator";switch(t=n.call(e)){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")}},function(e,t,n){"use strict"; /*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015 Jed Watson * MIT Licensed - */e.exports=function(e,t){if("string"==typeof e)return c(e);if("number"==typeof e)return a(e,t);return null},e.exports.format=a,e.exports.parse=c;var r=/\B(?=(\d{3})+(?!\d))/g,o=/(?:\.0*|(\.[^0]+)0+)$/,s={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},i=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function a(e,t){if(!Number.isFinite(e))return null;var n=Math.abs(e),i=t&&t.thousandsSeparator||"",a=t&&t.unitSeparator||"",c=t&&void 0!==t.decimalPlaces?t.decimalPlaces:2,u=Boolean(t&&t.fixedDecimals),l=t&&t.unit||"";l&&s[l.toLowerCase()]||(l=n>=s.pb?"PB":n>=s.tb?"TB":n>=s.gb?"GB":n>=s.mb?"MB":n>=s.kb?"KB":"B");var p=(e/s[l.toLowerCase()]).toFixed(c);return u||(p=p.replace(o,"$1")),i&&(p=p.replace(r,i)),p+a+l}function c(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var t,n=i.exec(e),r="b";return n?(t=parseFloat(n[1]),r=n[4].toLowerCase()):(t=parseInt(e,10),r="b"),Math.floor(s[r]*t)}},function(e,t,n){"use strict";const r=n(232);e.exports=e=>{const t=r(0,e.length-1);return()=>e[t()]}},,,function(e,t,n){"use strict";var r=n(67),o=n(31),s=n(46),i=n(47),a=n(48),c=n(49),u=n(50),l=n(68),p=n(51),h=n(52),f=n(53),d=n(54),m=n(55),y=n(36),g=n(134),b=n(135),S=n(137),v=n(26),w=v.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,s="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.lengthe.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,i=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!i)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,p=null!=n.promoteBuffers&&n.promoteBuffers,h=null==n.promoteLongs||n.promoteLongs,f=null==n.promoteValues||n.promoteValues,d=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var y=r?[]:{},g=0;;){var b=e[t++];if(0===b)break;for(var S=t;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var v=r?g++:e.toString("utf8",t,S);if(t=S+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),y[v]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===f)y[v]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)y[v]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===f)y[v]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)y[v]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;y[v]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");y[v]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var E=t,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(C<=0||C>e.length-t)throw new Error("bad embedded document length in bson");y[v]=u?e.slice(t,t+C):deserializeObject(e,E,n,!1),t+=C}else if(b===BSON.BSON_DATA_ARRAY){E=t;var x=n,A=t+(C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[v]){for(var N in x={},n)x[N]=n[N];x.raw=!0}if(y[v]=deserializeObject(e,E,x,!0),0!==e[(t+=C)-1])throw new Error("invalid array terminator byte");if(t!==A)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)y[v]=void 0;else if(b===BSON.BSON_DATA_NULL)y[v]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var I=new Long(O,T);y[v]=h&&!0===f&&I.lessThanOrEqual(JS_INT_MAX_LONG)&&I.greaterThanOrEqual(JS_INT_MIN_LONG)?I.toNumber():I}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);y[v]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,D=R,B=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(B===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>D-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(RD-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,S);for(S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var j=e.toString("utf8",t,S);t=S+1;var U=new Array(j.length);for(S=0;S=e.length)throw new Error("Bad BSON Document: illegal CString");for(L=e.toString("utf8",t,S),S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");j=e.toString("utf8",t,S),t=S+1,y[v]=new BSONRegExp(L,j)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,y[v]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)y[v]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)y[v]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var z=e.toString("utf8",t,t+w-1);if(o)if(s){var F=i?a(z):z;y[v]=isolateEvalWithHash(functionCache,F,z,y)}else y[v]=isolateEval(z);else y[v]=new Code(z);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(W<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");z=e.toString("utf8",t,t+w-1),E=t+=w,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,E,n,!1);if(t+=C,W<8+C+w)throw new Error("code_w_scope total size is to short, truncating scope");if(W>8+C+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(s?(F=i?a(z):z,y[v]=isolateEvalWithHash(functionCache,F,z,y)):y[v]=isolateEval(z),y[v].scope=q):y[v]=new Code(z,q)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+v+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var $=e.toString("utf8",t,t+w-1);t+=w;var H=utils.allocBuffer(12);e.copy(H,0,t,t+12),_=new ObjectID(H),t+=12;var V=$.split("."),Y=V.shift(),G=V.join(".");y[v]=new DBRef(G,_,Y)}}if(m!==t-d){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=y.$id&&(y=new DBRef(y.$ref,y.$id,y.$db)),y},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(136).writeIEEE754,o=n(31).Long,s=n(67),i=n(36).Binary,a=n(26).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},p=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},h=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var s=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+s+1)-1]=0;var i=e.write(n,r+4,"utf8");return e[r+3]=i+1>>24&255,e[r+2]=i+1>>16&255,e[r+1]=i+1>>8&255,e[r]=i+1&255,r=r+4+i,e[r++]=0,r},f=function(e,t,n,s,i){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[s++]=R.BSON_DATA_INT;var a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8");s+=a,e[s++]=0,e[s++]=255&n,e[s++]=n>>8&255,e[s++]=n>>16&255,e[s++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;else{e[s++]=R.BSON_DATA_LONG,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[s++]=255&u,e[s++]=u>>8&255,e[s++]=u>>16&255,e[s++]=u>>24&255,e[s++]=255&l,e[s++]=l>>8&255,e[s++]=l>>16&255,e[s++]=l>>24&255}else e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;return s},d=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},y=function(e,t,n,r,s){e[r++]=R.BSON_DATA_DATE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=o.fromNumber(n.getTime()),a=i.getLowBits(),c=i.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},g=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.length;return e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,s),r+=s},_=function(e,t,n,r,o,s,i,a,c,u){for(var l=0;l>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,r},E=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},C=function(e,t,n,o,s){return e[o++]=R.BSON_DATA_NUMBER,o+=s?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},x=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_CODE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},A=function(e,t,n,r,o,s,i,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,p="string"==typeof n.code?n.code:n.code.toString();r+=4;var h=e.write(p,r+4,"utf8")+1;e[r]=255&h,e[r+1]=h>>8&255,e[r+2]=h>>16&255,e[r+3]=h>>24&255,e[r+4+h-1]=0,r=r+h+4;var f=M(e,n.scope,o,r,s+1,i,a);r=f-1;var d=f-l;e[l++]=255&d,e[l++]=d>>8&255,e[l++]=d>>16&255,e[l++]=d>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,p=n.code.toString();var m=e.write(p,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},N=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.value(!0),a=n.position;return n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),s.copy(e,r,0,n.position),r+=n.position},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=e.write(n.value,r+4,"utf8")+1;return e[r]=255&s,e[r+1]=s>>8&255,e[r+2]=s>>16&255,e[r+3]=s>>24&255,r=r+4+s-1,e[r++]=0,r},k=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_OBJECT,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,s):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,s))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,i,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var D=0;D>8&255,e[r++]=F>>16&255,e[r++]=F>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var s,i,a="big"===n,c=8*o-r-1,u=(1<>1,p=-7,h=a?0:o-1,f=a?1:-1,d=e[t+h];for(h+=f,s=d&(1<<-p)-1,d>>=-p,p+=c;p>0;s=256*s+e[t+h],h+=f,p-=8);for(i=s&(1<<-p)-1,s>>=-p,p+=r;p>0;i=256*i+e[t+h],h+=f,p-=8);if(0===s)s=1-l;else{if(s===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),s-=l}return(d?-1:1)*i*Math.pow(2,s-r)},t.writeIEEE754=function(e,t,n,r,o,s){var i,a,c,u="big"===r,l=8*s-o-1,p=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=u?s-1:0,m=u?-1:1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=p):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=p?(a=0,i=p):i+h>=1?(a=(t*c-1)*Math.pow(2,o),i+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;e[n+d]=255&a,d+=m,a/=256,o-=8);for(i=i<0;e[n+d]=255&i,d+=m,i/=256,l-=8);e[n+d-m]|=128*y}},function(e,t,n){"use strict";var r=n(31).Long,o=n(46).Double,s=n(47).Timestamp,i=n(48).ObjectID,a=n(50).Symbol,c=n(49).BSONRegExp,u=n(51).Code,l=n(52),p=n(53).MinKey,h=n(54).MaxKey,f=n(55).DBRef,d=n(36).Binary,m=n(26).normalizedFunctionString,y=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return g||!S?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof p||t instanceof h||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof i||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof s||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+y(t.scope,n,S):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof d||"Binary"===t._bsontype)return t.sub_type===d.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof f||"DBRef"===t._bsontype){var v={$ref:t.namespace,$id:t.oid};return null!=t.db&&(v.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+y(v,n,S)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+y(t,n,S)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+y(t.scope,n,S);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=y},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";var r=n(37),o=n(140);e.exports=function(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected `fromDir` and `moduleId` to be a string");e=r.resolve(e);var n=r.join(e,"noop.js");try{return o._resolveFilename(t,{id:n,filename:n,paths:o._nodeModulePaths(e)})}catch(e){return null}}},function(e,t){e.exports=require("module")},function(e,t){var n;t=e.exports=V,n="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var r=Number.MAX_SAFE_INTEGER||9007199254740991,o=t.re=[],s=t.src=[],i=0,a=i++;s[a]="0|[1-9]\\d*";var c=i++;s[c]="[0-9]+";var u=i++;s[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var l=i++;s[l]="("+s[a]+")\\.("+s[a]+")\\.("+s[a]+")";var p=i++;s[p]="("+s[c]+")\\.("+s[c]+")\\.("+s[c]+")";var h=i++;s[h]="(?:"+s[a]+"|"+s[u]+")";var f=i++;s[f]="(?:"+s[c]+"|"+s[u]+")";var d=i++;s[d]="(?:-("+s[h]+"(?:\\."+s[h]+")*))";var m=i++;s[m]="(?:-?("+s[f]+"(?:\\."+s[f]+")*))";var y=i++;s[y]="[0-9A-Za-z-]+";var g=i++;s[g]="(?:\\+("+s[y]+"(?:\\."+s[y]+")*))";var b=i++,S="v?"+s[l]+s[d]+"?"+s[g]+"?";s[b]="^"+S+"$";var v="[v=\\s]*"+s[p]+s[m]+"?"+s[g]+"?",w=i++;s[w]="^"+v+"$";var _=i++;s[_]="((?:<|>)?=?)";var O=i++;s[O]=s[c]+"|x|X|\\*";var T=i++;s[T]=s[a]+"|x|X|\\*";var E=i++;s[E]="[v=\\s]*("+s[T]+")(?:\\.("+s[T]+")(?:\\.("+s[T]+")(?:"+s[d]+")?"+s[g]+"?)?)?";var C=i++;s[C]="[v=\\s]*("+s[O]+")(?:\\.("+s[O]+")(?:\\.("+s[O]+")(?:"+s[m]+")?"+s[g]+"?)?)?";var x=i++;s[x]="^"+s[_]+"\\s*"+s[E]+"$";var A=i++;s[A]="^"+s[_]+"\\s*"+s[C]+"$";var N=i++;s[N]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var I=i++;s[I]="(?:~>?)";var k=i++;s[k]="(\\s*)"+s[I]+"\\s+",o[k]=new RegExp(s[k],"g");var M=i++;s[M]="^"+s[I]+s[E]+"$";var R=i++;s[R]="^"+s[I]+s[C]+"$";var D=i++;s[D]="(?:\\^)";var B=i++;s[B]="(\\s*)"+s[D]+"\\s+",o[B]=new RegExp(s[B],"g");var P=i++;s[P]="^"+s[D]+s[E]+"$";var L=i++;s[L]="^"+s[D]+s[C]+"$";var j=i++;s[j]="^"+s[_]+"\\s*("+v+")$|^$";var U=i++;s[U]="^"+s[_]+"\\s*("+S+")$|^$";var z=i++;s[z]="(\\s*)"+s[_]+"\\s*("+v+"|"+s[E]+")",o[z]=new RegExp(s[z],"g");var F=i++;s[F]="^\\s*("+s[E]+")\\s+-\\s+("+s[E]+")\\s*$";var W=i++;s[W]="^\\s*("+s[C]+")\\s+-\\s+("+s[C]+")\\s*$";var q=i++;s[q]="(<|>)?=?\\s*\\*";for(var $=0;$<35;$++)n($,s[$]),o[$]||(o[$]=new RegExp(s[$]));function H(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?o[w]:o[b]).test(e))return null;try{return new V(e,t)}catch(e){return null}}function V(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof V))return new V(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var s=e.trim().match(t.loose?o[w]:o[b]);if(!s)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);-1===n&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,n,r){"string"==typeof n&&(r=n,n=void 0);try{return new V(e,n).inc(t,r).version}catch(e){return null}},t.diff=function(e,t){if(Z(e,t))return null;var n=H(e),r=H(t),o="";if(n.prerelease.length||r.prerelease.length){o="pre";var s="prerelease"}for(var i in n)if(("major"===i||"minor"===i||"patch"===i)&&n[i]!==r[i])return o+i;return s},t.compareIdentifiers=G;var Y=/^[0-9]+$/;function G(e,t){var n=Y.test(e),r=Y.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e0}function J(e,t,n){return K(e,t,n)<0}function Z(e,t,n){return 0===K(e,t,n)}function Q(e,t,n){return 0!==K(e,t,n)}function ee(e,t,n){return K(e,t,n)>=0}function te(e,t,n){return K(e,t,n)<=0}function ne(e,t,n,r){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return Z(e,n,r);case"!=":return Q(e,n,r);case">":return X(e,n,r);case">=":return ee(e,n,r);case"<":return J(e,n,r);case"<=":return te(e,n,r);default:throw new TypeError("Invalid operator: "+t)}}function re(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof re){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof re))return new re(e,t);n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===oe?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}t.rcompareIdentifiers=function(e,t){return G(t,e)},t.major=function(e,t){return new V(e,t).major},t.minor=function(e,t){return new V(e,t).minor},t.patch=function(e,t){return new V(e,t).patch},t.compare=K,t.compareLoose=function(e,t){return K(e,t,!0)},t.rcompare=function(e,t,n){return K(t,e,n)},t.sort=function(e,n){return e.sort((function(e,r){return t.compare(e,r,n)}))},t.rsort=function(e,n){return e.sort((function(e,r){return t.rcompare(e,r,n)}))},t.gt=X,t.lt=J,t.eq=Z,t.neq=Q,t.gte=ee,t.lte=te,t.cmp=ne,t.Comparator=re;var oe={};function se(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof se)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new se(e.raw,t);if(e instanceof re)return new se(e.value,t);if(!(this instanceof se))return new se(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ie(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,n,r,o,s,i,a,c,u,l,p,h){return((t=ie(n)?"":ie(r)?">="+n+".0.0":ie(o)?">="+n+"."+r+".0":">="+t)+" "+(a=ie(c)?"":ie(u)?"<"+(+c+1)+".0.0":ie(l)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+l+"-"+p:"<="+a)).trim()}function ce(e,t,r){for(var o=0;o0){var s=e[o].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}function ue(e,t,n){try{t=new se(t,n)}catch(e){return!1}return t.test(e)}function le(e,t,n,r){var o,s,i,a,c;switch(e=new V(e,r),t=new se(t,r),n){case">":o=X,s=te,i=J,a=">",c=">=";break;case"<":o=J,s=ee,i=X,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,r))return!1;for(var u=0;u=0.0.0")),p=p||e,h=h||e,o(e.semver,p.semver,r)?p=e:i(e.semver,h.semver,r)&&(h=e)})),p.operator===a||p.operator===c)return!1;if((!h.operator||h.operator===a)&&s(e,h.semver))return!1;if(h.operator===c&&i(e,h.semver))return!1}return!0}re.prototype.parse=function(e){var t=this.options.loose?o[j]:o[U],n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1],"="===this.operator&&(this.operator=""),n[2]?this.semver=new V(n[2],this.options.loose):this.semver=oe},re.prototype.toString=function(){return this.value},re.prototype.test=function(e){return n("Comparator.test",e,this.options.loose),this.semver===oe||("string"==typeof e&&(e=new V(e,this.options)),ne(e,this.operator,this.semver,this.options))},re.prototype.intersects=function(e,t){if(!(e instanceof re))throw new TypeError("a Comparator is required");var n;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return n=new se(e.value,t),ue(this.value,n,t);if(""===e.operator)return n=new se(this.value,t),ue(e.semver,n,t);var r=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),o=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),s=this.semver.version===e.semver.version,i=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=ne(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=ne(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return r||o||s&&i||a||c},t.Range=se,se.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},se.prototype.toString=function(){return this.range},se.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var r=t?o[W]:o[F];e=e.replace(r,ae),n("hyphen replace",e),e=e.replace(o[z],"$1$2$3"),n("comparator trim",e,o[z]),e=(e=(e=e.replace(o[k],"$1~")).replace(o[B],"$1^")).split(/\s+/).join(" ");var s=t?o[j]:o[U],i=e.split(" ").map((function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){n("caret",e,t);var r=t.loose?o[L]:o[P];return e.replace(r,(function(t,r,o,s,i){var a;return n("caret",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a="0"===r?">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":">="+r+"."+o+".0 <"+(+r+1)+".0.0":i?(n("replaceCaret pr",i),a="0"===r?"0"===o?">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+"-"+i+" <"+(+r+1)+".0.0"):(n("no pr"),a="0"===r?"0"===o?">="+r+"."+o+"."+s+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+" <"+(+r+1)+".0.0"),n("caret return",a),a}))}(e,t)})).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var r=t.loose?o[R]:o[M];return e.replace(r,(function(t,r,o,s,i){var a;return n("tilde",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a=">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":i?(n("replaceTilde pr",i),a=">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0"):a=">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0",n("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var r=t.loose?o[A]:o[x];return e.replace(r,(function(t,r,o,s,i,a){n("xRange",e,t,r,o,s,i,a);var c=ie(o),u=c||ie(s),l=u||ie(i);return"="===r&&l&&(r=""),c?t=">"===r||"<"===r?"<0.0.0":"*":r&&l?(u&&(s=0),i=0,">"===r?(r=">=",u?(o=+o+1,s=0,i=0):(s=+s+1,i=0)):"<="===r&&(r="<",u?o=+o+1:s=+s+1),t=r+o+"."+s+"."+i):u?t=">="+o+".0.0 <"+(+o+1)+".0.0":l&&(t=">="+o+"."+s+".0 <"+o+"."+(+s+1)+".0"),n("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(o[q],"")}(e,t),n("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter((function(e){return!!e.match(s)}))),i=i.map((function(e){return new re(e,this.options)}),this)},se.prototype.intersects=function(e,t){if(!(e instanceof se))throw new TypeError("a Range is required");return this.set.some((function(n){return n.every((function(n){return e.set.some((function(e){return e.every((function(e){return n.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new se(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},se.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new V(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!X(n,t)||(n=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(n&&e.test(n))return n;return null},t.validRange=function(e,t){try{return new se(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,n){return le(e,t,"<",n)},t.gtr=function(e,t,n){return le(e,t,">",n)},t.outside=le,t.prerelease=function(e,t){var n=H(e,t);return n&&n.prerelease.length?n.prerelease:null},t.intersects=function(e,t,n){return e=new se(e,n),t=new se(t,n),e.intersects(t)},t.coerce=function(e){if(e instanceof V)return e;if("string"!=typeof e)return null;var t=e.match(o[N]);if(null==t)return null;return H(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"_from":"mongodb@^3.6.0","_id":"mongodb@3.6.0","_inBundle":false,"_integrity":"sha512-/XWWub1mHZVoqEsUppE0GV7u9kanLvHxho6EvBxQbShXTKYF9trhZC2NzbulRGeG7xMJHD8IOWRcdKx5LPjAjQ==","_location":"/mongodb","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"mongodb@^3.6.0","name":"mongodb","escapedName":"mongodb","rawSpec":"^3.6.0","saveSpec":null,"fetchSpec":"^3.6.0"},"_requiredBy":["#DEV:/","/mongodb-memory-server-core"],"_resolved":"https://registry.npmjs.org/mongodb/-/mongodb-3.6.0.tgz","_shasum":"babd7172ec717e2ed3f85e079b3f1aa29dce4724","_spec":"mongodb@^3.6.0","_where":"/repos/.nhscc/airports.api.hscc.bdpa.org","bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"bundleDependencies":false,"dependencies":{"bl":"^2.2.0","bson":"^1.1.4","denque":"^1.4.1","require_optional":"^1.0.1","safe-buffer":"^5.1.2","saslprep":"^1.0.0"},"deprecated":false,"description":"The official MongoDB driver for Node.js","devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^4.5.0","eslint-plugin-prettier":"^2.2.0","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","standard-version":"^4.4.0","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"engines":{"node":">=4"},"files":["index.js","lib"],"homepage":"https://github.com/mongodb/node-mongodb-native","keywords":["mongodb","driver","official"],"license":"Apache-2.0","main":"index.js","name":"mongodb","optionalDependencies":{"saslprep":"^1.0.0"},"peerOptionalDependencies":{"kerberos":"^1.1.0","mongodb-client-encryption":"^1.0.0","mongodb-extjson":"^2.1.2","snappy":"^6.3.4","bson-ext":"^2.0.0"},"repository":{"type":"git","url":"git+ssh://git@github.com/mongodb/node-mongodb-native.git"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","bench":"node test/benchmarks/driverBench/","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional","format":"prettier --print-width 100 --tab-width 2 --single-quote --write \'test/**/*.js\' \'lib/**/*.js\'","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","lint":"eslint -v && eslint lib test","release":"standard-version -i HISTORY.md","test":"npm run lint && mocha --recursive test/functional test/unit test/core","test-nolint":"mocha --recursive test/functional test/unit test/core"},"version":"3.6.0"}')},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(9).EventEmitter,s=n(2).MongoError,i=n(2).MongoTimeoutError,a=n(2).MongoWriteConcernError,c=n(17),u=n(5).format,l=n(33).Msg,p=n(71),h=n(6).MESSAGE_HEADER_SIZE,f=n(6).COMPRESSION_DETAILS_SIZE,d=n(6).opcodes,m=n(25).compress,y=n(25).compressorIDs,g=n(25).uncompressibleCommands,b=n(91),S=n(15).Buffer,v=n(73),w=n(29).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,E="destroying",C="destroyed",x=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",E,C],[E]:[E,C],[C]:[C]}),A=new Set(["error","close","timeout","parseError","connect","message"]);var N=0,I=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:36e4,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=N++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;oe.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==C&&e.state!==E&&"draining"!==e.state&&e.options.reconnect&&x(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval));B(e){null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}}function D(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function B(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){x(e,E),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],x(e,C),"function"==typeof r&&r(null,null))})}function L(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(t))return n(null,r);const o=S.concat(r),s=o.slice(h),i=o.readInt32LE(12);m(e,s,(function(r,o){if(r)return n(r,null);const a=S.alloc(h);a.writeInt32LE(h+f+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(d.OP_COMPRESSED,12);const c=S.alloc(f);return c.writeInt32LE(i,0),c.writeInt32LE(s.length,4),c.writeUInt8(y[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function j(e,t){for(var n=0;n(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===C||e.state===E?("function"==typeof t&&t(new s("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void W(e)())))):"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}function F(e){for(var t=0;t0)e.executing=!1;else{for(;;){const i=B(e);if(0===e.availableConnections.length){F(e.queue),i0&&z(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){U(e,t),F(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n0&&z(e),setTimeout(()=>W(e)(),10);break}}if(i0){e.queue.unshift(n),z(e);break}var o=n.buffer;n.monitoring&&D(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var s=!0;if(Array.isArray(o))for(let e=0;e{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(x(this,"connected"),this.minSize)for(let e=0;e0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new s("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==C&&n.state!==E)if(F(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o0)return setTimeout(e,1);P(n,r,{force:!1},t)}else W(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},I.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new s("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),z(this,()=>{"function"==typeof e&&e(null,null)}))})},I.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new s("write method must provide a callback");if(this.state!==C&&this.state!==E)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,i.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,i.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,i.started)),"function"==typeof n&&n(t,o)}),L(r,e,(e,n)=>{if(e)throw e;i.buffer=n,t.monitoring?r.queue.unshift(i):r.queue.push(i),r.executing||process.nextTick((function(){W(r)()}))})}else n(new s("pool is draining, new operations prohibited"));else n(new s("pool destroyed"))},I._execute=W,e.exports=I},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:c}=n(148);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=h(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),s=h(o);if(s.some(e=>i.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(s.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const f=s.some(e=>a.get(e)),d=s.some(e=>c.get(e));if(f&&d)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(p((g=o,g[0]))),y=a.get(p((e=>e[e.length-1])(o)));var g;if(f&&(!m||!y))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=s,l=o,p=e=>e.codePointAt(0);function h(e){const t=[],n=e.length;for(let r=0;r=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(38),o=n(37),s=n(149),i=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);return a+=e,s({buffer:t})}const u=c(),l=c(),p=c(),h=c(),f=c(),d=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:p,prohibited_characters:h,bidirectional_r_al:f,bidirectional_l:d}}).call(this,"/")},function(e,t,n){var r=n(150);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages0;s--){var i=this.path[s],a=o[i];if(!a){if(t)return;a=o[i]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,s,i=this._array(e,t),a=this.path[0],c=i&&i[a];return c||t||(c=i[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,s=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(s),s),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),s=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[s]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=n[s],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);i?i.buffer=a:n[s]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new s(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new s("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void d("http://169.254.170.2"+process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,(e,r)=>{if(e)return t(e);n(r)});d(p+"/latest/api/token",{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);d(`${p}/${h}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);d(`${p}/${h}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,y=r.mechanismProperties.AWS_SESSION_TOKEN,g=this.bson;i.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:g.serialize({r:r,p:110})};n.command(m+".$cmd",o,(e,o)=>{if(e)return t(e);const i=o.result,c=g.deserialize(i.payload.buffer),p=c.h,h=c.s.buffer;if(64!==h.length)return void t(new s(`Invalid server nonce length ${h.length}, expected 64`));if(0!==h.compare(r,0,r.length,0,r.length))return void t(new s("Server nonce does not begin with client nonce"));if(p.length<1||p.length>255||-1!==p.indexOf(".."))return void t(new s(`Server returned an invalid host: "${p}"`));const d="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:p,region:f(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":d.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:d},{accessKeyId:a,secretAccessKey:u,token:y}),S={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};y&&(S.t=y);const v={saslContinue:1,conversationId:1,payload:g.serialize(S)};n.command(m+".$cmd",v,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(57),s=n(99),i=n(19),a=n(154)(1e3);function c(e,t,n){return i.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return i.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function p(e){return l(encodeURIComponent(e))}function h(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}h.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var n=0;n<2;n++)if(/^s3-/.test(t[n])){t[1]=t[n].slice(3),t[0]="s3";break}return t},h.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},h.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},h.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},h.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},h.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},h.prototype.getDate=function(){return this.getDateTime().substr(0,8)},h.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},h.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),s=a.get(o);return s||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),s=c(n,"aws4_request"),a.set(o,s)),c(s,this.stringToSign(),"hex")},h.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},h.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",s="s3"!==this.service,i="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[p(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),h=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(p).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+p(l[e]))})),o=h.join("&")}return"/"!==t&&(s&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return s&&".."===t?e.pop():s&&"."===t||(i&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(p(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},h.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()=0&&(n=s.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},h.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(s.stringify(t))):e},r.RequestSigner=h,r.sign=function(e,t){return new h(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(6).collectionNamespace,s=n(40);e.exports=function(e,t,n,i,a,c,u){if(0===a.length)throw new r(t+" must contain at least one document");"function"==typeof c&&(u=c,c={});const l="boolean"!=typeof(c=c||{}).ordered||c.ordered,p=c.writeConcern,h={};if(h[t]=o(i),h[n]=a,h.ordered=l,p&&Object.keys(p).length>0&&(h.writeConcern=p),c.collation)for(let e=0;e{};const l=n.cursorId;if(a(e)<4){const o=e.s.bson,s=e.s.pool,i=new r(o,t,[l]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),s&&s.isConnected())try{s.write(i,a,u)}catch(e){"function"==typeof u?u(e,null):console.warn(e)}return}const p={killCursors:i(t),cursors:[l]},h={};"object"==typeof n.session&&(h.session=n.session),c(e,t,p,h,(e,t)=>{if(e)return u(e);const n=t.message;return n.cursorNotFound?u(new s("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void u(null,n.documents[0]):u(new o("invalid killCursors result returned for cursor id "+l))})}},function(e,t,n){"use strict";const r=n(20).GetMore,o=n(10).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=o().Long,c=n(6).collectionNamespace,u=n(4).maxWireVersion,l=n(6).applyCommonQueryOptions,p=n(40);e.exports=function(e,t,n,o,h,f){h=h||{};const d=u(e);function m(e,t){if(e)return f(e);const r=t.message;if(r.cursorNotFound)return f(new i("cursor killed or timed out"),null);if(d<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void f(null,null,r.connection)}if(0===r.documents[0].ok)return f(new s(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,f(null,r.documents[0],r.connection)}if(d<4){const s=e.s.bson,i=new r(s,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(i,a,m)}const y={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(y.maxTimeMS=n.cmd.maxAwaitTimeMS);const g=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},h);n.session&&(g.session=n.session),p(e,t,y,g,m)}},function(e,t,n){"use strict";const r=n(20).Query,o=n(2).MongoError,s=n(6).getReadPreference,i=n(6).collectionNamespace,a=n(6).isSharded,c=n(4).maxWireVersion,u=n(6).applyCommonQueryOptions,l=n(40);e.exports=function(e,t,n,p,h,f){if(h=h||{},null!=p.cursorId)return f();if(null==n)return f(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const i=function(e,t,n,i,c){c=c||{};const u=e.s.bson,l=s(n,c);i.batchSize=n.batchSize||i.batchSize;let p=0;p=i.limit<0||0!==i.limit&&i.limit0&&0===i.batchSize?i.limit:i.batchSize;const h=i.skip||0,f={};a(e)&&l&&(f.$readPreference=l.toJSON());n.sort&&(f.$orderby=n.sort);n.hint&&(f.$hint=n.hint);n.snapshot&&(f.$snapshot=n.snapshot);void 0!==n.returnKey&&(f.$returnKey=n.returnKey);n.maxScan&&(f.$maxScan=n.maxScan);n.min&&(f.$min=n.min);n.max&&(f.$max=n.max);void 0!==n.showDiskLoc&&(f.$showDiskLoc=n.showDiskLoc);n.comment&&(f.$comment=n.comment);n.maxTimeMS&&(f.$maxTimeMS=n.maxTimeMS);n.explain&&(p=-Math.abs(n.limit||0),f.$explain=!0);if(f.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o("server find command does not support a readConcern level of "+n.readConcern.level);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const d="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,y=new r(u,t,f,{numberToSkip:h,numberToReturn:p,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:d,ignoreUndefined:m});"boolean"==typeof n.tailable&&(y.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(y.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(y.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(y.awaitData=n.awaitData);"boolean"==typeof n.partial&&(y.partial=n.partial);return y.slaveOk=l.slaveOk(),y}(e,t,n,p,h),c=u({},p);return"string"==typeof i.documentsReturnedIn&&(c.documentsReturnedIn=i.documentsReturnedIn),void e.s.pool.write(i,c,f)}const d=s(n,h),m=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;let o={find:i(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let s=n.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[s[0]]=t}else for(let t=0;te.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),s()}var r=new p(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",i(e,"connect")),r.once("close",i(e,"close")),r.once("timeout",i(e,"timeout")),r.once("error",i(e,"error")),r.once("parseError",i(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),g(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c0&&e.emit(t,n)}A.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},E(this,"connecting");var n=this.s.seedlist.map((function(n){return new p(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",B(e,"close")),t.once("timeout",B(e,"timeout")),t.once("parseError",B(e,"parseError")),t.once("error",B(e,"error")),t.once("connect",B(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),g(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),E(this,T),"function"==typeof t&&t(null,null))};this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o{if(!o)return n(null,s);if(!w(o,r))return o=S(o),n(o);if(c){return L(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[s](i,a,t,u)}A.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof i?e:t.readPreference||i.primary;const s=_(),a=()=>{if(O(s)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof p))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},A.prototype.getServers=function(){return this.s.replicaSetState.allServers()},A.prototype.insert=function(e,t,n,r){L({self:this,op:"insert",ns:e,ops:t},n,r)},A.prototype.update=function(e,t,n,r){L({self:this,op:"update",ns:e,ops:t},n,r)},A.prototype.remove=function(e,t,n,r){L({self:this,op:"remove",ns:e,ops:t},n,r)};const j=["findAndModify","insert","update","delete"];A.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var s=this,a=n.readPreference?n.readPreference:i.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof p))return r(c);if(s.s.debug&&s.emit("pickedServer",i.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&y(s)&&!n.session.inTransaction()&&(h=t,j.some(e=>h[e]));var h;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!w(o,s))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=A},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,s=n(8).diff,i=n(9).EventEmitter,a=n(17),c=n(12),u=n(2).MongoError,l=n(15).Buffer,p="ReplicaSetNoPrimary",h="ReplicaSetWithPrimary",f="Unknown",d="PossiblePrimary",m="RSPrimary",y="RSSecondary",g="RSArbiter",b="RSOther",S="RSGhost",v="Unknown",w=function(e){e=e||{},i.call(this),this.topologyType=p,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,i),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,I(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var s=0;sc)return!1}else if(!l&&i&&c&&c=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&null==e.maxStalenessSeconds){var o=E(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=E(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var s=n[e.index];return e.index=e.index+1,s}function C(e,t,n){for(var r=0;r0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var i=s(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:i};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,s=n(9).EventEmitter,i=n(18).CoreCursor,a=n(17),c=n(10).retrieveBSON,u=n(2).MongoError,l=n(72),p=n(8).diff,h=n(8).cloneOptions,f=n(8).SessionMixins,d=n(8).isRetryableWritesSupported,m=n(4).relayEvents,y=c(),g=n(8).getMMAPError,b=n(4).makeClientMetadata,S=n(8).legacyIsRetryableWriteError;var v="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",v,w,"disconnected"],connecting:["connecting",v,w,"connected","disconnected"],connected:["connected","disconnected",v,w,"unreferenced"],unreferenced:["unreferenced",v,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],E=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>(e.find(e=>e.host===t.host&&e.port===t.port)||e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout0&&e.emit(t,n)}r(E,s),Object.assign(E.prototype,f),Object.defineProperty(E.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(E.prototype,"parserType",{enumerable:!0,get:function(){return y.native?"c++":"js"}}),Object.defineProperty(E.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const x=["serverDescriptionChanged","error","close","timeout","parseError"];function A(e,t,n){t=t||{},x.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function N(e){return function(){e.state!==w&&e.state!==v&&(M(e.connectedProxies,e.disconnectedProxies,this),L(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function I(e,t){return function(){if(e.state===w)return L(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===v||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==v&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),D(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==v&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var s=0;s{if(!o)return n(null,s);if(!S(o,r)||!c)return o=g(o),n(o);if(a=k(r,t.session),!a)return n(o);return B(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](s,i,t,l)}E.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));C(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),L(e),t.once("close",I(e,"close")),t.once("timeout",I(e,"timeout")),t.once("parseError",I(e,"parseError")),t.once("error",I(e,"error")),t.once("connect",I(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},E.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},E.prototype.lastIsMaster=function(){return this.ismaster},E.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},E.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,v),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(L(this),C(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),A(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},E.prototype.isConnected=function(){return this.connectedProxies.length>0},E.prototype.isDestroyed=function(){return this.state===w},E.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},E.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},E.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function L(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=p(e.topologyDescription,n),s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",s),e.topologyDescription=n}}E.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var s=this,i=k(s,n.session);if((null==i||!i.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==i)return r(new u("no mongos proxy available"));var a=h(n);a.topology=s;const c=!n.retrying&&n.retryWrites&&n.session&&d(s)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),i.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!S(n,s))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},E.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},E.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},E.prototype.connections=function(){for(var e=[],t=0;t({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},k.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:A(t),compression:{compressors:g(t)}})),H.forEach(e=>{t[e]&&C(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,i=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:t.host+":27017";return e.set(n,new s(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:F,description:new a(n,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),servers:new Map,sessionPool:new x(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Z(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return y.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===q)return void("function"==typeof t&&t());var n,r;$(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=J(n,t);return e.set(t.address,r),e},new Map),h.translate(e);const o=e.readPreference||h.primary,s=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));$(this,q),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},s):this.selectServer(B(o),e,s)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==F&&this.s.state!==z?($(this,z),te(this[Y],new S("Topology closed")),M(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{E(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),$(this,F),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof h?n=e:"string"==typeof e?n=new h(e):(h.translate(t),n=t.readPreference||h.primary),e=B(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,s=o&&o.transaction;if(r&&s&&s.server)return void n(void 0,s.server);let i=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:h.primary;i=B(t)}const a={serverSelector:i,transaction:s,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[V]=!0,a.timer=void 0;const e=new v(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),ne(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return I(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new S(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Z(this,e),this[Y].length>0&&ne(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){Q({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){Q({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){Q({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),h.translate(n);const o=n.readPreference||h.primary;this.selectServer(B(o),n,(o,s)=>{if(o)return void r(o);const i=!n.retrying&&!!n.retryWrites&&n.session&&f(this)&&!n.session.inTransaction()&&(a=t,K.some(e=>a[e]));var a;i&&(n.session.incrementTransactionNumber(),n.willRetryWrite=i),s.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!ee(o))return r(o);if(i){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return h.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===q}isDestroyed(){return this.s.state===F}unref(){console.log("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(0===e.length)return{};return e.filter(e=>e.type!==i.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),j.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function J(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(p(r,e,j),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{R(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Z(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=J(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function Q(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,s=e.ns,i=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&f(r)&&!t.session.inTransaction();r.selectServer(P(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!ee(r))return r=O(r),n(r);if(a){return Q(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](s,i,t,u)})}function ee(e){return e instanceof S&&e.hasErrorLabel("RetryableWriteError")}function te(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[V]||n.callback(t)}}function ne(e){if(e.s.state===F)return void te(e[Y],new S("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(9),o=n(164).ConnectionPool,s=n(59).CMAP_EVENT_NAMES,i=n(2).MongoError,a=n(4).relayEvents,c=n(10).retrieveBSON(),u=n(17),l=n(32).ServerDescription,p=n(32).compareTopologyVersion,h=n(12),f=n(175).Monitor,d=n(2).MongoNetworkError,m=n(2).MongoNetworkTimeoutError,y=n(4).collationNotSupported,g=n(10).debugOptions,b=n(2).isSDAMUnrecoverableError,S=n(2).isRetryableWriteError,v=n(2).isNodeShuttingDownError,w=n(2).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(14),E=T.ServerType,C=n(39).isTransactionCommand,x=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],A=T.STATE_CLOSING,N=T.STATE_CLOSED,I=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[N]:[N,I],[I]:[I,A,k,N],[k]:[k,A,N],[A]:[A,N]}),R=Symbol("monitor");class D extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:N,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new f(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>L(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:B(this.description.roundTripTime,e.duration)})),this.s.state===I&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===N&&(M(this,I),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==N?(M(this,A),this[R].close(),this.s.pool.close(e,e=>{M(this,N),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===A||this.s.state===N)return void r(new i("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof h))return new i("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:g(x,n)})}] against ${this.name}`),y(this,t)?r(new i(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,s)=>{if(r)return L(this,r),s(r);o.command(e,t,n,U(this,o,t,n,s))},r)}query(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.query(e,t,n,r,U(this,s,t,r,i))},o):o(new i("server is closed"))}getMore(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.getMore(e,t,n,r,U(this,s,null,r,i))},o):o(new i("server is closed"))}killCursors(e,t,n){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((n,r,o)=>{if(n)return L(this,n),o(n);r.killCursors(e,t,U(this,r,null,void 0,o))},n):"function"==typeof n&&n(new i("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function B(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,s=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];if(r.s.state===A||r.s.state===N)return void n(new i("server is closed"));if(y(r,t))return void n(new i(`server ${r.name} does not support collation`));!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,i)=>{if(e)return L(r,e),i(e);n[o](s,a,t,U(r,n,a,t,i))},n):n(new i("servers < 3.4 do not support hint on "+o))}function L(e,t){t instanceof d&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function j(e,t){return e&&e.inTransaction()&&!C(t)}function U(e,t,n,r,o){const s=r&&r.session;return function(r,i){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof d?(s&&!s.hasEnded&&(s.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==E.Standalone}(e)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(L(e,r),e.s.pool.clear())):(_(e)<9&&S(r)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return p(r,n)<0}(e,r)&&((_(e)<=7||v(r))&&e.s.pool.clear(),L(e,r),process.nextTick(()=>e.requestCheck())))),o(r,i)}}Object.defineProperty(D.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:D}},function(e,t,n){"use strict";const r=n(74),o=n(9).EventEmitter,s=n(17),i=n(0).makeCounter,a=n(2).MongoError,c=n(102).Connection,u=n(4).eachAsync,l=n(73),p=n(4).relayEvents,h=n(174),f=h.PoolClosedError,d=h.WaitQueueTimeoutError,m=n(59),y=m.ConnectionPoolCreatedEvent,g=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,S=m.ConnectionReadyEvent,v=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,E=m.ConnectionPoolClearedEvent,C=Symbol("logger"),x=Symbol("connections"),A=Symbol("permits"),N=Symbol("minPoolSizeTimer"),I=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),D=Symbol("cancelled"),B=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[I]}function L(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function j(e,t){const n=Object.assign({id:e[k].next().value,generation:e[I]},e.options);e[A]--,l(n,e[M],(n,r)=>{if(n)return e[A]++,e[C].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(p(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new S(e,r)),"function"!=typeof t?(e[x].push(r),z(e)):t(void 0,r))})}function U(e,t,n){e.emit("connectionClosed",new v(e,t,n)),e[A]++,process.nextTick(()=>t.destroy())}function z(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[D]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[x].shift(),r=P(e,n),o=L(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const s=n.closed?"error":r?"stale":"idle";U(e,n,s)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount{const r=e[R].shift();null!=r?r[D]||(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n)):null==t&&e[x].push(n)})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(B).reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[C]=s("ConnectionPool",e),this[x]=new r,this[A]=this.options.maxPoolSize,this[N]=void 0,this[I]=0,this[k]=i(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new y(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;ee(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[I]}get totalConnectionCount(){return this[x].length+(this.options.maxPoolSize-this[A])}get availableConnectionCount(){return this[x].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new f(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[D]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new d(n))},r)),this[R].push(t),z(this)}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[x].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){U(this,e,e.closed?"error":t?"poolClosed":"stale")}z(this)}clear(){this[I]+=1,this.emit("connectionPoolCleared",new E(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[D]||e.callback(new a("connection pool closed"))}this[N]&&clearTimeout(this[N]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[x].toArray(),(t,n)=>{this.emit("connectionClosed",new v(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[x].clear(),this.emit("connectionPoolClosed",new g(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(22).Duplex,o=n(166),s=n(2).MongoParseError,i=n(25).decompress,a=n(20).Response,c=n(33).BinMsg,u=n(2).MongoError,l=n(6).opcodes.OP_COMPRESSED,p=n(6).opcodes.OP_MSG,h=n(6).MESSAGE_HEADER_SIZE,f=n(6).COMPRESSION_DETAILS_SIZE,d=n(6).opcodes,m=n(25).compress,y=n(25).compressorIDs,g=n(25).uncompressibleCommands,b=n(33).Msg,S=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[S]=new o}_write(e,t,n){this[S].append(e),function e(t,n){const r=t[S];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new s("Invalid message size: "+o));if(o>t.maxBsonMessageSize)return void n(new s(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const f=r.slice(0,o);r.consume(o);const d={length:f.readInt32LE(0),requestId:f.readInt32LE(4),responseTo:f.readInt32LE(8),opCode:f.readInt32LE(12)};let m=d.opCode===p?c:a;const y=t.responseOptions;if(d.opCode!==l){const o=f.slice(h);return t.emit("message",new m(t.bson,f,d,o,y)),void(r.length>=4?e(t,n):n())}d.fromCompressed=!0,d.opCode=f.readInt32LE(h),d.length=f.readInt32LE(h+4);const g=f[h+8],b=f.slice(h+9);m=d.opCode===p?c:a,i(g,b,(o,s)=>{o?n(o):s.length===d.length?(t.emit("message",new m(t.bson,f,d,s,y)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(h),o=n.readInt32LE(12);m({options:t},r,(n,s)=>{if(n)return void t.cb(n,null);const i=Buffer.alloc(h);i.writeInt32LE(h+f+s.length,0),i.writeInt32LE(e.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(d.OP_COMPRESSED,12);const a=Buffer.alloc(f);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(y[t.agreedCompressor],8),this.push(Buffer.concat([i,a,s]))})}}},function(e,t,n){"use strict";var r=n(167).Duplex,o=n(5),s=n(15).Buffer;function i(e){if(!(this instanceof i))return new i(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(i,r),i.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;rthis.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||s.alloc(0);if(r<=0)return e||s.alloc(0);var o,i,a=!!e,c=this._offset(n),u=r-n,l=u,p=a&&t||0,h=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:s.concat(this._bufs,this.length);for(i=0;i(o=this._bufs[i].length-h))){this._bufs[i].copy(e,p,h,h+l),p+=o;break}this._bufs[i].copy(e,p,h),p+=o,l-=o,h&&(h=0)}return e.length>p?e.slice(0,p):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new i;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new i(o)},i.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){for(var e=0,t=new i;ethis.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},i.prototype._match=function(e,t){if(this.length-e0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,s=r.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,n=s,o=a,t.copy(n,o),a+=i.data.length,i=i.next;return s},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=s;var r=n(108),o=Object.create(n(42));function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}o.inherits=n(43),o.inherits(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(32).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(2).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(14).ServerType,o=n(9),s=n(73),i=n(102).Connection,a=n(14),c=n(4).makeStateMachine,u=n(2).MongoNetworkError,l=n(10).retrieveBSON(),p=n(0).makeInterruptableAsyncInterval,h=n(0).calculateDurationInMs,f=n(0).now,d=n(101),m=d.ServerHeartbeatStartedEvent,y=d.ServerHeartbeatSucceededEvent,g=d.ServerHeartbeatFailedEvent,b=Symbol("server"),S=Symbol("monitorId"),v=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,E=a.STATE_CLOSING,C=c({[E]:[E,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",E],monitoring:["monitoring","idle",E]}),x=new Set([E,T,"monitoring"]);function A(e){return e.s.state===T||e.s.state===E}function N(e){C(e,E),e[S]&&(e[S].stop(),e[S]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[S]&&(clearTimeout(e[S]),e[S]=void 0),e[v]&&e[v].destroy({force:!0})}function I(e){return t=>{function n(){A(e)||C(e,"idle"),t()}C(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),function(e,t){let n=f();function r(r){e[v]&&(e[v].destroy({force:!0}),e[v]=void 0),e.emit("serverHeartbeatFailed",new g(h(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[v]&&!e[v].closed){const s=e.options.connectTimeoutMS,i=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u=c?{ismaster:!0,maxAwaitTimeMS:i,topologyVersion:(o=a,{processId:o.processId,counter:l.Long.fromNumber(o.counter)})}:{ismaster:!0},p=c?{socketTimeout:s+i,exhaustAllowed:!0}:{socketTimeout:s};return c&&null==e[_]&&(e[_]=new k(e[w],e.connectOptions)),void e[v].command("admin.$cmd",u,p,(o,s)=>{if(o)return void r(o);const i=s.result,a=c?e[_].roundTripTime:h(n);e.emit("serverHeartbeatSucceeded",new y(a,i,e.address)),c&&i.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=f()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,i))})}var o;s(e.connectOptions,e[w],(o,s)=>{if(s&&A(e))s.destroy({force:!0});else{if(o)return e[v]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[v]=s,e.emit("serverHeartbeatSucceeded",new y(h(n),s.ismaster,e.address)),t(void 0,s.ismaster)}})}(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{A(e)||e[S].wake()}),n()})}}class k{constructor(e,t){this[v]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[S]=setTimeout(()=>function e(t,n){const r=f(),o=t[w],i=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[v]&&(t[v]=o),t[O]=h(r),t[S]=setTimeout(()=>e(t,n),i))}if(null==t[v])return void s(n,o,(e,n)=>{if(e)return t[v]=void 0,void(t[O]=0);a(n)});t[v].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[v]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[S]),this[S]=void 0,this[v]&&this[v].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[v]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[S]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){x.has(this.s.state)||this[S].wake()}reset(){if(A(this))return;C(this,E),N(this),C(this,"idle");const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t})}close(){A(this)||(C(this,E),N(this),this.emit("close"),C(this,T))}}}},function(e,t,n){"use strict";const r=n(17),o=n(9).EventEmitter,s=n(75);class i{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=i,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return"_mongodb._tcp."+this.srvHost}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new i(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;s.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(14).ServerType,o=n(14).TopologyType,s=n(12),i=n(2).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function p(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function h(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(h));const f=e.mode;if(f===s.PRIMARY)return n.filter(u);if(f===s.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const d=f===s.NEAREST?p:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,s=(t.heartbeatFrequencyMS+1e4)/1e3;if(r((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(d))));return f===s.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(57),o=n(99),s=n(75),i=n(2).MongoParseError,a=n(12),c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;function u(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}function l(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=l(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>l(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const p=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),f=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),d={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function m(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),p.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!f.has(n))throw new i(`Value for authMechanism must be one of: ${Array.from(f).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new i("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&d[t]?e[d[t]]=n:e[t]=n}const y=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function g(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=b("tls",e,t),r=b("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new i("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new i("Incomplete key value pair for option");const s=e.toLowerCase();m(n,s,l(s,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,console.warn("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function b(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new i(`All values of ${e} must be the same.`)})}return o}const S="mongodb+srv",v=["mongodb",S];function w(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new i("URI malformed, cannot be parsed"))}const a=e.match(c);if(!a)return n(new i("Invalid connection string"));const l=a[1];if(-1===v.indexOf(l))return n(new i("Invalid protocol provided"));const p=a[4].split("?"),h=p.length>0?p[0]:null,f=p.length>1?p[1]:null;let d;try{d=g(f,t)}catch(e){return n(e)}if(d=Object.assign({},d,t),l===S)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new i("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new i("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new i("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new i(`Ports not accepted with '${S}' URIs`));const c=a.host;s.resolveSrv("_mongodb._tcp."+c,(e,l)=>{if(e)return n(e);if(0===l.length)return n(new i("No addresses found at host"));for(let e=0;e`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),s.resolveTxt(c,(e,s)=>{if(e){if("ENODATA"!==e.code)return n(e);s=null}if(s){if(s.length>1)return n(new i("Multiple text records not allowed"));if(s=o.parse(s[0].join("")),Object.keys(s).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new i("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);w(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,d,n);const m={username:null,password:null,db:h&&""!==h?o.unescape(h):null};if(d.auth?(d.auth.username&&(m.username=d.auth.username),d.auth.user&&(m.username=d.auth.user),d.auth.password&&(m.password=d.auth.password)):(d.username&&(m.username=d.username),d.user&&(m.username=d.user),d.password&&(m.password=d.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new i("Unescaped slash in userinfo section"));const b=a[3].split("@");if(b.length>2)return n(new i("Unescaped at-sign in authority section"));if(null==b[0]||""===b[0])return n(new i("No username provided in authority section"));if(b.length>1){const e=b.shift().split(":");if(e.length>2)return n(new i("Unescaped colon in authority section"));if(""===e[0])return n(new i("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let _=null;const O=b.shift().split(",").map(e=>{let t=r.parse("mongodb://"+e);if("/:"===t.path)return _=new i("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(_=new i("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)_=new i("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;_=new i("Invalid port (negative number)")}else _=new i("Invalid port (zero) with hostname")}).filter(e=>!!e);if(_)return n(_);if(0===O.length||""===O[0].host||null===O[0].host)return n(new i("No hostname or hostnames provided in connection string"));if(!!d.directConnection&&1!==O.length)return n(new i("directConnection option requires exactly one host"));null==d.directConnection&&1===O.length&&null==d.replicaSet&&(d.directConnection=!0);const T={hosts:O,auth:m.db||m.username?m:null,options:Object.keys(d).length?d:null};var E;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((E=T.options).tls&&(E.ssl=E.tls),E.tlsInsecure?(E.checkServerIdentity=!1,E.sslValidate=!1):Object.assign(E,{checkServerIdentity:!E.tlsAllowInvalidHostnames,sslValidate:!E.tlsAllowInvalidCertificates}),E.tlsCAFile&&(E.ssl=!0,E.sslCA=E.tlsCAFile),E.tlsCertificateKeyFile&&(E.ssl=!0,E.tlsCertificateFile?(E.sslCert=E.tlsCertificateFile,E.sslKey=E.tlsCertificateKeyFile):(E.sslKey=E.tlsCertificateKeyFile,E.sslCert=E.tlsCertificateKeyFile)),E.tlsCertificateKeyFilePassword&&(E.ssl=!0,E.sslPass=E.tlsCertificateKeyFilePassword),E);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(y.has(r)&&(!e.auth||null==e.auth.username))throw new i(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new i(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=w},function(e,t,n){"use strict";const r=n(9).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(44).buildCountCommand,o=n(0).handleCallback,s=n(1).MongoError,i=Array.prototype.push,a=n(18).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let s,i={};i.skip=n.skip,i.limit=n.limit,i.hint=n.hint,i.maxTimeMS=n.maxTimeMS,i.collectionName=e.namespace.collection;try{s=r(e,e.cmd.query,i)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),s,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw s.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,s.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,s)=>r?o(n,r):null==s?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,s)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((s,a)=>{if(s)return o(t,s);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),i.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(11).buildCountCommand,o=n(3).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let s,i={};i.skip=o.skip,i.limit=o.limit,i.hint=o.hint,i.maxTimeMS=o.maxTimeMS,i.collectionName=t.namespace.collection;try{s=r(t,t.cmd.query,i)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),s,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(78),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(78),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(61);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).deleteCallback,s=n(11).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).deleteCallback,s=n(11).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(24),i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern;class c extends s{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,s=this.options,c={distinct:n.collectionName,key:r,query:o};"number"==typeof s.maxTimeMS&&(c.maxTimeMS=s.maxTimeMS),a(c,n,s);try{i(c,n,s)}catch(e){return t(e,null)}super.executeCommand(e,c,(e,n)=>{e?t(e):t(null,this.options.full?n:n.values)})}}o(c,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(112),i=n(0).handleCallback;class a extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return i(e,t,!1);i(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(24);class i extends s{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(i,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(3).Aspect,s=n(3).defineAspects,i=n(1).ReadPreference,a=n(4).maxWireVersion,c=n(2).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=i.resolve(e,this.options)}execute(e,t){if(this.server=e,void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}s(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(3).OperationBase,s=n(0).toError;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,s(t),null);r(e,null,n)})}catch(t){e(t)}}}},function(e,t,n){"use strict";const r=n(62);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(62),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new=void 0!==r.returnOriginal&&!r.returnOriginal,s.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(62),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,s.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(3).OperationBase,i=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(13).executeCommand,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(0).toError;class h extends s{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,s={geoSearch:t.collectionName,near:[n,r]};s=i(s,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(s,t,o),c(t.s.db,s,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,p(n)),u(e,null,n)})}}o(h,r.READ_OPERATION),e.exports=h},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(13).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;s(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(3).OperationBase,s=n(11).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));s(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(114),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(24),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(i(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(13).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(82).loadDb,p=n(3).OperationBase,h=n(1).ReadPreference,f=n(0).toError,d=["readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];function m(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let s=t.length-1;s>=0;s--)n=t[s],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=m(e[n]);return r}e.exports=class extends p{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options;const p={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?p[e]=m(u[e]):-1===d.indexOf(e)&&(p[e]=u[e]);u=Object.assign({},u),u.readPreference=h.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(p,{db:t.s.db,collection:t},u)):i(p,t,u),!0===u.bypassDocumentValidation&&(p.bypassDocumentValidation=u.bypassDocumentValidation);try{s(p,t,u)}catch(t){return e(t,null)}a(t.s.db,p,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,f(r));const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let s=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;s=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else s=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,s);c(e,n,{collection:s,stats:o})})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback;let s;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,i=(s||(s=n(45)),s);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new i(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(24),o=n(3).defineAspects,s=n(3).Aspect;class i extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(i,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]),e.exports=i},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(21),i=n(0).applyWriteConcern,a=n(82).loadCollection,c=n(1).MongoError,u=n(1).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class p extends s{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let s=Object.assign({nameOnly:!0,strict:!1},r);function l(s){if(s)return e(s);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(s){e(s)}}s=i(s,{db:t},s);s.strict?t.listCollections({name:n},s).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(p,r.WRITE_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(24),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion,a=n(77);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(i(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=e+".";return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}s(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(21);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(21),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(21);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;enull!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(24),o=n(3).Aspect,s=n(3).defineAspects,i=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new i("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(24),i=n(14).serverType,a=n(14).ServerType,c=n(1).MongoError;class u extends s{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){i(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),s(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(21),s=n(3).defineAspects;class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}s(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).updateCallback,s=n(11).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,s(t,n,r,i,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(11).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!s(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n){if(null==n)return;if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}(t,n,e))}}},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(57),s=n(5).format,i=n(1).Logger,a=n(75),c=n(34);function u(e,t){let n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return!!r.endsWith(o)}function l(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",p=o.parse(e,!0);if((null==p.hostname||""===p.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===p.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(p.port,10))&&parseInt(p.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(p.path&&p.path.length>0&&"/"!==p.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(p.query)for(let e in p.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===p.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(p.auth){let t=p.auth.split(":");if(-1!==e.indexOf(p.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(p.auth)&&-1!==p.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let h=e.split("?").shift().split(","),f=[];for(let e=0;e1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let d,m,y,g,b={},S=a||"",v=S.split(":",2),w=decodeURIComponent(v[0]);if(v[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(v[0]=w,v[1]){let e=decodeURIComponent(v[1]);if(v[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");v[1]=e}2===v.length&&(b.auth={user:v[0],password:v[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},E={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=E,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),y=[{domain_socket:t}]}else{d=n;let e={};y=d.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,E.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,E.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,E.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),E.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),E.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(S);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(S)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");g.zlibCompressionLevel=e,_.compression=g}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:i("URL Parser").warn(n+" is not supported as a connection string option")}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=y,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return l(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let s="_mongodb._tcp."+r.host;a.resolveSrv(s,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e1)return n(new Error("Multiple text records not allowed"));if(!(r=(r=r[0]).length>1?r.join(""):r[0]).includes("authSource")&&!r.includes("replicaSet"))return n(new Error("Text record must only set `authSource` or `replicaSet`"));c.push(r)}c.length&&(i+="?"+c.join("&")),l(i,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(92),r=e.mongodb.MongoTimeoutError,o=n(65),s=o.debug,i=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,i=e._client,a=e._keyVaultNamespace,l=e._keyVaultClient,p=e._mongocryptdClient,h=e._mongocryptdManager;switch(s(`[context#${t.id}] ${u.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(i,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(p,t.ns,o,(s,i)=>{if(s)return s instanceof r&&h&&!h.bypassSpawn?void h.spawn(()=>{this.markCommand(p,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(s,null);t.addMongoOperationResponse(i),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(l,a,r,(r,s)=>{if(r)return n(r,null);s.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c("Unknown state: "+t.state))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],port:r},s=e.message;return new Promise((n,r)=>{const i=t.connect(o,()=>{i.write(s)});i.once("timeout",()=>{i.removeAllListeners(),i.destroy(),r(new c("KMS request timed out"))}),i.once("error",e=>{i.removeAllListeners(),i.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),i.on("data",t=>{e.addResponse(t),e.bytesNeeded<=0&&i.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,s=i(t);e.db(s).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,s=i(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(s).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,s=i(t),c=a(t);n=o.deserialize(n),e.db(s).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(125)("mongocrypt"),r=n(65).databaseNamespace,o=e.stateMachine.StateMachine,s=n(220).MongocryptdManager,i=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(126);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new s(n.extraOptions),this._mongocryptdClient=new i(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=n.kmsProviders),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&t.message.match(/timed out after/)?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,s){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==s&&(s=n,n={}),this._bypassEncryption)return void s(void 0,t);const i=this._bson,a=Buffer.isBuffer(t)?t:i.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void s(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t;new o(Object.assign({bson:i},n)).execute(this,c,s)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,s=Buffer.isBuffer(e)?e:r.serialize(e,t);let i;try{i=this._mongocrypt.makeDecryptionContext(s)}catch(e){return void n(e,null)}i.id=this._contextCounter++;new o(Object.assign({bson:r},t)).execute(this,i,n)}}}}},function(e,t,n){var r=n(37).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),s=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);s=s.replace(/^(.+)\|/,"$1:"),"\\"==r&&(s=s.replace(/\//g,"\\"));/^.+\:/.test(s)||(s=r+s);return o+s}},function(e,t,n){"use strict";const r=n(221).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(125)("mongocrypt"),r=n(65),o=r.databaseNamespace,s=r.collectionNamespace,i=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(126);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r{u.execute(this,c,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),i=s(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(i).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),s=Object.assign({},t);if(t.keyId&&(s.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError('"options.keyAltName" must be of type string, but was of type '+n);s.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,s);return i(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),s=new a({bson:n});return i(t,e=>{s.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(127),o=n(1).BSON.ObjectID,s=n(1).ReadPreference,i=n(15).Buffer,a=n(38),c=n(5).format,u=n(5),l=n(1).MongoError,p=u.inherits,h=n(22).Duplex,f=n(0).shallowClone,d=n(0).executeLegacyOperation,m=n(5).deprecate;const y=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var g=function e(t,n,i,a,c){if(y(),!(this instanceof e))return new e(t,n,i,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=i,i=void 0):"object"==typeof a&&(c=a,a=i,i=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=i):void 0===i?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=i),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||s.primary,this.writeConcern=z(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};g.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return d(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=z(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=f(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};g.prototype.eof=function(){return this.position===this.length},g.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,S,[this,e,t],{skipSessions:!0})};var S=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?I(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};g.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return d(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},g.prototype.stream=function(){return new F(this)},g.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},d(this.db.s.topology,j,[this,e,t,n,r],{skipSessions:!0})},g.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},g.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},d(this.db.s.topology,v,[this,e,t,n],{skipSessions:!0})};var v=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,s){if(e)return o(e,n);var c=0,u=0,l=function(){var e=i.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,i,p){if(e)return o(e,n);c+=i,new r(n,{n:u++},n.writeConcern).write(p.slice(0,i),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+i,n.currentChunk=r,c>=s.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};g.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate||(e.uploadDate=new Date),N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};g.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},g.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};g.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},g.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},d(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var c=e.currentChunk.readSlice(s-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===s&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,I(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};g.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},g.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},d(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var s=null==n?g.IO_SEEK_SET:n,i=t,a=0;a=s===g.IO_SEEK_CUR?e.position+i:s===g.IO_SEEK_END?e.length+i:i;var c=Math.floor(a/e.chunkSize);I(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},x=function(e,t,n){var s=e.collection(),i=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}i=null==e.fileId&&null==e.filename?null:i,t.readPreference=e.readPreference,null!=i?s.findOne(i,t,(function(s,i){if(s)return a(s);if(null!=i)e.fileId=i._id,e.filename="r"===e.mode||void 0===e.filename?i.filename:e.filename,e.contentType=i.contentType,e.internalChunkSize=i.chunkSize,e.uploadDate=i.uploadDate,e.aliases=i.aliases,e.length=i.length,e.metadata=i.metadata,e.internalMd5=i.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?I(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&i?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var s="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),s?e.close((function(t){o(t,e)})):o(null,e);for(var i=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),p=t.slice(a),h=[e.currentChunk.write(u)];p.length>=e.chunkSize;){var f=new r(e,{n:i+1},e.writeConcern);u=p.slice(0,e.chunkSize),p=p.slice(e.chunkSize),i+=1,f.write(u),h.push(f)}e.currentChunk=new r(e,{n:i+1},e.writeConcern),p.length>0&&e.currentChunk.write(p),e.position=e.position+t.length;for(var d=h.length,m=0;m=t.length?s("offset larger than size of file",null):n&&n>t.length?s("length is larger than the size of the file",null):r&&n&&r+n>t.length?s("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return s(e);t.read(n,s)})):t.read(n,s))}))};g.readlines=function(e,t,n,r,o){var s=Array.prototype.slice.call(arguments,2);return o="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=(r=s.length?s.shift():null)||{},d(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var s=null==n?"\n":n;new g(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};g.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},d(e.s.topology,L,[this,e,t,n,r],{skipSessions:!0})};var L=function(e,t,n,r,o){var s=z(t,r);if(n.constructor===Array)for(var i=0,a=0;ae.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var s={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)},p.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,f,[this,e,t,n],{skipSessions:!0})},p.prototype.drop=function(e){return u(this.s.db.s.topology,d,[this,e],{skipSessions:!0})},p.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(22),o=n(5);function s(e,t,n,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:s,readPreference:n},r.Readable.call(this)}function i(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=s,o.inherits(s,r.Readable),s.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end0&&(s.n={$gte:i})}e.s.cursor=e.s.chunks.find(s).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,s=Math.min(e.s.file.chunkSize,r);if(n.n>o){var i="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(i))}if(n.n0;){var d=o.length-s;if(o.copy(e.bufToStore,e.pos,d,d+c),e.pos+=c,0===(i-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++p,y(e,r))return!1;e.chunks.insertOne(m,f(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--p||(e.emit("drain",m),r&&r(),h(e))})),i=e.chunkSizeBytes,e.pos=0,++e.n}s-=c,c=Math.min(i,s)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),y(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):d(this,(function(){m(r)})))}},function(e,t,n){var r,o; + */e.exports=function(e,t){if("string"==typeof e)return c(e);if("number"==typeof e)return a(e,t);return null},e.exports.format=a,e.exports.parse=c;var r=/\B(?=(\d{3})+(?!\d))/g,o=/(?:\.0*|(\.[^0]+)0+)$/,s={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},i=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function a(e,t){if(!Number.isFinite(e))return null;var n=Math.abs(e),i=t&&t.thousandsSeparator||"",a=t&&t.unitSeparator||"",c=t&&void 0!==t.decimalPlaces?t.decimalPlaces:2,u=Boolean(t&&t.fixedDecimals),l=t&&t.unit||"";l&&s[l.toLowerCase()]||(l=n>=s.pb?"PB":n>=s.tb?"TB":n>=s.gb?"GB":n>=s.mb?"MB":n>=s.kb?"KB":"B");var p=(e/s[l.toLowerCase()]).toFixed(c);return u||(p=p.replace(o,"$1")),i&&(p=p.replace(r,i)),p+a+l}function c(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var t,n=i.exec(e),r="b";return n?(t=parseFloat(n[1]),r=n[4].toLowerCase()):(t=parseInt(e,10),r="b"),Math.floor(s[r]*t)}},function(e,t,n){"use strict";const r=n(233);e.exports=e=>{const t=r(0,e.length-1);return()=>e[t()]}},function(e,t,n){"use strict";var r=n(70),o=n(33),s=n(48),i=n(49),a=n(50),c=n(51),u=n(52),l=n(71),p=n(53),h=n(54),f=n(55),d=n(56),m=n(57),y=n(38),g=n(135),b=n(136),S=n(138),v=n(28),w=v.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,s="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.lengthe.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,i=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!i)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,p=null!=n.promoteBuffers&&n.promoteBuffers,h=null==n.promoteLongs||n.promoteLongs,f=null==n.promoteValues||n.promoteValues,d=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var y=r?[]:{},g=0;;){var b=e[t++];if(0===b)break;for(var S=t;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var v=r?g++:e.toString("utf8",t,S);if(t=S+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),y[v]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===f)y[v]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)y[v]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===f)y[v]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)y[v]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;y[v]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");y[v]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var E=t,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(C<=0||C>e.length-t)throw new Error("bad embedded document length in bson");y[v]=u?e.slice(t,t+C):deserializeObject(e,E,n,!1),t+=C}else if(b===BSON.BSON_DATA_ARRAY){E=t;var x=n,A=t+(C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[v]){for(var N in x={},n)x[N]=n[N];x.raw=!0}if(y[v]=deserializeObject(e,E,x,!0),0!==e[(t+=C)-1])throw new Error("invalid array terminator byte");if(t!==A)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)y[v]=void 0;else if(b===BSON.BSON_DATA_NULL)y[v]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var I=new Long(O,T);y[v]=h&&!0===f&&I.lessThanOrEqual(JS_INT_MAX_LONG)&&I.greaterThanOrEqual(JS_INT_MIN_LONG)?I.toNumber():I}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);y[v]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,D=R,B=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(B===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>D-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(RD-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,S);for(S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var j=e.toString("utf8",t,S);t=S+1;var U=new Array(j.length);for(S=0;S=e.length)throw new Error("Bad BSON Document: illegal CString");for(L=e.toString("utf8",t,S),S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");j=e.toString("utf8",t,S),t=S+1,y[v]=new BSONRegExp(L,j)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,y[v]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)y[v]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)y[v]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var z=e.toString("utf8",t,t+w-1);if(o)if(s){var F=i?a(z):z;y[v]=isolateEvalWithHash(functionCache,F,z,y)}else y[v]=isolateEval(z);else y[v]=new Code(z);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(W<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");z=e.toString("utf8",t,t+w-1),E=t+=w,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,E,n,!1);if(t+=C,W<8+C+w)throw new Error("code_w_scope total size is to short, truncating scope");if(W>8+C+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(s?(F=i?a(z):z,y[v]=isolateEvalWithHash(functionCache,F,z,y)):y[v]=isolateEval(z),y[v].scope=q):y[v]=new Code(z,q)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+v+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var $=e.toString("utf8",t,t+w-1);t+=w;var H=utils.allocBuffer(12);e.copy(H,0,t,t+12),_=new ObjectID(H),t+=12;var V=$.split("."),Y=V.shift(),G=V.join(".");y[v]=new DBRef(G,_,Y)}}if(m!==t-d){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=y.$id&&(y=new DBRef(y.$ref,y.$id,y.$db)),y},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(137).writeIEEE754,o=n(33).Long,s=n(70),i=n(38).Binary,a=n(28).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},p=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},h=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var s=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+s+1)-1]=0;var i=e.write(n,r+4,"utf8");return e[r+3]=i+1>>24&255,e[r+2]=i+1>>16&255,e[r+1]=i+1>>8&255,e[r]=i+1&255,r=r+4+i,e[r++]=0,r},f=function(e,t,n,s,i){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[s++]=R.BSON_DATA_INT;var a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8");s+=a,e[s++]=0,e[s++]=255&n,e[s++]=n>>8&255,e[s++]=n>>16&255,e[s++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;else{e[s++]=R.BSON_DATA_LONG,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[s++]=255&u,e[s++]=u>>8&255,e[s++]=u>>16&255,e[s++]=u>>24&255,e[s++]=255&l,e[s++]=l>>8&255,e[s++]=l>>16&255,e[s++]=l>>24&255}else e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;return s},d=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},y=function(e,t,n,r,s){e[r++]=R.BSON_DATA_DATE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=o.fromNumber(n.getTime()),a=i.getLowBits(),c=i.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},g=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.length;return e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,s),r+=s},_=function(e,t,n,r,o,s,i,a,c,u){for(var l=0;l>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,r},E=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},C=function(e,t,n,o,s){return e[o++]=R.BSON_DATA_NUMBER,o+=s?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},x=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_CODE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},A=function(e,t,n,r,o,s,i,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,p="string"==typeof n.code?n.code:n.code.toString();r+=4;var h=e.write(p,r+4,"utf8")+1;e[r]=255&h,e[r+1]=h>>8&255,e[r+2]=h>>16&255,e[r+3]=h>>24&255,e[r+4+h-1]=0,r=r+h+4;var f=M(e,n.scope,o,r,s+1,i,a);r=f-1;var d=f-l;e[l++]=255&d,e[l++]=d>>8&255,e[l++]=d>>16&255,e[l++]=d>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,p=n.code.toString();var m=e.write(p,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},N=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.value(!0),a=n.position;return n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),s.copy(e,r,0,n.position),r+=n.position},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=e.write(n.value,r+4,"utf8")+1;return e[r]=255&s,e[r+1]=s>>8&255,e[r+2]=s>>16&255,e[r+3]=s>>24&255,r=r+4+s-1,e[r++]=0,r},k=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_OBJECT,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,s):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,s))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,i,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var D=0;D>8&255,e[r++]=F>>16&255,e[r++]=F>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var s,i,a="big"===n,c=8*o-r-1,u=(1<>1,p=-7,h=a?0:o-1,f=a?1:-1,d=e[t+h];for(h+=f,s=d&(1<<-p)-1,d>>=-p,p+=c;p>0;s=256*s+e[t+h],h+=f,p-=8);for(i=s&(1<<-p)-1,s>>=-p,p+=r;p>0;i=256*i+e[t+h],h+=f,p-=8);if(0===s)s=1-l;else{if(s===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),s-=l}return(d?-1:1)*i*Math.pow(2,s-r)},t.writeIEEE754=function(e,t,n,r,o,s){var i,a,c,u="big"===r,l=8*s-o-1,p=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=u?s-1:0,m=u?-1:1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=p):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=p?(a=0,i=p):i+h>=1?(a=(t*c-1)*Math.pow(2,o),i+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;e[n+d]=255&a,d+=m,a/=256,o-=8);for(i=i<0;e[n+d]=255&i,d+=m,i/=256,l-=8);e[n+d-m]|=128*y}},function(e,t,n){"use strict";var r=n(33).Long,o=n(48).Double,s=n(49).Timestamp,i=n(50).ObjectID,a=n(52).Symbol,c=n(51).BSONRegExp,u=n(53).Code,l=n(54),p=n(55).MinKey,h=n(56).MaxKey,f=n(57).DBRef,d=n(38).Binary,m=n(28).normalizedFunctionString,y=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return g||!S?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof p||t instanceof h||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof i||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof s||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+y(t.scope,n,S):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof d||"Binary"===t._bsontype)return t.sub_type===d.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof f||"DBRef"===t._bsontype){var v={$ref:t.namespace,$id:t.oid};return null!=t.db&&(v.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+y(v,n,S)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+y(t,n,S)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+y(t.scope,n,S);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=y},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";var r=n(39),o=n(141);e.exports=function(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected `fromDir` and `moduleId` to be a string");e=r.resolve(e);var n=r.join(e,"noop.js");try{return o._resolveFilename(t,{id:n,filename:n,paths:o._nodeModulePaths(e)})}catch(e){return null}}},function(e,t){e.exports=require("module")},function(e,t){var n;t=e.exports=V,n="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var r=Number.MAX_SAFE_INTEGER||9007199254740991,o=t.re=[],s=t.src=[],i=0,a=i++;s[a]="0|[1-9]\\d*";var c=i++;s[c]="[0-9]+";var u=i++;s[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var l=i++;s[l]="("+s[a]+")\\.("+s[a]+")\\.("+s[a]+")";var p=i++;s[p]="("+s[c]+")\\.("+s[c]+")\\.("+s[c]+")";var h=i++;s[h]="(?:"+s[a]+"|"+s[u]+")";var f=i++;s[f]="(?:"+s[c]+"|"+s[u]+")";var d=i++;s[d]="(?:-("+s[h]+"(?:\\."+s[h]+")*))";var m=i++;s[m]="(?:-?("+s[f]+"(?:\\."+s[f]+")*))";var y=i++;s[y]="[0-9A-Za-z-]+";var g=i++;s[g]="(?:\\+("+s[y]+"(?:\\."+s[y]+")*))";var b=i++,S="v?"+s[l]+s[d]+"?"+s[g]+"?";s[b]="^"+S+"$";var v="[v=\\s]*"+s[p]+s[m]+"?"+s[g]+"?",w=i++;s[w]="^"+v+"$";var _=i++;s[_]="((?:<|>)?=?)";var O=i++;s[O]=s[c]+"|x|X|\\*";var T=i++;s[T]=s[a]+"|x|X|\\*";var E=i++;s[E]="[v=\\s]*("+s[T]+")(?:\\.("+s[T]+")(?:\\.("+s[T]+")(?:"+s[d]+")?"+s[g]+"?)?)?";var C=i++;s[C]="[v=\\s]*("+s[O]+")(?:\\.("+s[O]+")(?:\\.("+s[O]+")(?:"+s[m]+")?"+s[g]+"?)?)?";var x=i++;s[x]="^"+s[_]+"\\s*"+s[E]+"$";var A=i++;s[A]="^"+s[_]+"\\s*"+s[C]+"$";var N=i++;s[N]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var I=i++;s[I]="(?:~>?)";var k=i++;s[k]="(\\s*)"+s[I]+"\\s+",o[k]=new RegExp(s[k],"g");var M=i++;s[M]="^"+s[I]+s[E]+"$";var R=i++;s[R]="^"+s[I]+s[C]+"$";var D=i++;s[D]="(?:\\^)";var B=i++;s[B]="(\\s*)"+s[D]+"\\s+",o[B]=new RegExp(s[B],"g");var P=i++;s[P]="^"+s[D]+s[E]+"$";var L=i++;s[L]="^"+s[D]+s[C]+"$";var j=i++;s[j]="^"+s[_]+"\\s*("+v+")$|^$";var U=i++;s[U]="^"+s[_]+"\\s*("+S+")$|^$";var z=i++;s[z]="(\\s*)"+s[_]+"\\s*("+v+"|"+s[E]+")",o[z]=new RegExp(s[z],"g");var F=i++;s[F]="^\\s*("+s[E]+")\\s+-\\s+("+s[E]+")\\s*$";var W=i++;s[W]="^\\s*("+s[C]+")\\s+-\\s+("+s[C]+")\\s*$";var q=i++;s[q]="(<|>)?=?\\s*\\*";for(var $=0;$<35;$++)n($,s[$]),o[$]||(o[$]=new RegExp(s[$]));function H(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?o[w]:o[b]).test(e))return null;try{return new V(e,t)}catch(e){return null}}function V(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof V))return new V(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var s=e.trim().match(t.loose?o[w]:o[b]);if(!s)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);-1===n&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,n,r){"string"==typeof n&&(r=n,n=void 0);try{return new V(e,n).inc(t,r).version}catch(e){return null}},t.diff=function(e,t){if(Z(e,t))return null;var n=H(e),r=H(t),o="";if(n.prerelease.length||r.prerelease.length){o="pre";var s="prerelease"}for(var i in n)if(("major"===i||"minor"===i||"patch"===i)&&n[i]!==r[i])return o+i;return s},t.compareIdentifiers=G;var Y=/^[0-9]+$/;function G(e,t){var n=Y.test(e),r=Y.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e0}function J(e,t,n){return K(e,t,n)<0}function Z(e,t,n){return 0===K(e,t,n)}function Q(e,t,n){return 0!==K(e,t,n)}function ee(e,t,n){return K(e,t,n)>=0}function te(e,t,n){return K(e,t,n)<=0}function ne(e,t,n,r){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return Z(e,n,r);case"!=":return Q(e,n,r);case">":return X(e,n,r);case">=":return ee(e,n,r);case"<":return J(e,n,r);case"<=":return te(e,n,r);default:throw new TypeError("Invalid operator: "+t)}}function re(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof re){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof re))return new re(e,t);n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===oe?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}t.rcompareIdentifiers=function(e,t){return G(t,e)},t.major=function(e,t){return new V(e,t).major},t.minor=function(e,t){return new V(e,t).minor},t.patch=function(e,t){return new V(e,t).patch},t.compare=K,t.compareLoose=function(e,t){return K(e,t,!0)},t.rcompare=function(e,t,n){return K(t,e,n)},t.sort=function(e,n){return e.sort((function(e,r){return t.compare(e,r,n)}))},t.rsort=function(e,n){return e.sort((function(e,r){return t.rcompare(e,r,n)}))},t.gt=X,t.lt=J,t.eq=Z,t.neq=Q,t.gte=ee,t.lte=te,t.cmp=ne,t.Comparator=re;var oe={};function se(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof se)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new se(e.raw,t);if(e instanceof re)return new se(e.value,t);if(!(this instanceof se))return new se(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ie(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,n,r,o,s,i,a,c,u,l,p,h){return((t=ie(n)?"":ie(r)?">="+n+".0.0":ie(o)?">="+n+"."+r+".0":">="+t)+" "+(a=ie(c)?"":ie(u)?"<"+(+c+1)+".0.0":ie(l)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+l+"-"+p:"<="+a)).trim()}function ce(e,t,r){for(var o=0;o0){var s=e[o].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}function ue(e,t,n){try{t=new se(t,n)}catch(e){return!1}return t.test(e)}function le(e,t,n,r){var o,s,i,a,c;switch(e=new V(e,r),t=new se(t,r),n){case">":o=X,s=te,i=J,a=">",c=">=";break;case"<":o=J,s=ee,i=X,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,r))return!1;for(var u=0;u=0.0.0")),p=p||e,h=h||e,o(e.semver,p.semver,r)?p=e:i(e.semver,h.semver,r)&&(h=e)})),p.operator===a||p.operator===c)return!1;if((!h.operator||h.operator===a)&&s(e,h.semver))return!1;if(h.operator===c&&i(e,h.semver))return!1}return!0}re.prototype.parse=function(e){var t=this.options.loose?o[j]:o[U],n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1],"="===this.operator&&(this.operator=""),n[2]?this.semver=new V(n[2],this.options.loose):this.semver=oe},re.prototype.toString=function(){return this.value},re.prototype.test=function(e){return n("Comparator.test",e,this.options.loose),this.semver===oe||("string"==typeof e&&(e=new V(e,this.options)),ne(e,this.operator,this.semver,this.options))},re.prototype.intersects=function(e,t){if(!(e instanceof re))throw new TypeError("a Comparator is required");var n;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return n=new se(e.value,t),ue(this.value,n,t);if(""===e.operator)return n=new se(this.value,t),ue(e.semver,n,t);var r=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),o=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),s=this.semver.version===e.semver.version,i=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=ne(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=ne(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return r||o||s&&i||a||c},t.Range=se,se.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},se.prototype.toString=function(){return this.range},se.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var r=t?o[W]:o[F];e=e.replace(r,ae),n("hyphen replace",e),e=e.replace(o[z],"$1$2$3"),n("comparator trim",e,o[z]),e=(e=(e=e.replace(o[k],"$1~")).replace(o[B],"$1^")).split(/\s+/).join(" ");var s=t?o[j]:o[U],i=e.split(" ").map((function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){n("caret",e,t);var r=t.loose?o[L]:o[P];return e.replace(r,(function(t,r,o,s,i){var a;return n("caret",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a="0"===r?">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":">="+r+"."+o+".0 <"+(+r+1)+".0.0":i?(n("replaceCaret pr",i),a="0"===r?"0"===o?">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+"-"+i+" <"+(+r+1)+".0.0"):(n("no pr"),a="0"===r?"0"===o?">="+r+"."+o+"."+s+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+" <"+(+r+1)+".0.0"),n("caret return",a),a}))}(e,t)})).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var r=t.loose?o[R]:o[M];return e.replace(r,(function(t,r,o,s,i){var a;return n("tilde",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a=">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":i?(n("replaceTilde pr",i),a=">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0"):a=">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0",n("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var r=t.loose?o[A]:o[x];return e.replace(r,(function(t,r,o,s,i,a){n("xRange",e,t,r,o,s,i,a);var c=ie(o),u=c||ie(s),l=u||ie(i);return"="===r&&l&&(r=""),c?t=">"===r||"<"===r?"<0.0.0":"*":r&&l?(u&&(s=0),i=0,">"===r?(r=">=",u?(o=+o+1,s=0,i=0):(s=+s+1,i=0)):"<="===r&&(r="<",u?o=+o+1:s=+s+1),t=r+o+"."+s+"."+i):u?t=">="+o+".0.0 <"+(+o+1)+".0.0":l&&(t=">="+o+"."+s+".0 <"+o+"."+(+s+1)+".0"),n("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(o[q],"")}(e,t),n("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter((function(e){return!!e.match(s)}))),i=i.map((function(e){return new re(e,this.options)}),this)},se.prototype.intersects=function(e,t){if(!(e instanceof se))throw new TypeError("a Range is required");return this.set.some((function(n){return n.every((function(n){return e.set.some((function(e){return e.every((function(e){return n.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new se(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},se.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new V(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!X(n,t)||(n=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(n&&e.test(n))return n;return null},t.validRange=function(e,t){try{return new se(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,n){return le(e,t,"<",n)},t.gtr=function(e,t,n){return le(e,t,">",n)},t.outside=le,t.prerelease=function(e,t){var n=H(e,t);return n&&n.prerelease.length?n.prerelease:null},t.intersects=function(e,t,n){return e=new se(e,n),t=new se(t,n),e.intersects(t)},t.coerce=function(e){if(e instanceof V)return e;if("string"!=typeof e)return null;var t=e.match(o[N]);if(null==t)return null;return H(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"_from":"mongodb@^3.6.0","_id":"mongodb@3.6.0","_inBundle":false,"_integrity":"sha512-/XWWub1mHZVoqEsUppE0GV7u9kanLvHxho6EvBxQbShXTKYF9trhZC2NzbulRGeG7xMJHD8IOWRcdKx5LPjAjQ==","_location":"/mongodb","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"mongodb@^3.6.0","name":"mongodb","escapedName":"mongodb","rawSpec":"^3.6.0","saveSpec":null,"fetchSpec":"^3.6.0"},"_requiredBy":["#DEV:/","/mongodb-memory-server-core"],"_resolved":"https://registry.npmjs.org/mongodb/-/mongodb-3.6.0.tgz","_shasum":"babd7172ec717e2ed3f85e079b3f1aa29dce4724","_spec":"mongodb@^3.6.0","_where":"/repos/.nhscc/airports.api.hscc.bdpa.org","bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"bundleDependencies":false,"dependencies":{"bl":"^2.2.0","bson":"^1.1.4","denque":"^1.4.1","require_optional":"^1.0.1","safe-buffer":"^5.1.2","saslprep":"^1.0.0"},"deprecated":false,"description":"The official MongoDB driver for Node.js","devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^4.5.0","eslint-plugin-prettier":"^2.2.0","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","standard-version":"^4.4.0","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"engines":{"node":">=4"},"files":["index.js","lib"],"homepage":"https://github.com/mongodb/node-mongodb-native","keywords":["mongodb","driver","official"],"license":"Apache-2.0","main":"index.js","name":"mongodb","optionalDependencies":{"saslprep":"^1.0.0"},"peerOptionalDependencies":{"kerberos":"^1.1.0","mongodb-client-encryption":"^1.0.0","mongodb-extjson":"^2.1.2","snappy":"^6.3.4","bson-ext":"^2.0.0"},"repository":{"type":"git","url":"git+ssh://git@github.com/mongodb/node-mongodb-native.git"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","bench":"node test/benchmarks/driverBench/","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional","format":"prettier --print-width 100 --tab-width 2 --single-quote --write \'test/**/*.js\' \'lib/**/*.js\'","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","lint":"eslint -v && eslint lib test","release":"standard-version -i HISTORY.md","test":"npm run lint && mocha --recursive test/functional test/unit test/core","test-nolint":"mocha --recursive test/functional test/unit test/core"},"version":"3.6.0"}')},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(10).EventEmitter,s=n(2).MongoError,i=n(2).MongoTimeoutError,a=n(2).MongoWriteConcernError,c=n(19),u=n(5).format,l=n(35).Msg,p=n(74),h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(94),S=n(16).Buffer,v=n(76),w=n(31).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,E="destroying",C="destroyed",x=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",E,C],[E]:[E,C],[C]:[C]}),A=new Set(["error","close","timeout","parseError","connect","message"]);var N=0,I=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:36e4,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=N++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;oe.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==C&&e.state!==E&&"draining"!==e.state&&e.options.reconnect&&x(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval));B(e){null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}}function D(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function B(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){x(e,E),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],x(e,C),"function"==typeof r&&r(null,null))})}function L(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(t))return n(null,r);const o=S.concat(r),s=o.slice(h),i=o.readInt32LE(12);m(e,s,(function(r,o){if(r)return n(r,null);const a=S.alloc(h);a.writeInt32LE(h+f+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(d.OP_COMPRESSED,12);const c=S.alloc(f);return c.writeInt32LE(i,0),c.writeInt32LE(s.length,4),c.writeUInt8(y[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function j(e,t){for(var n=0;n(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===C||e.state===E?("function"==typeof t&&t(new s("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void W(e)())))):"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}function F(e){for(var t=0;t0)e.executing=!1;else{for(;;){const i=B(e);if(0===e.availableConnections.length){F(e.queue),i0&&z(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){U(e,t),F(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n0&&z(e),setTimeout(()=>W(e)(),10);break}}if(i0){e.queue.unshift(n),z(e);break}var o=n.buffer;n.monitoring&&D(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var s=!0;if(Array.isArray(o))for(let e=0;e{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(x(this,"connected"),this.minSize)for(let e=0;e0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new s("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==C&&n.state!==E)if(F(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o0)return setTimeout(e,1);P(n,r,{force:!1},t)}else W(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},I.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new s("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),z(this,()=>{"function"==typeof e&&e(null,null)}))})},I.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new s("write method must provide a callback");if(this.state!==C&&this.state!==E)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,i.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,i.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,i.started)),"function"==typeof n&&n(t,o)}),L(r,e,(e,n)=>{if(e)throw e;i.buffer=n,t.monitoring?r.queue.unshift(i):r.queue.push(i),r.executing||process.nextTick((function(){W(r)()}))})}else n(new s("pool is draining, new operations prohibited"));else n(new s("pool destroyed"))},I._execute=W,e.exports=I},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:c}=n(149);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=h(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),s=h(o);if(s.some(e=>i.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(s.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const f=s.some(e=>a.get(e)),d=s.some(e=>c.get(e));if(f&&d)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(p((g=o,g[0]))),y=a.get(p((e=>e[e.length-1])(o)));var g;if(f&&(!m||!y))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=s,l=o,p=e=>e.codePointAt(0);function h(e){const t=[],n=e.length;for(let r=0;r=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(40),o=n(39),s=n(150),i=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);return a+=e,s({buffer:t})}const u=c(),l=c(),p=c(),h=c(),f=c(),d=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:p,prohibited_characters:h,bidirectional_r_al:f,bidirectional_l:d}}).call(this,"/")},function(e,t,n){var r=n(151);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages0;s--){var i=this.path[s],a=o[i];if(!a){if(t)return;a=o[i]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,s,i=this._array(e,t),a=this.path[0],c=i&&i[a];return c||t||(c=i[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,s=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(s),s),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),s=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[s]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=n[s],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);i?i.buffer=a:n[s]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new s(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new s("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void d("http://169.254.170.2"+process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,(e,r)=>{if(e)return t(e);n(r)});d(p+"/latest/api/token",{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);d(`${p}/${h}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);d(`${p}/${h}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,y=r.mechanismProperties.AWS_SESSION_TOKEN,g=this.bson;i.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:g.serialize({r:r,p:110})};n.command(m+".$cmd",o,(e,o)=>{if(e)return t(e);const i=o.result,c=g.deserialize(i.payload.buffer),p=c.h,h=c.s.buffer;if(64!==h.length)return void t(new s(`Invalid server nonce length ${h.length}, expected 64`));if(0!==h.compare(r,0,r.length,0,r.length))return void t(new s("Server nonce does not begin with client nonce"));if(p.length<1||p.length>255||-1!==p.indexOf(".."))return void t(new s(`Server returned an invalid host: "${p}"`));const d="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:p,region:f(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":d.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:d},{accessKeyId:a,secretAccessKey:u,token:y}),S={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};y&&(S.t=y);const v={saslContinue:1,conversationId:1,payload:g.serialize(S)};n.command(m+".$cmd",v,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(59),s=n(102),i=n(21),a=n(155)(1e3);function c(e,t,n){return i.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return i.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function p(e){return l(encodeURIComponent(e))}function h(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}h.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var n=0;n<2;n++)if(/^s3-/.test(t[n])){t[1]=t[n].slice(3),t[0]="s3";break}return t},h.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},h.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},h.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},h.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},h.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},h.prototype.getDate=function(){return this.getDateTime().substr(0,8)},h.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},h.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),s=a.get(o);return s||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),s=c(n,"aws4_request"),a.set(o,s)),c(s,this.stringToSign(),"hex")},h.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},h.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",s="s3"!==this.service,i="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[p(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),h=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(p).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+p(l[e]))})),o=h.join("&")}return"/"!==t&&(s&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return s&&".."===t?e.pop():s&&"."===t||(i&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(p(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},h.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()=0&&(n=s.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},h.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(s.stringify(t))):e},r.RequestSigner=h,r.sign=function(e,t){return new h(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(7).collectionNamespace,s=n(42);e.exports=function(e,t,n,i,a,c,u){if(0===a.length)throw new r(t+" must contain at least one document");"function"==typeof c&&(u=c,c={});const l="boolean"!=typeof(c=c||{}).ordered||c.ordered,p=c.writeConcern,h={};if(h[t]=o(i),h[n]=a,h.ordered=l,p&&Object.keys(p).length>0&&(h.writeConcern=p),c.collation)for(let e=0;e{};const l=n.cursorId;if(a(e)<4){const o=e.s.bson,s=e.s.pool,i=new r(o,t,[l]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),s&&s.isConnected())try{s.write(i,a,u)}catch(e){"function"==typeof u?u(e,null):console.warn(e)}return}const p={killCursors:i(t),cursors:[l]},h={};"object"==typeof n.session&&(h.session=n.session),c(e,t,p,h,(e,t)=>{if(e)return u(e);const n=t.message;return n.cursorNotFound?u(new s("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void u(null,n.documents[0]):u(new o("invalid killCursors result returned for cursor id "+l))})}},function(e,t,n){"use strict";const r=n(22).GetMore,o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=o().Long,c=n(7).collectionNamespace,u=n(4).maxWireVersion,l=n(7).applyCommonQueryOptions,p=n(42);e.exports=function(e,t,n,o,h,f){h=h||{};const d=u(e);function m(e,t){if(e)return f(e);const r=t.message;if(r.cursorNotFound)return f(new i("cursor killed or timed out"),null);if(d<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void f(null,null,r.connection)}if(0===r.documents[0].ok)return f(new s(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,f(null,r.documents[0],r.connection)}if(d<4){const s=e.s.bson,i=new r(s,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(i,a,m)}const y={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(y.maxTimeMS=n.cmd.maxAwaitTimeMS);const g=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},h);n.session&&(g.session=n.session),p(e,t,y,g,m)}},function(e,t,n){"use strict";const r=n(22).Query,o=n(2).MongoError,s=n(7).getReadPreference,i=n(7).collectionNamespace,a=n(7).isSharded,c=n(4).maxWireVersion,u=n(7).applyCommonQueryOptions,l=n(42);e.exports=function(e,t,n,p,h,f){if(h=h||{},null!=p.cursorId)return f();if(null==n)return f(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const i=function(e,t,n,i,c){c=c||{};const u=e.s.bson,l=s(n,c);i.batchSize=n.batchSize||i.batchSize;let p=0;p=i.limit<0||0!==i.limit&&i.limit0&&0===i.batchSize?i.limit:i.batchSize;const h=i.skip||0,f={};a(e)&&l&&(f.$readPreference=l.toJSON());n.sort&&(f.$orderby=n.sort);n.hint&&(f.$hint=n.hint);n.snapshot&&(f.$snapshot=n.snapshot);void 0!==n.returnKey&&(f.$returnKey=n.returnKey);n.maxScan&&(f.$maxScan=n.maxScan);n.min&&(f.$min=n.min);n.max&&(f.$max=n.max);void 0!==n.showDiskLoc&&(f.$showDiskLoc=n.showDiskLoc);n.comment&&(f.$comment=n.comment);n.maxTimeMS&&(f.$maxTimeMS=n.maxTimeMS);n.explain&&(p=-Math.abs(n.limit||0),f.$explain=!0);if(f.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o("server find command does not support a readConcern level of "+n.readConcern.level);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const d="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,y=new r(u,t,f,{numberToSkip:h,numberToReturn:p,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:d,ignoreUndefined:m});"boolean"==typeof n.tailable&&(y.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(y.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(y.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(y.awaitData=n.awaitData);"boolean"==typeof n.partial&&(y.partial=n.partial);return y.slaveOk=l.slaveOk(),y}(e,t,n,p,h),c=u({},p);return"string"==typeof i.documentsReturnedIn&&(c.documentsReturnedIn=i.documentsReturnedIn),void e.s.pool.write(i,c,f)}const d=s(n,h),m=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;let o={find:i(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let s=n.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[s[0]]=t}else for(let t=0;te.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),s()}var r=new p(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",i(e,"connect")),r.once("close",i(e,"close")),r.once("timeout",i(e,"timeout")),r.once("error",i(e,"error")),r.once("parseError",i(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),g(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c0&&e.emit(t,n)}A.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},E(this,"connecting");var n=this.s.seedlist.map((function(n){return new p(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",B(e,"close")),t.once("timeout",B(e,"timeout")),t.once("parseError",B(e,"parseError")),t.once("error",B(e,"error")),t.once("connect",B(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),g(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),E(this,T),"function"==typeof t&&t(null,null))};this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o{if(!o)return n(null,s);if(!w(o,r))return o=S(o),n(o);if(c){return L(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[s](i,a,t,u)}A.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof i?e:t.readPreference||i.primary;const s=_(),a=()=>{if(O(s)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof p))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},A.prototype.getServers=function(){return this.s.replicaSetState.allServers()},A.prototype.insert=function(e,t,n,r){L({self:this,op:"insert",ns:e,ops:t},n,r)},A.prototype.update=function(e,t,n,r){L({self:this,op:"update",ns:e,ops:t},n,r)},A.prototype.remove=function(e,t,n,r){L({self:this,op:"remove",ns:e,ops:t},n,r)};const j=["findAndModify","insert","update","delete"];A.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var s=this,a=n.readPreference?n.readPreference:i.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof p))return r(c);if(s.s.debug&&s.emit("pickedServer",i.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&y(s)&&!n.session.inTransaction()&&(h=t,j.some(e=>h[e]));var h;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!w(o,s))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=A},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,s=n(9).diff,i=n(10).EventEmitter,a=n(19),c=n(13),u=n(2).MongoError,l=n(16).Buffer,p="ReplicaSetNoPrimary",h="ReplicaSetWithPrimary",f="Unknown",d="PossiblePrimary",m="RSPrimary",y="RSSecondary",g="RSArbiter",b="RSOther",S="RSGhost",v="Unknown",w=function(e){e=e||{},i.call(this),this.topologyType=p,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,i),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,I(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var s=0;sc)return!1}else if(!l&&i&&c&&c=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&null==e.maxStalenessSeconds){var o=E(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=E(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var s=n[e.index];return e.index=e.index+1,s}function C(e,t,n){for(var r=0;r0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var i=s(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:i};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,s=n(10).EventEmitter,i=n(20).CoreCursor,a=n(19),c=n(11).retrieveBSON,u=n(2).MongoError,l=n(75),p=n(9).diff,h=n(9).cloneOptions,f=n(9).SessionMixins,d=n(9).isRetryableWritesSupported,m=n(4).relayEvents,y=c(),g=n(9).getMMAPError,b=n(4).makeClientMetadata,S=n(9).legacyIsRetryableWriteError;var v="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",v,w,"disconnected"],connecting:["connecting",v,w,"connected","disconnected"],connected:["connected","disconnected",v,w,"unreferenced"],unreferenced:["unreferenced",v,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],E=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>(e.find(e=>e.host===t.host&&e.port===t.port)||e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout0&&e.emit(t,n)}r(E,s),Object.assign(E.prototype,f),Object.defineProperty(E.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(E.prototype,"parserType",{enumerable:!0,get:function(){return y.native?"c++":"js"}}),Object.defineProperty(E.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const x=["serverDescriptionChanged","error","close","timeout","parseError"];function A(e,t,n){t=t||{},x.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function N(e){return function(){e.state!==w&&e.state!==v&&(M(e.connectedProxies,e.disconnectedProxies,this),L(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function I(e,t){return function(){if(e.state===w)return L(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===v||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==v&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),D(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==v&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var s=0;s{if(!o)return n(null,s);if(!S(o,r)||!c)return o=g(o),n(o);if(a=k(r,t.session),!a)return n(o);return B(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](s,i,t,l)}E.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));C(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),L(e),t.once("close",I(e,"close")),t.once("timeout",I(e,"timeout")),t.once("parseError",I(e,"parseError")),t.once("error",I(e,"error")),t.once("connect",I(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},E.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},E.prototype.lastIsMaster=function(){return this.ismaster},E.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},E.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,v),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(L(this),C(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),A(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},E.prototype.isConnected=function(){return this.connectedProxies.length>0},E.prototype.isDestroyed=function(){return this.state===w},E.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},E.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},E.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function L(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=p(e.topologyDescription,n),s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",s),e.topologyDescription=n}}E.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var s=this,i=k(s,n.session);if((null==i||!i.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==i)return r(new u("no mongos proxy available"));var a=h(n);a.topology=s;const c=!n.retrying&&n.retryWrites&&n.session&&d(s)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),i.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!S(n,s))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},E.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},E.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},E.prototype.connections=function(){for(var e=[],t=0;t({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},k.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:A(t),compression:{compressors:g(t)}})),H.forEach(e=>{t[e]&&C(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,i=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:t.host+":27017";return e.set(n,new s(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:F,description:new a(n,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),servers:new Map,sessionPool:new x(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Z(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return y.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===q)return void("function"==typeof t&&t());var n,r;$(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=J(n,t);return e.set(t.address,r),e},new Map),h.translate(e);const o=e.readPreference||h.primary,s=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));$(this,q),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},s):this.selectServer(B(o),e,s)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==F&&this.s.state!==z?($(this,z),te(this[Y],new S("Topology closed")),M(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{E(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),$(this,F),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof h?n=e:"string"==typeof e?n=new h(e):(h.translate(t),n=t.readPreference||h.primary),e=B(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,s=o&&o.transaction;if(r&&s&&s.server)return void n(void 0,s.server);let i=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:h.primary;i=B(t)}const a={serverSelector:i,transaction:s,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[V]=!0,a.timer=void 0;const e=new v(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),ne(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return I(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new S(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Z(this,e),this[Y].length>0&&ne(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){Q({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){Q({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){Q({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),h.translate(n);const o=n.readPreference||h.primary;this.selectServer(B(o),n,(o,s)=>{if(o)return void r(o);const i=!n.retrying&&!!n.retryWrites&&n.session&&f(this)&&!n.session.inTransaction()&&(a=t,K.some(e=>a[e]));var a;i&&(n.session.incrementTransactionNumber(),n.willRetryWrite=i),s.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!ee(o))return r(o);if(i){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return h.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===q}isDestroyed(){return this.s.state===F}unref(){console.log("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(0===e.length)return{};return e.filter(e=>e.type!==i.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),j.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function J(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(p(r,e,j),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{R(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Z(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=J(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function Q(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,s=e.ns,i=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&f(r)&&!t.session.inTransaction();r.selectServer(P(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!ee(r))return r=O(r),n(r);if(a){return Q(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](s,i,t,u)})}function ee(e){return e instanceof S&&e.hasErrorLabel("RetryableWriteError")}function te(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[V]||n.callback(t)}}function ne(e){if(e.s.state===F)return void te(e[Y],new S("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(10),o=n(165).ConnectionPool,s=n(61).CMAP_EVENT_NAMES,i=n(2).MongoError,a=n(4).relayEvents,c=n(11).retrieveBSON(),u=n(19),l=n(34).ServerDescription,p=n(34).compareTopologyVersion,h=n(13),f=n(176).Monitor,d=n(2).MongoNetworkError,m=n(2).MongoNetworkTimeoutError,y=n(4).collationNotSupported,g=n(11).debugOptions,b=n(2).isSDAMUnrecoverableError,S=n(2).isRetryableWriteError,v=n(2).isNodeShuttingDownError,w=n(2).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(15),E=T.ServerType,C=n(41).isTransactionCommand,x=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],A=T.STATE_CLOSING,N=T.STATE_CLOSED,I=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[N]:[N,I],[I]:[I,A,k,N],[k]:[k,A,N],[A]:[A,N]}),R=Symbol("monitor");class D extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:N,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new f(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>L(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:B(this.description.roundTripTime,e.duration)})),this.s.state===I&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===N&&(M(this,I),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==N?(M(this,A),this[R].close(),this.s.pool.close(e,e=>{M(this,N),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===A||this.s.state===N)return void r(new i("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof h))return new i("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:g(x,n)})}] against ${this.name}`),y(this,t)?r(new i(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,s)=>{if(r)return L(this,r),s(r);o.command(e,t,n,U(this,o,t,n,s))},r)}query(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.query(e,t,n,r,U(this,s,t,r,i))},o):o(new i("server is closed"))}getMore(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.getMore(e,t,n,r,U(this,s,null,r,i))},o):o(new i("server is closed"))}killCursors(e,t,n){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((n,r,o)=>{if(n)return L(this,n),o(n);r.killCursors(e,t,U(this,r,null,void 0,o))},n):"function"==typeof n&&n(new i("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function B(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,s=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];if(r.s.state===A||r.s.state===N)return void n(new i("server is closed"));if(y(r,t))return void n(new i(`server ${r.name} does not support collation`));!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,i)=>{if(e)return L(r,e),i(e);n[o](s,a,t,U(r,n,a,t,i))},n):n(new i("servers < 3.4 do not support hint on "+o))}function L(e,t){t instanceof d&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function j(e,t){return e&&e.inTransaction()&&!C(t)}function U(e,t,n,r,o){const s=r&&r.session;return function(r,i){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof d?(s&&!s.hasEnded&&(s.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==E.Standalone}(e)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(L(e,r),e.s.pool.clear())):(_(e)<9&&S(r)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return p(r,n)<0}(e,r)&&((_(e)<=7||v(r))&&e.s.pool.clear(),L(e,r),process.nextTick(()=>e.requestCheck())))),o(r,i)}}Object.defineProperty(D.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:D}},function(e,t,n){"use strict";const r=n(77),o=n(10).EventEmitter,s=n(19),i=n(0).makeCounter,a=n(2).MongoError,c=n(105).Connection,u=n(4).eachAsync,l=n(76),p=n(4).relayEvents,h=n(175),f=h.PoolClosedError,d=h.WaitQueueTimeoutError,m=n(61),y=m.ConnectionPoolCreatedEvent,g=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,S=m.ConnectionReadyEvent,v=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,E=m.ConnectionPoolClearedEvent,C=Symbol("logger"),x=Symbol("connections"),A=Symbol("permits"),N=Symbol("minPoolSizeTimer"),I=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),D=Symbol("cancelled"),B=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[I]}function L(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function j(e,t){const n=Object.assign({id:e[k].next().value,generation:e[I]},e.options);e[A]--,l(n,e[M],(n,r)=>{if(n)return e[A]++,e[C].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(p(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new S(e,r)),"function"!=typeof t?(e[x].push(r),z(e)):t(void 0,r))})}function U(e,t,n){e.emit("connectionClosed",new v(e,t,n)),e[A]++,process.nextTick(()=>t.destroy())}function z(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[D]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[x].shift(),r=P(e,n),o=L(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const s=n.closed?"error":r?"stale":"idle";U(e,n,s)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount{const r=e[R].shift();null!=r?r[D]||(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n)):null==t&&e[x].push(n)})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(B).reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[C]=s("ConnectionPool",e),this[x]=new r,this[A]=this.options.maxPoolSize,this[N]=void 0,this[I]=0,this[k]=i(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new y(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;ee(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[I]}get totalConnectionCount(){return this[x].length+(this.options.maxPoolSize-this[A])}get availableConnectionCount(){return this[x].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new f(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[D]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new d(n))},r)),this[R].push(t),z(this)}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[x].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){U(this,e,e.closed?"error":t?"poolClosed":"stale")}z(this)}clear(){this[I]+=1,this.emit("connectionPoolCleared",new E(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[D]||e.callback(new a("connection pool closed"))}this[N]&&clearTimeout(this[N]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[x].toArray(),(t,n)=>{this.emit("connectionClosed",new v(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[x].clear(),this.emit("connectionPoolClosed",new g(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(24).Duplex,o=n(167),s=n(2).MongoParseError,i=n(27).decompress,a=n(22).Response,c=n(35).BinMsg,u=n(2).MongoError,l=n(7).opcodes.OP_COMPRESSED,p=n(7).opcodes.OP_MSG,h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(35).Msg,S=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[S]=new o}_write(e,t,n){this[S].append(e),function e(t,n){const r=t[S];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new s("Invalid message size: "+o));if(o>t.maxBsonMessageSize)return void n(new s(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const f=r.slice(0,o);r.consume(o);const d={length:f.readInt32LE(0),requestId:f.readInt32LE(4),responseTo:f.readInt32LE(8),opCode:f.readInt32LE(12)};let m=d.opCode===p?c:a;const y=t.responseOptions;if(d.opCode!==l){const o=f.slice(h);return t.emit("message",new m(t.bson,f,d,o,y)),void(r.length>=4?e(t,n):n())}d.fromCompressed=!0,d.opCode=f.readInt32LE(h),d.length=f.readInt32LE(h+4);const g=f[h+8],b=f.slice(h+9);m=d.opCode===p?c:a,i(g,b,(o,s)=>{o?n(o):s.length===d.length?(t.emit("message",new m(t.bson,f,d,s,y)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(h),o=n.readInt32LE(12);m({options:t},r,(n,s)=>{if(n)return void t.cb(n,null);const i=Buffer.alloc(h);i.writeInt32LE(h+f+s.length,0),i.writeInt32LE(e.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(d.OP_COMPRESSED,12);const a=Buffer.alloc(f);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(y[t.agreedCompressor],8),this.push(Buffer.concat([i,a,s]))})}}},function(e,t,n){"use strict";var r=n(168).Duplex,o=n(5),s=n(16).Buffer;function i(e){if(!(this instanceof i))return new i(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(i,r),i.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;rthis.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||s.alloc(0);if(r<=0)return e||s.alloc(0);var o,i,a=!!e,c=this._offset(n),u=r-n,l=u,p=a&&t||0,h=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:s.concat(this._bufs,this.length);for(i=0;i(o=this._bufs[i].length-h))){this._bufs[i].copy(e,p,h,h+l),p+=o;break}this._bufs[i].copy(e,p,h),p+=o,l-=o,h&&(h=0)}return e.length>p?e.slice(0,p):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new i;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new i(o)},i.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){for(var e=0,t=new i;ethis.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},i.prototype._match=function(e,t){if(this.length-e0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,s=r.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,n=s,o=a,t.copy(n,o),a+=i.data.length,i=i.next;return s},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=s;var r=n(111),o=Object.create(n(44));function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}o.inherits=n(45),o.inherits(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(34).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(2).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(10),s=n(76),i=n(105).Connection,a=n(15),c=n(4).makeStateMachine,u=n(2).MongoNetworkError,l=n(11).retrieveBSON(),p=n(0).makeInterruptableAsyncInterval,h=n(0).calculateDurationInMs,f=n(0).now,d=n(104),m=d.ServerHeartbeatStartedEvent,y=d.ServerHeartbeatSucceededEvent,g=d.ServerHeartbeatFailedEvent,b=Symbol("server"),S=Symbol("monitorId"),v=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,E=a.STATE_CLOSING,C=c({[E]:[E,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",E],monitoring:["monitoring","idle",E]}),x=new Set([E,T,"monitoring"]);function A(e){return e.s.state===T||e.s.state===E}function N(e){C(e,E),e[S]&&(e[S].stop(),e[S]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[S]&&(clearTimeout(e[S]),e[S]=void 0),e[v]&&e[v].destroy({force:!0})}function I(e){return t=>{function n(){A(e)||C(e,"idle"),t()}C(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),function(e,t){let n=f();function r(r){e[v]&&(e[v].destroy({force:!0}),e[v]=void 0),e.emit("serverHeartbeatFailed",new g(h(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[v]&&!e[v].closed){const s=e.options.connectTimeoutMS,i=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u=c?{ismaster:!0,maxAwaitTimeMS:i,topologyVersion:(o=a,{processId:o.processId,counter:l.Long.fromNumber(o.counter)})}:{ismaster:!0},p=c?{socketTimeout:s+i,exhaustAllowed:!0}:{socketTimeout:s};return c&&null==e[_]&&(e[_]=new k(e[w],e.connectOptions)),void e[v].command("admin.$cmd",u,p,(o,s)=>{if(o)return void r(o);const i=s.result,a=c?e[_].roundTripTime:h(n);e.emit("serverHeartbeatSucceeded",new y(a,i,e.address)),c&&i.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=f()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,i))})}var o;s(e.connectOptions,e[w],(o,s)=>{if(s&&A(e))s.destroy({force:!0});else{if(o)return e[v]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[v]=s,e.emit("serverHeartbeatSucceeded",new y(h(n),s.ismaster,e.address)),t(void 0,s.ismaster)}})}(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{A(e)||e[S].wake()}),n()})}}class k{constructor(e,t){this[v]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[S]=setTimeout(()=>function e(t,n){const r=f(),o=t[w],i=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[v]&&(t[v]=o),t[O]=h(r),t[S]=setTimeout(()=>e(t,n),i))}if(null==t[v])return void s(n,o,(e,n)=>{if(e)return t[v]=void 0,void(t[O]=0);a(n)});t[v].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[v]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[S]),this[S]=void 0,this[v]&&this[v].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[v]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[S]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){x.has(this.s.state)||this[S].wake()}reset(){if(A(this))return;C(this,E),N(this),C(this,"idle");const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t})}close(){A(this)||(C(this,E),N(this),this.emit("close"),C(this,T))}}}},function(e,t,n){"use strict";const r=n(19),o=n(10).EventEmitter,s=n(78);class i{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=i,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return"_mongodb._tcp."+this.srvHost}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new i(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;s.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(15).TopologyType,s=n(13),i=n(2).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function p(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function h(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(h));const f=e.mode;if(f===s.PRIMARY)return n.filter(u);if(f===s.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const d=f===s.NEAREST?p:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,s=(t.heartbeatFrequencyMS+1e4)/1e3;if(r((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(d))));return f===s.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(59),o=n(102),s=n(78),i=n(2).MongoParseError,a=n(13),c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;function u(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}function l(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=l(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>l(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const p=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),f=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),d={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function m(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),p.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!f.has(n))throw new i(`Value for authMechanism must be one of: ${Array.from(f).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new i("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&d[t]?e[d[t]]=n:e[t]=n}const y=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function g(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=b("tls",e,t),r=b("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new i("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new i("Incomplete key value pair for option");const s=e.toLowerCase();m(n,s,l(s,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,console.warn("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function b(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new i(`All values of ${e} must be the same.`)})}return o}const S="mongodb+srv",v=["mongodb",S];function w(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new i("URI malformed, cannot be parsed"))}const a=e.match(c);if(!a)return n(new i("Invalid connection string"));const l=a[1];if(-1===v.indexOf(l))return n(new i("Invalid protocol provided"));const p=a[4].split("?"),h=p.length>0?p[0]:null,f=p.length>1?p[1]:null;let d;try{d=g(f,t)}catch(e){return n(e)}if(d=Object.assign({},d,t),l===S)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new i("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new i("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new i("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new i(`Ports not accepted with '${S}' URIs`));const c=a.host;s.resolveSrv("_mongodb._tcp."+c,(e,l)=>{if(e)return n(e);if(0===l.length)return n(new i("No addresses found at host"));for(let e=0;e`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),s.resolveTxt(c,(e,s)=>{if(e){if("ENODATA"!==e.code)return n(e);s=null}if(s){if(s.length>1)return n(new i("Multiple text records not allowed"));if(s=o.parse(s[0].join("")),Object.keys(s).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new i("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);w(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,d,n);const m={username:null,password:null,db:h&&""!==h?o.unescape(h):null};if(d.auth?(d.auth.username&&(m.username=d.auth.username),d.auth.user&&(m.username=d.auth.user),d.auth.password&&(m.password=d.auth.password)):(d.username&&(m.username=d.username),d.user&&(m.username=d.user),d.password&&(m.password=d.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new i("Unescaped slash in userinfo section"));const b=a[3].split("@");if(b.length>2)return n(new i("Unescaped at-sign in authority section"));if(null==b[0]||""===b[0])return n(new i("No username provided in authority section"));if(b.length>1){const e=b.shift().split(":");if(e.length>2)return n(new i("Unescaped colon in authority section"));if(""===e[0])return n(new i("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let _=null;const O=b.shift().split(",").map(e=>{let t=r.parse("mongodb://"+e);if("/:"===t.path)return _=new i("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(_=new i("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)_=new i("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;_=new i("Invalid port (negative number)")}else _=new i("Invalid port (zero) with hostname")}).filter(e=>!!e);if(_)return n(_);if(0===O.length||""===O[0].host||null===O[0].host)return n(new i("No hostname or hostnames provided in connection string"));if(!!d.directConnection&&1!==O.length)return n(new i("directConnection option requires exactly one host"));null==d.directConnection&&1===O.length&&null==d.replicaSet&&(d.directConnection=!0);const T={hosts:O,auth:m.db||m.username?m:null,options:Object.keys(d).length?d:null};var E;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((E=T.options).tls&&(E.ssl=E.tls),E.tlsInsecure?(E.checkServerIdentity=!1,E.sslValidate=!1):Object.assign(E,{checkServerIdentity:!E.tlsAllowInvalidHostnames,sslValidate:!E.tlsAllowInvalidCertificates}),E.tlsCAFile&&(E.ssl=!0,E.sslCA=E.tlsCAFile),E.tlsCertificateKeyFile&&(E.ssl=!0,E.tlsCertificateFile?(E.sslCert=E.tlsCertificateFile,E.sslKey=E.tlsCertificateKeyFile):(E.sslKey=E.tlsCertificateKeyFile,E.sslCert=E.tlsCertificateKeyFile)),E.tlsCertificateKeyFilePassword&&(E.ssl=!0,E.sslPass=E.tlsCertificateKeyFilePassword),E);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(y.has(r)&&(!e.auth||null==e.auth.username))throw new i(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new i(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=w},function(e,t,n){"use strict";const r=n(10).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(46).buildCountCommand,o=n(0).handleCallback,s=n(1).MongoError,i=Array.prototype.push,a=n(20).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let s,i={};i.skip=n.skip,i.limit=n.limit,i.hint=n.hint,i.maxTimeMS=n.maxTimeMS,i.collectionName=e.namespace.collection;try{s=r(e,e.cmd.query,i)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),s,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw s.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,s.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,s)=>r?o(n,r):null==s?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,s)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((s,a)=>{if(s)return o(t,s);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),i.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(12).buildCountCommand,o=n(3).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let s,i={};i.skip=o.skip,i.limit=o.limit,i.hint=o.hint,i.maxTimeMS=o.maxTimeMS,i.collectionName=t.namespace.collection;try{s=r(t,t.cmd.query,i)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),s,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(63);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern;class c extends s{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,s=this.options,c={distinct:n.collectionName,key:r,query:o};"number"==typeof s.maxTimeMS&&(c.maxTimeMS=s.maxTimeMS),a(c,n,s);try{i(c,n,s)}catch(e){return t(e,null)}super.executeCommand(e,c,(e,n)=>{e?t(e):t(null,this.options.full?n:n.values)})}}o(c,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(115),i=n(0).handleCallback;class a extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return i(e,t,!1);i(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26);class i extends s{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(i,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(3).Aspect,s=n(3).defineAspects,i=n(1).ReadPreference,a=n(4).maxWireVersion,c=n(2).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=i.resolve(e,this.options)}execute(e,t){if(this.server=e,void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}s(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(3).OperationBase,s=n(0).toError;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,s(t),null);r(e,null,n)})}catch(t){e(t)}}}},function(e,t,n){"use strict";const r=n(64);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new=void 0!==r.returnOriginal&&!r.returnOriginal,s.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,s.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(3).OperationBase,i=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(14).executeCommand,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(0).toError;class h extends s{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,s={geoSearch:t.collectionName,near:[n,r]};s=i(s,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(s,t,o),c(t.s.db,s,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,p(n)),u(e,null,n)})}}o(h,r.READ_OPERATION),e.exports=h},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(14).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;s(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(3).OperationBase,s=n(12).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));s(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(117),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(i(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(85).loadDb,p=n(3).OperationBase,h=n(1).ReadPreference,f=n(0).toError,d=["readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];function m(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let s=t.length-1;s>=0;s--)n=t[s],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=m(e[n]);return r}e.exports=class extends p{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options;const p={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?p[e]=m(u[e]):-1===d.indexOf(e)&&(p[e]=u[e]);u=Object.assign({},u),u.readPreference=h.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(p,{db:t.s.db,collection:t},u)):i(p,t,u),!0===u.bypassDocumentValidation&&(p.bypassDocumentValidation=u.bypassDocumentValidation);try{s(p,t,u)}catch(t){return e(t,null)}a(t.s.db,p,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,f(r));const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let s=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;s=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else s=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,s);c(e,n,{collection:s,stats:o})})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback;let s;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,i=(s||(s=n(47)),s);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new i(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).defineAspects,s=n(3).Aspect;class i extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(i,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]),e.exports=i},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(85).loadCollection,c=n(1).MongoError,u=n(1).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class p extends s{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let s=Object.assign({nameOnly:!0,strict:!1},r);function l(s){if(s)return e(s);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(s){e(s)}}s=i(s,{db:t},s);s.strict?t.listCollections({name:n},s).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(p,r.WRITE_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion,a=n(80);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(i(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=e+".";return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}s(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(23),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;enull!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new i("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(15).serverType,a=n(15).ServerType,c=n(1).MongoError;class u extends s{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){i(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),s(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects;class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}s(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateCallback,s=n(12).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,s(t,n,r,i,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!s(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n){if(null==n)return;if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}(t,n,e))}}},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(59),s=n(5).format,i=n(1).Logger,a=n(78),c=n(36);function u(e,t){let n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return!!r.endsWith(o)}function l(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",p=o.parse(e,!0);if((null==p.hostname||""===p.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===p.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(p.port,10))&&parseInt(p.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(p.path&&p.path.length>0&&"/"!==p.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(p.query)for(let e in p.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===p.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(p.auth){let t=p.auth.split(":");if(-1!==e.indexOf(p.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(p.auth)&&-1!==p.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let h=e.split("?").shift().split(","),f=[];for(let e=0;e1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let d,m,y,g,b={},S=a||"",v=S.split(":",2),w=decodeURIComponent(v[0]);if(v[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(v[0]=w,v[1]){let e=decodeURIComponent(v[1]);if(v[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");v[1]=e}2===v.length&&(b.auth={user:v[0],password:v[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},E={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=E,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),y=[{domain_socket:t}]}else{d=n;let e={};y=d.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,E.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,E.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,E.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),E.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),E.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(S);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(S)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");g.zlibCompressionLevel=e,_.compression=g}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:i("URL Parser").warn(n+" is not supported as a connection string option")}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=y,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return l(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let s="_mongodb._tcp."+r.host;a.resolveSrv(s,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e1)return n(new Error("Multiple text records not allowed"));if(!(r=(r=r[0]).length>1?r.join(""):r[0]).includes("authSource")&&!r.includes("replicaSet"))return n(new Error("Text record must only set `authSource` or `replicaSet`"));c.push(r)}c.length&&(i+="?"+c.join("&")),l(i,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(95),r=e.mongodb.MongoTimeoutError,o=n(67),s=o.debug,i=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,i=e._client,a=e._keyVaultNamespace,l=e._keyVaultClient,p=e._mongocryptdClient,h=e._mongocryptdManager;switch(s(`[context#${t.id}] ${u.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(i,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(p,t.ns,o,(s,i)=>{if(s)return s instanceof r&&h&&!h.bypassSpawn?void h.spawn(()=>{this.markCommand(p,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(s,null);t.addMongoOperationResponse(i),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(l,a,r,(r,s)=>{if(r)return n(r,null);s.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c("Unknown state: "+t.state))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],port:r},s=e.message;return new Promise((n,r)=>{const i=t.connect(o,()=>{i.write(s)});i.once("timeout",()=>{i.removeAllListeners(),i.destroy(),r(new c("KMS request timed out"))}),i.once("error",e=>{i.removeAllListeners(),i.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),i.on("data",t=>{e.addResponse(t),e.bytesNeeded<=0&&i.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,s=i(t);e.db(s).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,s=i(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(s).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,s=i(t),c=a(t);n=o.deserialize(n),e.db(s).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67).databaseNamespace,o=e.stateMachine.StateMachine,s=n(221).MongocryptdManager,i=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(129);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new s(n.extraOptions),this._mongocryptdClient=new i(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=n.kmsProviders),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&t.message.match(/timed out after/)?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,s){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==s&&(s=n,n={}),this._bypassEncryption)return void s(void 0,t);const i=this._bson,a=Buffer.isBuffer(t)?t:i.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void s(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t;new o(Object.assign({bson:i},n)).execute(this,c,s)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,s=Buffer.isBuffer(e)?e:r.serialize(e,t);let i;try{i=this._mongocrypt.makeDecryptionContext(s)}catch(e){return void n(e,null)}i.id=this._contextCounter++;new o(Object.assign({bson:r},t)).execute(this,i,n)}}}}},function(e,t,n){var r=n(39).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),s=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);s=s.replace(/^(.+)\|/,"$1:"),"\\"==r&&(s=s.replace(/\//g,"\\"));/^.+\:/.test(s)||(s=r+s);return o+s}},function(e,t,n){"use strict";const r=n(222).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67),o=r.databaseNamespace,s=r.collectionNamespace,i=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(129);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r{u.execute(this,c,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),i=s(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(i).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),s=Object.assign({},t);if(t.keyId&&(s.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError('"options.keyAltName" must be of type string, but was of type '+n);s.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,s);return i(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),s=new a({bson:n});return i(t,e=>{s.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(130),o=n(1).BSON.ObjectID,s=n(1).ReadPreference,i=n(16).Buffer,a=n(40),c=n(5).format,u=n(5),l=n(1).MongoError,p=u.inherits,h=n(24).Duplex,f=n(0).shallowClone,d=n(0).executeLegacyOperation,m=n(5).deprecate;const y=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var g=function e(t,n,i,a,c){if(y(),!(this instanceof e))return new e(t,n,i,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=i,i=void 0):"object"==typeof a&&(c=a,a=i,i=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=i):void 0===i?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=i),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||s.primary,this.writeConcern=z(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};g.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return d(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=z(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=f(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};g.prototype.eof=function(){return this.position===this.length},g.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,S,[this,e,t],{skipSessions:!0})};var S=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?I(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};g.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return d(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},g.prototype.stream=function(){return new F(this)},g.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},d(this.db.s.topology,j,[this,e,t,n,r],{skipSessions:!0})},g.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},g.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},d(this.db.s.topology,v,[this,e,t,n],{skipSessions:!0})};var v=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,s){if(e)return o(e,n);var c=0,u=0,l=function(){var e=i.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,i,p){if(e)return o(e,n);c+=i,new r(n,{n:u++},n.writeConcern).write(p.slice(0,i),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+i,n.currentChunk=r,c>=s.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};g.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate||(e.uploadDate=new Date),N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};g.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},g.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};g.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},g.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},d(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var c=e.currentChunk.readSlice(s-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===s&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,I(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};g.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},g.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},d(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var s=null==n?g.IO_SEEK_SET:n,i=t,a=0;a=s===g.IO_SEEK_CUR?e.position+i:s===g.IO_SEEK_END?e.length+i:i;var c=Math.floor(a/e.chunkSize);I(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},x=function(e,t,n){var s=e.collection(),i=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}i=null==e.fileId&&null==e.filename?null:i,t.readPreference=e.readPreference,null!=i?s.findOne(i,t,(function(s,i){if(s)return a(s);if(null!=i)e.fileId=i._id,e.filename="r"===e.mode||void 0===e.filename?i.filename:e.filename,e.contentType=i.contentType,e.internalChunkSize=i.chunkSize,e.uploadDate=i.uploadDate,e.aliases=i.aliases,e.length=i.length,e.metadata=i.metadata,e.internalMd5=i.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?I(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&i?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var s="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),s?e.close((function(t){o(t,e)})):o(null,e);for(var i=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),p=t.slice(a),h=[e.currentChunk.write(u)];p.length>=e.chunkSize;){var f=new r(e,{n:i+1},e.writeConcern);u=p.slice(0,e.chunkSize),p=p.slice(e.chunkSize),i+=1,f.write(u),h.push(f)}e.currentChunk=new r(e,{n:i+1},e.writeConcern),p.length>0&&e.currentChunk.write(p),e.position=e.position+t.length;for(var d=h.length,m=0;m=t.length?s("offset larger than size of file",null):n&&n>t.length?s("length is larger than the size of the file",null):r&&n&&r+n>t.length?s("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return s(e);t.read(n,s)})):t.read(n,s))}))};g.readlines=function(e,t,n,r,o){var s=Array.prototype.slice.call(arguments,2);return o="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=(r=s.length?s.shift():null)||{},d(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var s=null==n?"\n":n;new g(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};g.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},d(e.s.topology,L,[this,e,t,n,r],{skipSessions:!0})};var L=function(e,t,n,r,o){var s=z(t,r);if(n.constructor===Array)for(var i=0,a=0;ae.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var s={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)},p.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,f,[this,e,t,n],{skipSessions:!0})},p.prototype.drop=function(e){return u(this.s.db.s.topology,d,[this,e],{skipSessions:!0})},p.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(24),o=n(5);function s(e,t,n,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:s,readPreference:n},r.Readable.call(this)}function i(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=s,o.inherits(s,r.Readable),s.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end0&&(s.n={$gte:i})}e.s.cursor=e.s.chunks.find(s).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,s=Math.min(e.s.file.chunkSize,r);if(n.n>o){var i="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(i))}if(n.n0;){var d=o.length-s;if(o.copy(e.bufToStore,e.pos,d,d+c),e.pos+=c,0===(i-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++p,y(e,r))return!1;e.chunks.insertOne(m,f(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--p||(e.emit("drain",m),r&&r(),h(e))})),i=e.chunkSizeBytes,e.pos=0,++e.n}s-=c,c=Math.min(i,s)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),y(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):d(this,(function(){m(r)})))}},function(e,t,n){var r,o; /*! * is.js 0.8.0 * Author: Aras Atasaygin @@ -14,16 +14,16 @@ * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. - */const r=Symbol.prototype.valueOf,o=n(128);e.exports=function(e,t){switch(o(e)){case"array":return e.slice();case"object":return Object.assign({},e);case"date":return new e.constructor(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return function(e){const t=e.length,n=Buffer.allocUnsafe?Buffer.allocUnsafe(t):Buffer.from(t);return e.copy(n),n}(e);case"symbol":return function(e){return r?Object(r.call(e)):{}}(e);case"arraybuffer":return function(e){const t=new e.constructor(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}(e);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return function(e,t){return new e.constructor(e.buffer,e.byteOffset,e.length)}(e);case"regexp":return function(e){const t=void 0!==e.flags?e.flags:/\w+$/.exec(e)||void 0,n=new e.constructor(e.source,t);return n.lastIndex=e.lastIndex,n}(e);case"error":return Object.create(e);default:return e}}},function(e,t,n){"use strict"; + */const r=Symbol.prototype.valueOf,o=n(131);e.exports=function(e,t){switch(o(e)){case"array":return e.slice();case"object":return Object.assign({},e);case"date":return new e.constructor(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return function(e){const t=e.length,n=Buffer.allocUnsafe?Buffer.allocUnsafe(t):Buffer.from(t);return e.copy(n),n}(e);case"symbol":return function(e){return r?Object(r.call(e)):{}}(e);case"arraybuffer":return function(e){const t=new e.constructor(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}(e);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return function(e,t){return new e.constructor(e.buffer,e.byteOffset,e.length)}(e);case"regexp":return function(e){const t=void 0!==e.flags?e.flags:/\w+$/.exec(e)||void 0,n=new e.constructor(e.source,t);return n.lastIndex=e.lastIndex,n}(e);case"error":return Object.create(e);default:return e}}},function(e,t,n){"use strict"; /*! * is-plain-object * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. - */var r=n(231);function o(e){return!0===r(e)&&"[object Object]"===Object.prototype.toString.call(e)}e.exports=function(e){var t,n;return!1!==o(e)&&("function"==typeof(t=e.constructor)&&(!1!==o(n=t.prototype)&&!1!==n.hasOwnProperty("isPrototypeOf")))}},function(e,t,n){"use strict"; + */var r=n(232);function o(e){return!0===r(e)&&"[object Object]"===Object.prototype.toString.call(e)}e.exports=function(e){var t,n;return!1!==o(e)&&("function"==typeof(t=e.constructor)&&(!1!==o(n=t.prototype)&&!1!==n.hasOwnProperty("isPrototypeOf")))}},function(e,t,n){"use strict"; /*! * isobject * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. - */e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},function(e,t,n){"use strict";e.exports=(e,t)=>{let n;return function r(){const o=Math.floor(Math.random()*(t-e+1)+e);return n=o===n&&e!==t?r():o,n}}},function(e,t,n){"use strict";n.r(t);var r=n(16),o=n(5),s=n(129),i=()=>"undefined"==typeof window;class a extends Error{}class c extends a{constructor(e,t){super(`${e}${t=t?": "+t:""}`)}}class u extends c{constructor(e){super(u.name,e)}}class l extends c{constructor(e){super(l.name,e||"data upsert failed")}}function p(e=!1){const t={NODE_ENV:"development",MONGODB_URI:"mongodb://127.0.0.1:27017/hscc-api-airports".toString(),MONGODB_MS_PORT:parseInt(null!=="6666"?"6666":"-Infinity"),DISABLED_API_VERSIONS:[],FLIGHTS_GENERATE_DAYS:parseInt(null!=="1"?"1":"-Infinity"),AIRPORT_NUM_OF_GATE_LETTERS:parseInt(null!=="4"?"4":"-Infinity"),AIRPORT_GATE_NUMBERS_PER_LETTER:parseInt(null!=="20"?"20":"-Infinity"),AIRPORT_PAIR_USED_PERCENT:parseInt(null!=="75"?"75":"-Infinity"),FLIGHT_HOUR_HAS_FLIGHTS_PERCENT:parseInt(null!=="66"?"66":"-Infinity"),RESULTS_PER_PAGE:parseInt(null!=="100"?"100":"-Infinity"),IGNORE_RATE_LIMITS:!1,LOCKOUT_ALL_KEYS:!1,DISALLOWED_METHODS:[],REQUESTS_PER_CONTRIVED_ERROR:parseInt(null!=="10"?"10":"-Infinity"),MAX_CONTENT_LENGTH_BYTES:Object(s.parse)("100kb"),HYDRATE_DB_ON_STARTUP:!Object(o.isUndefined)("true")&&!0,DEBUG_MODE:/--debug|--inspect/.test(process.execArgv.join(" "))},n=e=>i()?[e]:[],r=[t.FLIGHTS_GENERATE_DAYS,t.AIRPORT_NUM_OF_GATE_LETTERS,t.AIRPORT_GATE_NUMBERS_PER_LETTER,...n(t.AIRPORT_PAIR_USED_PERCENT),...n(t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT),t.RESULTS_PER_PAGE,t.REQUESTS_PER_CONTRIVED_ERROR,t.MAX_CONTENT_LENGTH_BYTES];e&&"development"==t.NODE_ENV&&console.info("debug - "+t);if("unknown"==t.NODE_ENV||i()&&""===t.MONGODB_URI||r.some(e=>!Object(o.isNumber)(e)||e<0))throw new a("illegal environment detected, check environment variables");if(t.RESULTS_PER_PAGE<_)throw new a("RESULTS_PER_PAGE must be >= "+_);if(t.AIRPORT_NUM_OF_GATE_LETTERS>26)throw new a("AIRPORT_NUM_OF_GATE_LETTERS must be <= 26");if(i()&&t.AIRPORT_PAIR_USED_PERCENT>100)throw new a("AIRPORT_PAIR_USED_PERCENT must between 0 and 100");if(i()&&t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT>100)throw new a("FLIGHT_HOUR_HAS_FLIGHTS_PERCENT must between 0 and 100");if(i()&&t.MONGODB_MS_PORT&&t.MONGODB_MS_PORT<=1024)throw new a("optional environment variable MONGODB_MS_PORT must be > 1024");return t}let h=null;async function f(){return h=h||(await r.MongoClient.connect(p().MONGODB_URI,{useUnifiedTopology:!0})).db(),h}n(83);var d=n(66),m=n(84),y=n.n(m),g=n(7),b=n.n(g),S=n(130),v=n.n(S),w=n(19);const _=15,O=["type","airline","comingFrom","landingAt","departingTo","flightNumber","ffms","seats.economy.priceDollars","_id"],T=["departFromSender","arriveAtReceiver","departFromReceiver","status","gate"];console.log((async function(e=!1){var t,n;const o=await f(),s=await o.collection("airports").find().toArray(),i=await o.collection("airlines").find().toArray(),c=await o.collection("info").find().next(),h=o.collection("flights");if(s.length<2||i.length<2)throw new l("cannot generate flights without at least two airports and airlines");let m=b()(1024,2097151);const g=Object(w.pseudoRandomBytes)(5).toString("hex"),S=24*p().FLIGHTS_GENERATE_DAYS*60*60*1e3,_=()=>b()(1,100),O=e=>36e5*Math.floor(e/36e5),T=e=>{const t=(Math.floor(e/1e3).toString(16)+g+(++m).toString(16)).padEnd(24,"0");return new r.ObjectId(t)},E=await h.deleteMany({_id:{$lt:T(Date.now()-6048e5)}});!e&&console.info(`api - Deleted ${E.deletedCount} flights older than 7 days`);const C=O((null!==(t=null===(n=await h.find().sort({_id:-1}).limit(1).next())||void 0===n?void 0:n._id)&&void 0!==t?t:new r.ObjectId).getTimestamp().getTime()),x=(O(Date.now()+S)-C)/36e5;if(!e&&console.info(`api - Generating ${x} hours worth of flights...`),!x)return 0;const A=[...Array(9999)].map((e,t)=>t+1),N="abcdefghijklmnopqrstuvwxyz".split("").slice(0,p().AIRPORT_NUM_OF_GATE_LETTERS).map(e=>[...Array(p().AIRPORT_GATE_NUMBERS_PER_LETTER)].map((t,n)=>`${e}${n+1}`)).flat(),I=[];let k=!1;[...Array(x)].forEach((t,n)=>{if(_()>p().FLIGHT_HOUR_HAS_FLIGHTS_PERCENT)return;const r=C+36e5+36e5*n,o=Object(d.shuffle)(i).slice(0,b()(2,i.length)),a=o.reduce((e,t)=>({...e,[t._id.toHexString()]:v()(y()(A))}),{});!e&&console.info(`api ↳ Generating flights for hour ${r} (${n+1}/${x})`),s.forEach(e=>{const t=Object(d.shuffle)(y()(N)),n=e=>t.push(e),i=()=>{const e=t.shift();if(!e)throw new u("ran out of gates");return e},l=[];s.forEach(t=>{e._id.equals(t._id)||_()>p().AIRPORT_PAIR_USED_PERCENT||o.forEach(n=>{k=!k;const o=b()(0,10),i=b()(0,4),u={};let p=b()(60,150),h=b()(5e3,8e3);const f=[...Array(c.seatClasses.length)].map(e=>b()(10,100/c.seatClasses.length)).sort((e,t)=>t-e);f[0]+=100-f.reduce((e,t)=>e+t,0);for(const[e,t]of Object.entries(c.seatClasses))p=b()(p,2*p)+Number(Math.random().toFixed(2)),h=b()(h,2*h),u[t]={total:f[Number(e)],priceDollars:p,priceFfms:h};const m={};let y=1,g=b()(10,150);for(const e of c.allExtras)_()>75||(y=b()(y,2.5*y)+Number(Math.random().toFixed(2)),g=b()(g,2*g),m[e]={priceDollars:y,priceFfms:g});l.push({_id:T(r),bookerKey:k?null:e.chapterKey,type:k?"arrival":"departure",airline:n.name,comingFrom:k?t.shortName:Object(d.shuffle)(s).filter(t=>t.shortName!=e.shortName)[0].shortName,landingAt:e.shortName,departingTo:k?null:t.shortName,flightNumber:n.codePrefix+a[n._id.toHexString()]().toString(),baggage:{checked:{max:o,prices:[...Array(o)].reduce(e=>{const t=e.slice(-1)[0];return[...e,b()(t||0,2*(t||35))]},[])},carry:{max:i,prices:[...Array(i)].reduce(e=>{const t=e.slice(-1)[0];return[...e,b()(t||0,2*(t||15))]},[])}},ffms:b()(2e3,6e3),seats:u,extras:m})})});const h=e=>{if(!e.stochasticStates)throw new u("expected stochastic state to exist");return Object.values(e.stochasticStates).slice(-1)[0]};l.forEach(e=>{let t=0,n=!1;const o="arrival"==e.type,s=b()(r,r+36e5-(o?96e4:186e4));e.stochasticStates={0:{arriveAtReceiver:s,departFromSender:s-b()(72e5,18e6),departFromReceiver:o?null:s+9e5,status:"scheduled",gate:null}};for(let r=1;!n&&r<3;++r){const o={...h(e)};switch(r){case 1:t=o.departFromSender,_()>80?(o.status="cancelled",n=!0):o.status="on time",e.stochasticStates[t.toString()]=o;break;case 2:_()>75&&(t=b()(o.arriveAtReceiver-72e5,o.departFromSender+9e5),o.status="delayed",o.arriveAtReceiver+=b()(3e5,9e5),o.departFromReceiver&&(o.departFromReceiver+=b()(3e5,9e5)),e.stochasticStates[t.toString()]=o);break;default:throw new u("unreachable stage encountered (1)")}}}),l.forEach(e=>{if(!e.stochasticStates)throw new u("stage 3 encountered impossible condition");const t=h(e);"cancelled"!=t.status&&(e.stochasticStates[b()(t.arriveAtReceiver-72e5,t.arriveAtReceiver-9e5).toString()]={...t,gate:i()})}),l.forEach(e=>{if(!e.stochasticStates)throw new u("stage 4 encountered impossible condition");const t=h(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new u("gate was not predetermined?!");_()>50&&(n(r),r=i()),e.stochasticStates[b()(t.arriveAtReceiver-18e5,t.arriveAtReceiver-3e5).toString()]={...t,gate:r,status:"landed"}}),l.forEach(e=>{if(!e.stochasticStates)throw new u("stage 5 encountered impossible condition");const t=h(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new u("gate was not predetermined?!");_()>85&&(n(r),r=i()),e.stochasticStates[t.arriveAtReceiver]={...t,gate:r,status:"arrived"}}),l.forEach(e=>{if(!e.stochasticStates)throw new u("stage 6-9 encountered impossible condition");const t=h(e);if("cancelled"==t.status)return;let n=0,o=!1;const s="arrival"==e.type;for(let i=6;!o&&i<10;++i){const a={...t};switch(i){case 6:if(!s)continue;n=r+36e5,a.status="past",a.gate=null,o=!0;break;case 7:if(s)throw new u("arrival type encountered in departure-only model");n=a.arriveAtReceiver+b()(18e4,6e5),a.status="boarding";break;case 8:if(!a.departFromReceiver)throw new u("illegal departure state encountered in model (1)");n=a.departFromReceiver,a.status="departed";break;case 9:if(!a.departFromReceiver)throw new u("illegal departure state encountered in model (2)");n=a.departFromReceiver+b()(72e5,18e6),a.status="past",a.gate=null;break;default:throw new u("unreachable stage encountered (2)")}e.stochasticStates[n.toString()]=a}}),I.push(...l)})});try{if(!I.length)return 0;!e&&console.info(`api - Committing ${I.length} flights into database...`);const t=await h.insertMany(I);if(!t.result.ok)throw new l("flight insertion failed");if(t.insertedCount!=I.length)throw new u("assert failed: operation.insertedCount != totalHoursToGenerate");return!e&&console.info("api - Operation completed successfully!"),t.insertedCount}catch(e){throw e instanceof a?e:new l(e)}}))}]); \ No newline at end of file + */e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},function(e,t,n){"use strict";e.exports=(e,t)=>{let n;return function r(){const o=Math.floor(Math.random()*(t-e+1)+e);return n=o===n&&e!==t?r():o,n}}},,,function(e,t,n){"use strict";n.r(t);var r=n(18),o=n(69);console.log(o.b),console.log(r.a)}]); \ No newline at end of file diff --git a/external-scripts/bin/prune-logs.js b/external-scripts/bin/prune-logs.js index 6915e92..61a1132 100644 --- a/external-scripts/bin/prune-logs.js +++ b/external-scripts/bin/prune-logs.js @@ -1 +1,29 @@ -!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=132)}({132:function(e,t){console.log("6666")}}); \ No newline at end of file +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=235)}([function(e,t,n){"use strict";const r=n(2).MongoError,o=n(29);var s=t.formatSortValue=function(e){switch((""+e).toLowerCase()){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new Error("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}},i=t.formattedOrderClause=function(e){var t={};if(null==e)return null;if(Array.isArray(e)){if(0===e.length)return null;for(var n=0;nprocess.emitWarning(e,"DeprecationWarning"):e=>console.error(e);function l(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}const p={};try{n(92),p.ASYNC_ITERATOR=!0}catch(e){p.ASYNC_ITERATOR=!1}class h{constructor(e,t){this.db=e,this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new h(this.db,e)}static fromString(e){if(!e)throw new Error(`Cannot parse namespace from "${e}"`);const t=e.indexOf(".");return new h(e.substring(0,t),e.substring(t+1))}}function f(){const e=process.hrtime();return Math.floor(1e3*e[0]+e[1]/1e6)}e.exports={filterOptions:function(e,t){var n={};for(var r in e)-1!==t.indexOf(r)&&(n[r]=e[r]);return n},mergeOptions:function(e,t){for(var n in t)e[n]=t[n];return e},translateOptions:function(e,t){var n={sslCA:"ca",sslCRL:"crl",sslValidate:"rejectUnauthorized",sslKey:"key",sslCert:"cert",sslPass:"passphrase",socketTimeoutMS:"socketTimeout",connectTimeoutMS:"connectionTimeout",replicaSet:"setName",rs_name:"setName",secondaryAcceptableLatencyMS:"acceptableLatency",connectWithNoPrimary:"secondaryOnlyConnectionAllowed",acceptableLatencyMS:"localThresholdMS"};for(var r in t)n[r]?e[n[r]]=t[r]:e[r]=t[r];return e},shallowClone:function(e){var t={};for(var n in e)t[n]=e[n];return t},getSingleProperty:function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},checkCollectionName:function(e){if("string"!=typeof e)throw new r("collection name must be a String");if(!e||-1!==e.indexOf(".."))throw new r("collection names cannot be empty");if(-1!==e.indexOf("$")&&null==e.match(/((^\$cmd)|(oplog\.\$main))/))throw new r("collection names must not contain '$'");if(null!=e.match(/^\.|\.$/))throw new r("collection names must not start or end with '.'");if(-1!==e.indexOf("\0"))throw new r("collection names cannot contain a null character")},toError:function(e){if(e instanceof Error)return e;for(var t=e.err||e.errmsg||e.errMessage||e,n=r.create({message:t,driver:!0}),o="object"==typeof e?Object.keys(e):[],s=0;s{if(null==e)throw new TypeError("This method requires a valid topology instance");if(!Array.isArray(n))throw new TypeError("This method requires an array of arguments to apply");o=o||{};const s=e.s.promiseLibrary;let i,a,c,u=n[n.length-1];if(!o.skipSessions&&e.hasSessionSupport())if(a=n[n.length-2],null==a||null==a.session){c=Symbol(),i=e.startSession({owner:c});const t=n.length-2;n[t]=Object.assign({},n[t],{session:i})}else if(a.session&&a.session.hasEnded)throw new r("Use of expired sessions is not permitted");const l=(e,t)=>function(n,r){if(i&&i.owner===c&&!o.returnsCursor)i.endSession(()=>{if(delete a.session,n)return t(n);e(r)});else{if(n)return t(n);e(r)}};if("function"==typeof u){u=n.pop();const e=l(e=>u(null,e),e=>u(e,null));n.push(e);try{return t.apply(null,n)}catch(t){throw e(t),t}}if(null!=n[n.length-1])throw new TypeError("final argument to `executeLegacyOperation` must be a callback");return new s((function(e,r){const o=l(e,r);n[n.length-1]=o;try{return t.apply(null,n)}catch(e){o(e)}}))},applyRetryableWrites:function(e,t){return t&&t.s.options.retryWrites&&(e.retryWrites=!0),e},applyWriteConcern:function(e,t,n){n=n||{};const r=t.db,s=t.collection;if(n.session&&n.session.inTransaction())return e.writeConcern&&delete e.writeConcern,e;const i=o.fromOptions(n);return i?Object.assign(e,{writeConcern:i}):s&&s.writeConcern?Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)}):r&&r.writeConcern?Object.assign(e,{writeConcern:Object.assign({},r.writeConcern)}):e},isPromiseLike:function(e){return e&&"function"==typeof e.then},decorateWithCollation:function(e,t,n){const o=t.s&&t.s.topology||t.topology;if(!o)throw new TypeError('parameter "target" is missing a topology');const s=o.capabilities();if(n.collation&&"object"==typeof n.collation){if(!s||!s.commandsTakeCollation)throw new r("Current topology does not support collation");e.collation=n.collation}},decorateWithReadConcern:function(e,t,n){if(n&&n.session&&n.session.inTransaction())return;let r=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(r,t.s.readConcern),Object.keys(r).length>0&&Object.assign(e,{readConcern:r})},deprecateOptions:function(e,t){if(!0===process.noDeprecation)return t;const n=e.msgHandler?e.msgHandler:l,r=new Set;function o(){const o=arguments[e.optionsIndex];return a(o)&&0!==Object.keys(o).length?(e.deprecatedOptions.forEach(t=>{if(o.hasOwnProperty(t)&&!r.has(t)){r.add(t);const o=n(e.name,t);if(u(o),this&&this.getLogger){const e=this.getLogger();e&&e.warn(o)}}}),t.apply(this,arguments)):t.apply(this,arguments)}return Object.setPrototypeOf(o,t),t.prototype&&(o.prototype=t.prototype),o},SUPPORTS:p,MongoDBNamespace:h,emitDeprecationWarning:u,makeCounter:function*(e){let t=e||0;for(;;){const e=t;t+=1,yield e}},maybePromise:function(e,t,n){const r=e&&e.s&&e.s.promiseLibrary||Promise;let o;return"function"!=typeof t&&(o=new r((e,n)=>{t=(t,r)=>{if(t)return n(t);e(r)}})),n((function(e,n){if(null==e)t(e,n);else try{t(e)}catch(e){return process.nextTick(()=>{throw e})}})),o},now:f,calculateDurationInMs:function(e){if("number"!=typeof e)throw TypeError("numeric value required to calculate duration");const t=f()-e;return t<0?0:t},makeInterruptableAsyncInterval:function(e,t){let n,r,o,s=!1;const i=(t=t||{}).interval||1e3,a=t.minInterval||500;function c(e){s||(clearTimeout(n),n=setTimeout(u,e||i))}function u(){o=0,r=f(),e(e=>{if(e)throw e;c(i)})}return"boolean"==typeof t.immediate&&t.immediate?u():(r=f(),c()),{wake:function(){const e=f(),t=e-o,n=e-r,s=Math.max(i-n,0);o=e,ta&&c(a)},stop:function(){s=!0,n&&(clearTimeout(n),n=null),r=0,o=0}}},hasAtomicOperators:function e(t){if(Array.isArray(t))return t.reduce((t,n)=>t||e(n),null);const n=Object.keys(t);return n.length>0&&"$"===n[0][0]}}},function(e,t,n){"use strict";let r=n(88);const o=n(72),s=n(4).retrieveEJSON();try{const e=o("bson-ext");e&&(r=e)}catch(e){}e.exports={MongoError:n(2).MongoError,MongoNetworkError:n(2).MongoNetworkError,MongoParseError:n(2).MongoParseError,MongoTimeoutError:n(2).MongoTimeoutError,MongoServerSelectionError:n(2).MongoServerSelectionError,MongoWriteConcernError:n(2).MongoWriteConcernError,Connection:n(90),Server:n(75),ReplSet:n(160),Mongos:n(162),Logger:n(19),Cursor:n(20).CoreCursor,ReadPreference:n(13),Sessions:n(31),BSON:r,EJSON:s,Topology:n(163).Topology,Query:n(22).Query,MongoCredentials:n(101).MongoCredentials,defaultAuthProviders:n(96).defaultAuthProviders,MongoCR:n(97),X509:n(98),Plain:n(99),GSSAPI:n(100),ScramSHA1:n(58).ScramSHA1,ScramSHA256:n(58).ScramSHA256,parseConnectionString:n(179)}},function(e,t,n){"use strict";const r=Symbol("errorLabels");class o extends Error{constructor(e){if(e instanceof Error)super(e.message),this.stack=e.stack;else{if("string"==typeof e)super(e);else for(var t in super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels&&(this[r]=new Set(e.errorLabels)),e)"errorLabels"!==t&&"errmsg"!==t&&(this[t]=e[t]);Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new o(e)}hasErrorLabel(e){return null!=this[r]&&this[r].has(e)}addErrorLabel(e){null==this[r]&&(this[r]=new Set),this[r].add(e)}get errorLabels(){return this[r]?Array.from(this[r]):[]}}const s=Symbol("beforeHandshake");class i extends o{constructor(e,t){super(e),this.name="MongoNetworkError",t&&!0===t.beforeHandshake&&(this[s]=!0)}}class a extends o{constructor(e){super(e),this.name="MongoParseError"}}class c extends o{constructor(e,t){t&&t.error?super(t.error.message||t.error):super(e),this.name="MongoTimeoutError",t&&(this.reason=t)}}class u extends o{constructor(e,t){super(e),this.name="MongoWriteConcernError",t&&Array.isArray(t.errorLabels)&&(this[r]=new Set(t.errorLabels)),null!=t&&(this.result=function(e){const t=Object.assign({},e);return 0===t.ok&&(t.ok=1,delete t.errmsg,delete t.code,delete t.codeName),t}(t))}}const l=new Set([6,7,89,91,189,9001,10107,11600,11602,13435,13436]),p=new Set([11600,11602,10107,13435,13436,189,91,7,6,89,9001,262]);const h=new Set([91,189,11600,11602,13436]),f=new Set([10107,13435]),d=new Set([11600,91]);function m(e){return!(!e.code||!h.has(e.code))||(e.message.match(/not master or secondary/)||e.message.match(/node is recovering/))}e.exports={MongoError:o,MongoNetworkError:i,MongoNetworkTimeoutError:class extends i{constructor(e,t){super(e,t),this.name="MongoNetworkTimeoutError"}},MongoParseError:a,MongoTimeoutError:c,MongoServerSelectionError:class extends c{constructor(e,t){super(e,t),this.name="MongoServerSelectionError"}},MongoWriteConcernError:u,isRetryableError:function(e){return l.has(e.code)||e instanceof i||e.message.match(/not master/)||e.message.match(/node is recovering/)},isSDAMUnrecoverableError:function(e){return e instanceof a||null==e||!!(m(e)||(t=e,t.code&&f.has(t.code)||!m(t)&&t.message.match(/not master/)));var t},isNodeShuttingDownError:function(e){return e.code&&d.has(e.code)},isRetryableWriteError:function(e){return e instanceof u?p.has(e.code)||p.has(e.result.code):p.has(e.code)},isNetworkErrorBeforeHandshake:function(e){return!0===e[s]}}},function(e,t,n){"use strict";const r={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXECUTE_WITH_SELECTION:Symbol("EXECUTE_WITH_SELECTION"),NO_INHERIT_OPTIONS:Symbol("NO_INHERIT_OPTIONS")};e.exports={Aspect:r,defineAspects:function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t},OperationBase:class{constructor(e){this.options=Object.assign({},e)}hasAspect(e){return null!=this.constructor.aspects&&this.constructor.aspects.has(e)}set session(e){Object.assign(this.options,{session:e})}get session(){return this.options.session}clearSession(){delete this.options.session}get canRetryRead(){return!0}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}}},function(e,t,n){"use strict";const r=n(143),o=n(21),s=n(72);const i=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function a(e){if(e){if(e.ismaster)return e.ismaster.maxWireVersion;if("function"==typeof e.lastIsMaster){const t=e.lastIsMaster();if(t)return t.maxWireVersion}if(e.description)return e.description.maxWireVersion}return 0}e.exports={uuidV4:()=>{const e=o.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},relayEvents:function(e,t,n){n.forEach(n=>e.on(n,e=>t.emit(n,e)))},collationNotSupported:function(e,t){return t&&t.collation&&a(e)<5},retrieveEJSON:function(){let e=null;try{e=s("mongodb-extjson")}catch(e){}return e||(e={parse:i,deserialize:i,serialize:i,stringify:i,setBSONModule:i,BSON:i}),e},retrieveKerberos:function(){let e;try{e=s("kerberos")}catch(e){if("MODULE_NOT_FOUND"===e.code)throw new Error("The `kerberos` module was not found. Please install it and try again.");throw e}return e},maxWireVersion:a,isPromiseLike:function(e){return e&&"function"==typeof e.then},eachAsync:function(e,t,n){e=e||[];let r=0,o=0;for(r=0;re===t[n]))},tagsStrictEqual:function(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>t[n]===e[n])},errorStrictEqual:function(e,t){return e===t||!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message)},makeStateMachine:function(e){return function(t,n){const r=e[t.s.state];if(r&&r.indexOf(n)<0)throw new TypeError(`illegal state transition from [${t.s.state}] => [${n}], allowed: [${r}]`);t.emit("stateChanged",t.s.state,n),t.s.state=n}},makeClientMetadata:function(e){e=e||{};const t={driver:{name:"nodejs",version:n(144).version},os:{type:r.type(),name:process.platform,architecture:process.arch,version:r.release()},platform:`'Node.js ${process.version}, ${r.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo&&(e.driverInfo.name&&(t.driver.name=`${t.driver.name}|${e.driverInfo.name}`),e.driverInfo.version&&(t.version=`${t.driver.version}|${e.driverInfo.version}`),e.driverInfo.platform&&(t.platform=`${t.platform}|${e.driverInfo.platform}`)),e.appname){const n=Buffer.from(e.appname);t.application={name:n.length>128?n.slice(0,128).toString("utf8"):e.appname}}return t},noop:()=>{}}},function(e,t){e.exports=require("util")},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"d",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"a",(function(){return c})),n.d(t,"f",(function(){return u}));class r extends Error{}class o extends r{constructor(e,t){super(`${e}${t=t?": "+t:""}`)}}class s extends o{constructor(e){super(s.name,e)}}class i extends o{constructor(e){super(i.name,e||"data upsert failed")}}class a extends o{constructor(e){super(a.name,e?`expected valid ObjectId instance, got "${e}" instead`:"invalid ObjectId encountered")}}class c extends o{constructor(){super(c.name,"invalid API key encountered")}}class u extends o{constructor(e){super(u.name,null!=e?e:"validation failed")}}},function(e,t,n){"use strict";const r=n(13),o=n(2).MongoError,s=n(15).ServerType,i=n(91).TopologyDescription;e.exports={getReadPreference:function(e,t){var n=e.readPreference||new r("primary");if(t.readPreference&&(n=t.readPreference),"string"==typeof n&&(n=new r(n)),!(n instanceof r))throw new o("read preference must be a ReadPreference instance");return n},MESSAGE_HEADER_SIZE:16,COMPRESSION_DETAILS_SIZE:9,opcodes:{OP_REPLY:1,OP_UPDATE:2001,OP_INSERT:2002,OP_QUERY:2004,OP_GETMORE:2005,OP_DELETE:2006,OP_KILL_CURSORS:2007,OP_COMPRESSED:2012,OP_MSG:2013},parseHeader:function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}},applyCommonQueryOptions:function(e,t){return Object.assign(e,{raw:"boolean"==typeof t.raw&&t.raw,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,monitoring:"boolean"==typeof t.monitoring&&t.monitoring,fullResult:"boolean"==typeof t.fullResult&&t.fullResult}),"number"==typeof t.socketTimeout&&(e.socketTimeout=t.socketTimeout),t.session&&(e.session=t.session),"string"==typeof t.documentsReturnedIn&&(e.documentsReturnedIn=t.documentsReturnedIn),e},isSharded:function(e){if("mongos"===e.type)return!0;if(e.description&&e.description.type===s.Mongos)return!0;if(e.description&&e.description instanceof i){return Array.from(e.description.servers.values()).some(e=>e.type===s.Mongos)}return!1},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")}}},function(e,t,n){"use strict";e.exports=(e,t)=>{if(void 0===t&&(t=e,e=0),"number"!=typeof e||"number"!=typeof t)throw new TypeError("Expected all arguments to be numbers");return Math.floor(Math.random()*(t-e+1)+e)}},function(e,t,n){"use strict";const r=n(13),o=n(15).TopologyType,s=n(2).MongoError,i=n(2).isRetryableWriteError,a=n(4).maxWireVersion,c=n(2).MongoNetworkError;function u(e,t,n){e.listeners(t).length>0&&e.emit(t,n)}var l=function(e){return e.s.serverDescription||(e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),e.s.serverDescription},p=function(e,t){e.listeners("serverDescriptionChanged").length>0&&(e.emit("serverDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:l(e),newDescription:t}),e.s.serverDescription=t)},h=function(e){return e.s.topologyDescription||(e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}),e.s.topologyDescription},f=function(e,t){return t||(t=e.ismaster),t?t.ismaster&&"isdbgrid"===t.msg?"Mongos":t.ismaster&&!t.hosts?"Standalone":t.ismaster?"RSPrimary":t.secondary?"RSSecondary":t.arbiterOnly?"RSArbiter":"Unknown":"Unknown"},d=function(e){return function(t){if("destroyed"!==e.s.state){var n=(new Date).getTime();u(e,"serverHeartbeatStarted",{connectionId:e.name}),e.command("admin.$cmd",{ismaster:!0},{monitoring:!0},(function(r,o){if(r)u(e,"serverHeartbeatFailed",{durationMS:s,failure:r,connectionId:e.name});else{e.emit("ismaster",o,e);var s=(new Date).getTime()-n;u(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name}),function(e,t,n){var r=f(e,t);return f(e,n)!==r}(e,e.s.ismaster,o.result)&&p(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:e.s.inTopology?f(e):"Standalone"}),e.s.ismaster=o.result,e.s.isMasterLatencyMS=s}if("function"==typeof t)return t(r,o);e.s.inquireServerStateTimeout=setTimeout(d(e),e.s.haInterval)}))}}};const m={endSessions:function(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:r.primaryPreferred},()=>{"function"==typeof t&&t()})}};function y(e){return e.description?e.description.type:"mongos"===e.type?o.Sharded:"replset"===e.type?o.ReplicaSetWithPrimary:o.Single}const g=function(e){return!(e.lastIsMaster().maxWireVersion<6)&&(!!e.logicalSessionTimeoutMinutes&&y(e)!==o.Single)},b="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";e.exports={SessionMixins:m,resolveClusterTime:function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},inquireServerState:d,getTopologyType:f,emitServerDescriptionChanged:p,emitTopologyDescriptionChanged:function(e,t){e.listeners("topologyDescriptionChanged").length>0&&(e.emit("topologyDescriptionChanged",{topologyId:-1!==e.s.topologyId?e.s.topologyId:e.id,address:e.name,previousDescription:h(e),newDescription:t}),e.s.serverDescription=t)},cloneOptions:function(e){var t={};for(var n in e)t[n]=e[n];return t},createCompressionInfo:function(e){return e.compression&&e.compression.compressors?(e.compression.compressors.forEach((function(e){if("snappy"!==e&&"zlib"!==e)throw new Error("compressors must be at least one of snappy or zlib")})),e.compression.compressors):[]},clone:function(e){return JSON.parse(JSON.stringify(e))},diff:function(e,t){var n={servers:[]};e||(e={servers:[]});for(var r=0;r{n&&(clearTimeout(n),n=!1,e())};this.start=function(){return this.isRunning()||(n=setTimeout(r,t)),this},this.stop=function(){return clearTimeout(n),n=!1,this},this.isRunning=function(){return!1!==n}},isRetryableWritesSupported:g,getMMAPError:function(e){return 20===e.code&&e.errmsg.includes("Transaction numbers")?new s({message:b,errmsg:b,originalError:e}):e},topologyType:y,legacyIsRetryableWriteError:function(e,t){return e instanceof s&&(g(t)&&(e instanceof c||a(t)<9&&i(e))&&e.addErrorLabel("RetryableWriteError"),e.hasErrorLabel("RetryableWriteError"))}}},function(e,t){e.exports=require("events")},function(e,t,n){"use strict";const r=n(72);function o(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}e.exports={debugOptions:function(e,t){var n={};return e.forEach((function(e){n[e]=t[e]})),n},retrieveBSON:function(){var e=n(88);e.native=!1;try{var t=r("bson-ext");if(t)return t.native=!0,t}catch(e){}return e},retrieveSnappy:function(){var e=null;try{e=r("snappy")}catch(e){}return e||(e={compress:o,uncompress:o,compressSync:o,uncompressSync:o}),e}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).MongoError,p=n(1).ReadPreference,h=n(0).toError,f=n(20).CursorState;function d(e,t,n){const r="boolean"==typeof n.forceServerObjectId?n.forceServerObjectId:e.s.db.options.forceServerObjectId;return!0===r?t:t.map(t=>(!0!==r&&null==t._id&&(t._id=e.s.pkFactory.createPk()),t))}e.exports={buildCountCommand:function(e,t,n){const r=n.skip,o=n.limit;let a=n.hint;const c=n.maxTimeMS;t=t||{};const u={count:n.collectionName,query:t};return e.s.numberOfRetries?(e.options.hint?a=e.options.hint:e.cmd.hint&&(a=e.cmd.hint),s(u,e,e.cmd)):s(u,e,n),"number"==typeof r&&(u.skip=r),"number"==typeof o&&(u.limit=o),"number"==typeof c&&(u.maxTimeMS=c),a&&(u.hint=a),i(u,e),u},deleteCallback:function(e,t,n){if(null!=n){if(e&&n)return n(e);if(null==t)return n(null,{result:{ok:1}});t.deletedCount=t.result.n,n&&n(null,t)}},findAndModify:function(e,t,n,i,l,h){const f={findAndModify:e.collectionName,query:t};(n=c(n))&&(f.sort=n),f.new=!!l.new,f.remove=!!l.remove,f.upsert=!!l.upsert;const d=l.projection||l.fields;d&&(f.fields=d),l.arrayFilters&&(f.arrayFilters=l.arrayFilters,delete l.arrayFilters),i&&!l.remove&&(f.update=i),l.maxTimeMS&&(f.maxTimeMS=l.maxTimeMS),l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions,l.checkKeys=!1;let m=Object.assign({},l);m=r(m,e.s.db),m=o(m,{db:e.s.db,collection:e},l),m.writeConcern&&(f.writeConcern=m.writeConcern),!0===m.bypassDocumentValidation&&(f.bypassDocumentValidation=m.bypassDocumentValidation),m.readPreference=p.primary;try{s(f,e,m)}catch(e){return h(e,null)}a(e.s.db,f,m,(e,t)=>e?u(h,e,null):u(h,null,t))},indexInformation:function(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new l("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(h(e)):Array.isArray(t)?o?u(r,null,t):void u(r,null,function(e){let t={};for(let n=0;n{if(e.s.state=f.OPEN,n)return u(t,n);u(t,null,r)})},prepareDocs:d,insertDocuments:function(e,t,n,s){"function"==typeof n&&(s=n,n={}),n=n||{},t=Array.isArray(t)?t:[t];let i=Object.assign({},n);i=r(i,e.s.db),i=o(i,{db:e.s.db,collection:e},n),!0===i.keepGoing&&(i.ordered=!1),i.serializeFunctions=n.serializeFunctions||e.s.serializeFunctions,t=d(e,t,n),e.s.topology.insert(e.s.namespace,t,i,(e,n)=>{if(null!=s){if(e)return u(s,e);if(null==n)return u(s,null,null);if(n.result.code)return u(s,h(n.result));if(n.result.writeErrors)return u(s,h(n.result.writeErrors[0]));n.ops=t,u(s,null,n)}})},removeDocuments:function(e,t,n,i){"function"==typeof n?(i=n,n={}):"function"==typeof t&&(i=t,n={},t={}),n=n||{};let a=Object.assign({},n);a=r(a,e.s.db),a=o(a,{db:e.s.db,collection:e},n),null==t&&(t={});const c={q:t,limit:0};n.single?c.limit=1:a.retryWrites&&(a.retryWrites=!1),n.hint&&(c.hint=n.hint);try{s(a,e,n)}catch(e){return i(e,null)}e.s.topology.remove(e.s.namespace,[c],a,(e,t)=>{if(null!=i)return e?u(i,e,null):null==t?u(i,null,null):t.result.code?u(i,h(t.result)):t.result.writeErrors?u(i,h(t.result.writeErrors[0])):void u(i,null,t)})},updateDocuments:function(e,t,n,i,a){if("function"==typeof i&&(a=i,i=null),null==i&&(i={}),"function"!=typeof a&&(a=null),null==t||"object"!=typeof t)return a(h("selector must be a valid JavaScript object"));if(null==n||"object"!=typeof n)return a(h("document must be a valid JavaScript object"));let c=Object.assign({},i);c=r(c,e.s.db),c=o(c,{db:e.s.db,collection:e},i),c.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const l={q:t,u:n};l.upsert=void 0!==i.upsert&&!!i.upsert,l.multi=void 0!==i.multi&&!!i.multi,i.hint&&(l.hint=i.hint),c.arrayFilters&&(l.arrayFilters=c.arrayFilters,delete c.arrayFilters),c.retryWrites&&l.multi&&(c.retryWrites=!1);try{s(c,e,i)}catch(e){return a(e,null)}e.s.topology.update(e.s.namespace,[l],c,(e,t)=>{if(null!=a)return e?u(a,e,null):null==t?u(a,null,null):t.result.code?u(a,h(t.result)):t.result.writeErrors?u(a,h(t.result.writeErrors[0])):void u(a,null,t)})},updateCallback:function(e,t,n){if(null!=n){if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}}}},function(e,t,n){"use strict";const r=function(e,t,n){if(!r.isValid(e))throw new TypeError("Invalid read preference mode "+e);if(t&&!Array.isArray(t)){console.warn("ReadPreference tags must be an array, this will change in the next major version");const e=void 0!==t.maxStalenessSeconds,r=void 0!==t.hedge;e||r?(n=t,t=void 0):t=[t]}if(this.mode=e,this.tags=t,this.hedge=n&&n.hedge,null!=(n=n||{}).maxStalenessSeconds){if(n.maxStalenessSeconds<=0)throw new TypeError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=n.maxStalenessSeconds,this.minWireVersion=5}if(this.mode===r.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new TypeError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new TypeError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new TypeError("Primary read preference cannot be combined with hedge")}};Object.defineProperty(r.prototype,"preference",{enumerable:!0,get:function(){return this.mode}}),r.PRIMARY="primary",r.PRIMARY_PREFERRED="primaryPreferred",r.SECONDARY="secondary",r.SECONDARY_PREFERRED="secondaryPreferred",r.NEAREST="nearest";const o=[r.PRIMARY,r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST,null];r.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const n=e.readPreferenceTags,o=e.maxStalenessSeconds;if("string"==typeof t)return new r(t,n);if(!(t instanceof r)&&"object"==typeof t){const e=t.mode||t.preference;if(e&&"string"==typeof e)return new r(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||o,hedge:t.hedge})}return t},r.resolve=function(e,t){const n=(t=t||{}).session,o=e&&e.readPreference;let s;return s=t.readPreference?r.fromOptions(t):n&&n.inTransaction()&&n.transaction.options.readPreference?n.transaction.options.readPreference:null!=o?o:r.primary,"string"==typeof s?new r(s):s},r.translate=function(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new r(t);else if(!t||t instanceof r||"object"!=typeof t){if(!(t instanceof r))throw new TypeError("Invalid read preference: "+t)}else{const n=t.mode||t.preference;n&&"string"==typeof n&&(e.readPreference=new r(n,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e},r.isValid=function(e){return-1!==o.indexOf(e)},r.prototype.isValid=function(e){return r.isValid("string"==typeof e?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];r.prototype.slaveOk=function(){return-1!==s.indexOf(this.mode)},r.prototype.equals=function(e){return e.mode===this.mode},r.prototype.toJSON=function(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e},r.primary=new r("primary"),r.primaryPreferred=new r("primaryPreferred"),r.secondary=new r("secondary"),r.secondaryPreferred=new r("secondaryPreferred"),r.nearest=new r("nearest"),e.exports=r},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).debugOptions,i=n(0).handleCallback,a=n(1).MongoError,c=n(0).parseIndexOptions,u=n(1).ReadPreference,l=n(0).toError,p=n(80),h=n(0).MongoDBNamespace,f=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function d(e,t,n,o,s){let h=Object.assign({},{readPreference:u.PRIMARY},o);if(h=r(h,{db:e},o),h.writeConcern&&"function"!=typeof s)throw a.create({message:"Cannot use a writeConcern without a provided callback",driver:!0});if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));!function(e,t,n,o,s){const p=c(n),h="string"==typeof o.name?o.name:p.name,f=[{name:h,key:p.fieldHash}],d=Object.keys(f[0]).concat(["writeConcern","w","wtimeout","j","fsync","readPreference","session"]);for(let e in o)-1===d.indexOf(e)&&(f[0][e]=o[e]);const y=e.s.topology.capabilities();if(f[0].collation&&y&&!y.commandsTakeCollation){const e=new a("server/primary/mongos does not support collation");return e.code=67,s(e)}const g=r({createIndexes:t,indexes:f},{db:e},o);o.readPreference=u.PRIMARY,m(e,g,o,(e,t)=>e?i(s,e,null):0===t.ok?i(s,l(t),null):void i(s,null,h))}(e,t,n,h,(r,c)=>{if(null==r)return i(s,r,c);if(67===r.code||11e3===r.code||85===r.code||86===r.code||11600===r.code||197===r.code)return i(s,r,c);const u=g(e,t,n,o);h.checkKeys=!1,e.s.topology.insert(e.s.namespace.withCollection(p.SYSTEM_INDEX_COLLECTION),u,h,(e,t)=>{if(null!=s)return e?i(s,e):null==t?i(s,null,null):t.result.writeErrors?i(s,a.create(t.result.writeErrors[0]),null):void i(s,null,u.name)})})}function m(e,t,n,r){if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));const o=n.dbName||n.authdb||e.databaseName;n.readPreference=u.resolve(e,n),e.s.logger.isDebug()&&e.s.logger.debug(`executing command ${JSON.stringify(t)} against ${o}.$cmd with options [${JSON.stringify(s(f,n))}]`),e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,n,(e,t)=>e?i(r,e):n.full?i(r,null,t):void i(r,null,t.result))}function y(e,t,n,r){const o=null!=n.full&&n.full;if(e.serverConfig&&e.serverConfig.isDestroyed())return r(new a("topology was destroyed"));e.collection(t).listIndexes(n).toArray((e,t)=>e?r(l(e)):Array.isArray(t)?o?i(r,null,t):void i(r,null,function(e){let t={};for(let n=0;n0){n.emit(t,r,e);for(let n=0;n{if(null!=r&&26!==r.code)return i(s,r,null);if(null!=a&&a[l]){if("function"==typeof s)return i(s,null,l)}else d(e,t,n,o,s)})},evaluate:function(e,t,n,r,s){let c=t,l=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return s(new a("topology was destroyed"));c&&"Code"===c._bsontype||(c=new o(c)),null==n||Array.isArray(n)||"function"==typeof n?null!=n&&Array.isArray(n)&&"function"!=typeof n&&(l=n):l=[n];let p={$eval:c,args:l};r.nolock&&(p.nolock=r.nolock),r.readPreference=new u(u.PRIMARY),m(e,p,r,(e,t)=>e?i(s,e,null):t&&1===t.ok?i(s,null,t.retval):t?i(s,a.create({message:"eval failed: "+t.errmsg,driver:!0}),null):void i(s,e,t))},executeCommand:m,executeDbAdminCommand:function(e,t,n,r){const o=new h("admin","$cmd");e.s.topology.command(o,t,n,(t,n)=>e.serverConfig&&e.serverConfig.isDestroyed()?r(new a("topology was destroyed")):t?i(r,t):void i(r,null,n.result))},indexInformation:y,profilingInfo:function(e,t,n){try{e.collection("system.profile").find({},t).toArray(n)}catch(e){return n(e,null)}},validateDatabaseName:function(e){if("string"!=typeof e)throw a.create({message:"database name must be a string",driver:!0});if(0===e.length)throw a.create({message:"database name cannot be the empty string",driver:!0});if("$external"===e)return;const t=[" ",".","$","/","\\"];for(let n=0;n"undefined"==typeof window,i=n(69),a=n(6);function c(e=!1){const t={NODE_ENV:"development",MONGODB_URI:"mongodb://127.0.0.1:27017/hscc-api-airports".toString(),MONGODB_MS_PORT:parseInt(null!=="6666"?"6666":"-Infinity"),DISABLED_API_VERSIONS:[],FLIGHTS_GENERATE_DAYS:parseInt(null!=="1"?"1":"-Infinity"),AIRPORT_NUM_OF_GATE_LETTERS:parseInt(null!=="4"?"4":"-Infinity"),AIRPORT_GATE_NUMBERS_PER_LETTER:parseInt(null!=="20"?"20":"-Infinity"),AIRPORT_PAIR_USED_PERCENT:parseInt(null!=="75"?"75":"-Infinity"),FLIGHT_HOUR_HAS_FLIGHTS_PERCENT:parseInt(null!=="66"?"66":"-Infinity"),RESULTS_PER_PAGE:parseInt(null!=="100"?"100":"-Infinity"),IGNORE_RATE_LIMITS:!1,LOCKOUT_ALL_KEYS:!1,DISALLOWED_METHODS:[],REQUESTS_PER_CONTRIVED_ERROR:parseInt(null!=="10"?"10":"-Infinity"),MAX_CONTENT_LENGTH_BYTES:Object(o.parse)("100kb"),HYDRATE_DB_ON_STARTUP:!Object(r.isUndefined)("true")&&!0,DEBUG_MODE:/--debug|--inspect/.test(process.execArgv.join(" "))},n=e=>s()?[e]:[],c=[t.FLIGHTS_GENERATE_DAYS,t.AIRPORT_NUM_OF_GATE_LETTERS,t.AIRPORT_GATE_NUMBERS_PER_LETTER,...n(t.AIRPORT_PAIR_USED_PERCENT),...n(t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT),t.RESULTS_PER_PAGE,t.REQUESTS_PER_CONTRIVED_ERROR,t.MAX_CONTENT_LENGTH_BYTES];e&&"development"==t.NODE_ENV&&console.info("debug - "+t);if("unknown"==t.NODE_ENV||s()&&""===t.MONGODB_URI||c.some(e=>!Object(r.isNumber)(e)||e<0))throw new a.b("illegal environment detected, check environment variables");if(t.RESULTS_PER_PAGE= "+i.a);if(t.AIRPORT_NUM_OF_GATE_LETTERS>26)throw new a.b("AIRPORT_NUM_OF_GATE_LETTERS must be <= 26");if(s()&&t.AIRPORT_PAIR_USED_PERCENT>100)throw new a.b("AIRPORT_PAIR_USED_PERCENT must between 0 and 100");if(s()&&t.FLIGHT_HOUR_HAS_FLIGHTS_PERCENT>100)throw new a.b("FLIGHT_HOUR_HAS_FLIGHTS_PERCENT must between 0 and 100");if(s()&&t.MONGODB_MS_PORT&&t.MONGODB_MS_PORT<=1024)throw new a.b("optional environment variable MONGODB_MS_PORT must be > 1024");return t}},function(e,t,n){"use strict";var r=n(5).format,o=n(2).MongoError,s={},i={},a=null,c=process.pid,u=null,l=function(e,t){if(!(this instanceof l))return new l(e,t);t=t||{},this.className=e,t.logger?u=t.logger:null==u&&(u=console.log),t.loggerLevel&&(a=t.loggerLevel||"error"),null==i[this.className]&&(s[this.className]=!0)};l.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","DEBUG",this.className,c,n,e),a={type:"debug",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","WARN",this.className,c,n,e),a={type:"warn",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","INFO",this.className,c,n,e),a={type:"info",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||0===Object.keys(i).length&&s[this.className])){var n=(new Date).getTime(),o=r("[%s-%s:%s] %s %s","ERROR",this.className,c,n,e),a={type:"error",message:e,className:this.className,pid:c,date:n};t&&(a.meta=t),u(o,a)}},l.prototype.isInfo=function(){return"info"===a||"debug"===a},l.prototype.isError=function(){return"error"===a||"info"===a||"debug"===a},l.prototype.isWarn=function(){return"error"===a||"warn"===a||"info"===a||"debug"===a},l.prototype.isDebug=function(){return"debug"===a},l.reset=function(){a="error",i={}},l.currentLogger=function(){return u},l.setCurrentLogger=function(e){if("function"!=typeof e)throw new o("current logger must be a function");u=e},l.filter=function(e,t){"class"===e&&Array.isArray(t)&&(i={},t.forEach((function(e){i[e]=!0})))},l.setLevel=function(e){if("info"!==e&&"error"!==e&&"debug"!==e&&"warn"!==e)throw new Error(r("%s is an illegal logging level",e));a=e},e.exports=l},function(e,t,n){"use strict";const r=n(19),o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(4).collationNotSupported,c=n(13),u=n(4).isUnifiedTopology,l=n(43),p=n(24).Readable,h=n(0).SUPPORTS,f=n(0).MongoDBNamespace,d=n(3).OperationBase,m=o().Long,y={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function g(e,t,n){try{e(t,n)}catch(t){process.nextTick((function(){throw t}))}}class b extends p{constructor(e,t,n,o){super({objectMode:!0}),o=o||{},t instanceof d&&(this.operation=t,t=this.operation.ns.toString(),o=this.operation.options,n=this.operation.cmd?this.operation.cmd:{}),this.pool=null,this.server=null,this.disconnectHandler=o.disconnectHandler,this.bson=e.s.bson,this.ns=t,this.namespace=f.fromString(t),this.cmd=n,this.options=o,this.topology=e,this.cursorState={cursorId:null,cmd:n,documents:o.documents||[],cursorIndex:0,dead:!1,killed:!1,init:!1,notified:!1,limit:o.limit||n.limit||0,skip:o.skip||n.skip||0,batchSize:o.batchSize||n.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||n&&n.raw},"object"==typeof o.session&&(this.cursorState.session=o.session);const s=e.s.options;"boolean"==typeof s.promoteLongs?this.cursorState.promoteLongs=s.promoteLongs:"boolean"==typeof o.promoteLongs&&(this.cursorState.promoteLongs=o.promoteLongs),"boolean"==typeof s.promoteValues?this.cursorState.promoteValues=s.promoteValues:"boolean"==typeof o.promoteValues&&(this.cursorState.promoteValues=o.promoteValues),"boolean"==typeof s.promoteBuffers?this.cursorState.promoteBuffers=s.promoteBuffers:"boolean"==typeof o.promoteBuffers&&(this.cursorState.promoteBuffers=o.promoteBuffers),s.reconnect&&(this.cursorState.reconnect=s.reconnect),this.logger=r("Cursor",s),"number"==typeof n?(this.cursorState.cursorId=m.fromNumber(n),this.cursorState.lastCursorId=this.cursorState.cursorId):n instanceof m&&(this.cursorState.cursorId=n,this.cursorState.lastCursorId=n),this.operation&&(this.operation.cursorState=this.cursorState)}setCursorBatchSize(e){this.cursorState.batchSize=e}cursorBatchSize(){return this.cursorState.batchSize}setCursorLimit(e){this.cursorState.limit=e}cursorLimit(){return this.cursorState.limit}setCursorSkip(e){this.cursorState.skip=e}cursorSkip(){return this.cursorState.skip}_next(e){!function e(t,n){if(t.cursorState.notified)return n(new Error("cursor is exhausted"));if(function(e,t){if(e.cursorState.killed)return v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&!e.cursorState.killed)return e.cursorState.killed=!0,v(e,t),!0;return!1}(t,n))return;if(function(e,t){if(e.cursorState.dead&&e.cursorState.killed)return g(t,new s("cursor is dead")),!0;return!1}(t,n))return;if(!t.cursorState.init){if(!t.topology.isConnected(t.options)){if("server"===t.topology._type&&!t.topology.s.options.reconnect)return n(new s("no connection available"));if(null!=t.disconnectHandler)return t.topology.isDestroyed()?n(new s("Topology was destroyed")):void t.disconnectHandler.addObjectAndMethod("cursor",t,"next",[n],n)}return void t._initializeCursor((r,o)=>{r||null===o?n(r,o):e(t,n)})}if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);if(t.cursorState.cursorIndex!==t.cursorState.documents.length||m.ZERO.equals(t.cursorState.cursorId)){if(t.cursorState.documents.length===t.cursorState.cursorIndex&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId))return g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData}));if(t.cursorState.documents.length===t.cursorState.cursorIndex&&m.ZERO.equals(t.cursorState.cursorId))S(t,n);else{if(t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit)return t.kill(),S(t,n);t.cursorState.currentLimit+=1;let e=t.cursorState.documents[t.cursorState.cursorIndex++];if(!e||e.$err)return t.kill(),S(t,(function(){g(n,new s(e?e.$err:void 0))}));t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.doc&&(e=t.cursorState.transforms.doc(e)),g(n,null,e)}}else{if(t.cursorState.documents=[],t.cursorState.cursorIndex=0,t.topology.isDestroyed())return n(new i("connection destroyed, not possible to instantiate cursor"));if(function(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=!0;const n=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);return w(e,()=>t(n)),!0}return!1}(t,n))return;t._getMore((function(r,o,i){return r?g(n,r):(t.connection=i,0===t.cursorState.documents.length&&t.cmd.tailable&&m.ZERO.equals(t.cursorState.cursorId)?g(n,new s({message:"No more documents in tailed cursor",tailable:t.cmd.tailable,awaitData:t.cmd.awaitData})):0===t.cursorState.documents.length&&t.cmd.tailable&&!m.ZERO.equals(t.cursorState.cursorId)?e(t,n):t.cursorState.limit>0&&t.cursorState.currentLimit>=t.cursorState.limit?S(t,n):void e(t,n))}))}}(this,e)}clone(){return this.topology.cursor(this.ns,this.cmd,this.options)}isDead(){return!0===this.cursorState.dead}isKilled(){return!0===this.cursorState.killed}isNotified(){return!0===this.cursorState.notified}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex,n=e0&&this.cursorState.currentLimit+r.length>this.cursorState.limit&&(r=r.slice(0,this.cursorState.limit-this.cursorState.currentLimit),this.kill()),this.cursorState.currentLimit=this.cursorState.currentLimit+r.length,this.cursorState.cursorIndex=this.cursorState.cursorIndex+r.length,r}kill(e){this.cursorState.dead=!0,this.cursorState.killed=!0,this.cursorState.documents=[],null==this.cursorState.cursorId||this.cursorState.cursorId.isZero()||!1===this.cursorState.init?e&&e(null,null):this.server.killCursors(this.ns,this.cursorState,e)}rewind(){this.cursorState.init&&(this.cursorState.dead||this.kill(),this.cursorState.currentLimit=0,this.cursorState.init=!1,this.cursorState.dead=!1,this.cursorState.killed=!1,this.cursorState.notified=!1,this.cursorState.documents=[],this.cursorState.cursorId=null,this.cursorState.cursorIndex=0)}_read(){if(this.s&&this.s.state===y.CLOSED||this.isDead())return this.push(null);this._next((e,t)=>e?(this.listeners("error")&&this.listeners("error").length>0&&this.emit("error",e),this.isDead()||this.close(),this.emit("end"),this.emit("finish")):this.cursorState.streamOptions&&"function"==typeof this.cursorState.streamOptions.transform&&null!=t?this.push(this.cursorState.streamOptions.transform(t)):(this.push(t),void(null===t&&this.isDead()&&this.once("end",()=>{this.close(),this.emit("finish")}))))}_endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=this.cursorState.session;return n&&(e.force||n.owner===this)?(this.cursorState.session=void 0,this.operation&&this.operation.clearSession(),n.endSession(t),!0):(t&&t(),!1)}_getMore(e){this.logger.isDebug()&&this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`);let t=this.cursorState.batchSize;this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit&&(t=this.cursorState.limit-this.cursorState.currentLimit);const n=this.cursorState;this.server.getMore(this.ns,n,t,this.options,(t,r,o)=>{(t||n.cursorId&&n.cursorId.isZero())&&this._endSession(),e(t,r,o)})}_initializeCursor(e){const t=this;if(u(t.topology)&&t.topology.shouldCheckForSessionSupport())return void t.topology.selectServer(c.primaryPreferred,t=>{t?e(t):this._initializeCursor(e)});function n(n,r){const o=t.cursorState;if((n||o.cursorId&&o.cursorId.isZero())&&t._endSession(),0===o.documents.length&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData)return v(t,e);e(n,r)}const r=(e,r)=>{if(e)return n(e);const o=r.message;if(Array.isArray(o.documents)&&1===o.documents.length){const e=o.documents[0];if(o.queryFailure)return n(new s(e),null);if(!t.cmd.find||t.cmd.find&&!1===t.cmd.virtual){if(e.$err||e.errmsg)return n(new s(e),null);if(null!=e.cursor&&"string"!=typeof e.cursor){const r=e.cursor.id;return e.cursor.ns&&(t.ns=e.cursor.ns),t.cursorState.cursorId="number"==typeof r?m.fromNumber(r):r,t.cursorState.lastCursorId=t.cursorState.cursorId,t.cursorState.operationTime=e.operationTime,Array.isArray(e.cursor.firstBatch)&&(t.cursorState.documents=e.cursor.firstBatch),n(null,o)}}}const i=o.cursorId||0;t.cursorState.cursorId=i instanceof m?i:m.fromNumber(i),t.cursorState.documents=o.documents,t.cursorState.lastCursorId=o.cursorId,t.cursorState.transforms&&"function"==typeof t.cursorState.transforms.query&&(t.cursorState.documents=t.cursorState.transforms.query(o)),n(null,o)};if(t.operation)return t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),void l(t.topology,t.operation,(e,o)=>{if(e)n(e);else{if(t.server=t.operation.server,t.cursorState.init=!0,null!=t.cursorState.cursorId)return n();r(e,o)}});const o={};return t.cursorState.session&&(o.session=t.cursorState.session),t.operation?o.readPreference=t.operation.readPreference:t.options.readPreference&&(o.readPreference=t.options.readPreference),t.topology.selectServer(o,(o,i)=>{if(o){const n=t.disconnectHandler;return null!=n?n.addObjectAndMethod("cursor",t,"next",[e],e):e(o)}if(t.server=i,t.cursorState.init=!0,a(t.server,t.cmd))return e(new s(`server ${t.server.name} does not support collation`));if(null!=t.cursorState.cursorId)return n();if(t.logger.isDebug()&&t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`),null!=t.cmd.find)return void i.query(t.ns,t.cmd,t.cursorState,t.options,r);const c=Object.assign({session:t.cursorState.session},t.options);i.command(t.ns,t.cmd,c,r)})}}function S(e,t){e.cursorState.dead=!0,v(e,t)}function v(e,t){w(e,()=>g(t,null,null))}function w(e,t){if(e.cursorState.notified=!0,e.cursorState.documents=[],e.cursorState.cursorIndex=0,!e.cursorState.session)return t();e._endSession(t)}h.ASYNC_ITERATOR&&(b.prototype[Symbol.asyncIterator]=n(92).asyncIterator),e.exports={CursorState:y,CoreCursor:b}},function(e,t){e.exports=require("crypto")},function(e,t,n){"use strict";var r=(0,n(11).retrieveBSON)().Long;const o=n(16).Buffer;var s=0,i=n(7).opcodes,a=function(e,t,n,r){if(null==t)throw new Error("ns must be specified for query");if(null==n)throw new Error("query must be specified for query");if(-1!==t.indexOf("\0"))throw new Error("namespace cannot contain a null character");this.bson=e,this.ns=t,this.query=n,this.numberToSkip=r.numberToSkip||0,this.numberToReturn=r.numberToReturn||0,this.returnFieldSelector=r.returnFieldSelector||null,this.requestId=a.getRequestId(),this.pre32Limit=r.pre32Limit,this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.maxBsonSize=r.maxBsonSize||16777216,this.checkKeys="boolean"!=typeof r.checkKeys||r.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.slaveOk="boolean"==typeof r.slaveOk&&r.slaveOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1};a.prototype.incRequestId=function(){this.requestId=s++},a.nextRequestId=function(){return s+1},a.prototype.toBin=function(){var e=[],t=null,n=0;this.tailable&&(n|=2),this.slaveOk&&(n|=4),this.oplogReplay&&(n|=8),this.noCursorTimeout&&(n|=16),this.awaitData&&(n|=32),this.exhaust&&(n|=64),this.partial&&(n|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);var r=o.alloc(20+o.byteLength(this.ns)+1+4+4);e.push(r);var s=this.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=this.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));var a=r.length+s.length+(t?t.length:0),c=4;return r[3]=a>>24&255,r[2]=a>>16&255,r[1]=a>>8&255,r[0]=255&a,r[c+3]=this.requestId>>24&255,r[c+2]=this.requestId>>16&255,r[c+1]=this.requestId>>8&255,r[c]=255&this.requestId,r[(c+=4)+3]=0,r[c+2]=0,r[c+1]=0,r[c]=0,r[(c+=4)+3]=i.OP_QUERY>>24&255,r[c+2]=i.OP_QUERY>>16&255,r[c+1]=i.OP_QUERY>>8&255,r[c]=255&i.OP_QUERY,r[(c+=4)+3]=n>>24&255,r[c+2]=n>>16&255,r[c+1]=n>>8&255,r[c]=255&n,c=(c+=4)+r.write(this.ns,c,"utf8")+1,r[c-1]=0,r[c+3]=this.numberToSkip>>24&255,r[c+2]=this.numberToSkip>>16&255,r[c+1]=this.numberToSkip>>8&255,r[c]=255&this.numberToSkip,r[(c+=4)+3]=this.numberToReturn>>24&255,r[c+2]=this.numberToReturn>>16&255,r[c+1]=this.numberToReturn>>8&255,r[c]=255&this.numberToReturn,c+=4,e},a.getRequestId=function(){return++s};var c=function(e,t,n,r){r=r||{},this.numberToReturn=r.numberToReturn||0,this.requestId=s++,this.bson=e,this.ns=t,this.cursorId=n};c.prototype.toBin=function(){var e=4+o.byteLength(this.ns)+1+4+8+16,t=0,n=o.alloc(e);return n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_GETMORE>>24&255,n[t+2]=i.OP_GETMORE>>16&255,n[t+1]=i.OP_GETMORE>>8&255,n[t]=255&i.OP_GETMORE,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,t=(t+=4)+n.write(this.ns,t,"utf8")+1,n[t-1]=0,n[t+3]=this.numberToReturn>>24&255,n[t+2]=this.numberToReturn>>16&255,n[t+1]=this.numberToReturn>>8&255,n[t]=255&this.numberToReturn,n[(t+=4)+3]=this.cursorId.getLowBits()>>24&255,n[t+2]=this.cursorId.getLowBits()>>16&255,n[t+1]=this.cursorId.getLowBits()>>8&255,n[t]=255&this.cursorId.getLowBits(),n[(t+=4)+3]=this.cursorId.getHighBits()>>24&255,n[t+2]=this.cursorId.getHighBits()>>16&255,n[t+1]=this.cursorId.getHighBits()>>8&255,n[t]=255&this.cursorId.getHighBits(),t+=4,n};var u=function(e,t,n){this.ns=t,this.requestId=s++,this.cursorIds=n};u.prototype.toBin=function(){var e=24+8*this.cursorIds.length,t=0,n=o.alloc(e);n[t+3]=e>>24&255,n[t+2]=e>>16&255,n[t+1]=e>>8&255,n[t]=255&e,n[(t+=4)+3]=this.requestId>>24&255,n[t+2]=this.requestId>>16&255,n[t+1]=this.requestId>>8&255,n[t]=255&this.requestId,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=i.OP_KILL_CURSORS>>24&255,n[t+2]=i.OP_KILL_CURSORS>>16&255,n[t+1]=i.OP_KILL_CURSORS>>8&255,n[t]=255&i.OP_KILL_CURSORS,n[(t+=4)+3]=0,n[t+2]=0,n[t+1]=0,n[t]=0,n[(t+=4)+3]=this.cursorIds.length>>24&255,n[t+2]=this.cursorIds.length>>16&255,n[t+1]=this.cursorIds.length>>8&255,n[t]=255&this.cursorIds.length,t+=4;for(var r=0;r>24&255,n[t+2]=this.cursorIds[r].getLowBits()>>16&255,n[t+1]=this.cursorIds[r].getLowBits()>>8&255,n[t]=255&this.cursorIds[r].getLowBits(),n[(t+=4)+3]=this.cursorIds[r].getHighBits()>>24&255,n[t+2]=this.cursorIds[r].getHighBits()>>16&255,n[t+1]=this.cursorIds[r].getHighBits()>>8&255,n[t]=255&this.cursorIds[r].getHighBits(),t+=4;return n};var l=function(e,t,n,o,s){s=s||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=o,this.bson=e,this.opts=s,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=o.readInt32LE(0),this.cursorId=new r(o.readInt32LE(4),o.readInt32LE(8)),this.startingFrom=o.readInt32LE(12),this.numberReturned=o.readInt32LE(16),this.documents=new Array(this.numberReturned),this.cursorNotFound=0!=(1&this.responseFlags),this.queryFailure=0!=(2&this.responseFlags),this.shardConfigStale=0!=(4&this.responseFlags),this.awaitCapable=0!=(8&this.responseFlags),this.promoteLongs="boolean"!=typeof s.promoteLongs||s.promoteLongs,this.promoteValues="boolean"!=typeof s.promoteValues||s.promoteValues,this.promoteBuffers="boolean"==typeof s.promoteBuffers&&s.promoteBuffers};l.prototype.isParsed=function(){return this.parsed},l.prototype.parse=function(e){if(!this.parsed){var t,n,r=(e=e||{}).raw||!1,o=e.documentsReturnedIn||null;n={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers},this.index=20;for(var s=0;st?a(e,t):n.full?a(e,null,r):void a(e,null,r.result))}}},function(e,t){e.exports=require("stream")},function(e,t,n){"use strict";const r=n(24).Transform,o=n(24).PassThrough,s=n(5).deprecate,i=n(0).handleCallback,a=n(1).ReadPreference,c=n(1).MongoError,u=n(20).CoreCursor,l=n(20).CursorState,p=n(1).BSON.Map,h=n(0).maybePromise,f=n(43),d=n(0).formattedOrderClause,m=n(181).each,y=n(182),g=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],b=["numberOfRetries","tailableRetryInterval"];class S extends u{constructor(e,t,n,r){super(e,t,n,r),this.operation&&(r=this.operation.options);const o=r.numberOfRetries||5,s=r.tailableRetryInterval||500,i=o,a=r.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!r.explicitlyIgnoreSession},!r.explicitlyIgnoreSession&&r.session&&(this.cursorState.session=r.session),!0===this.options.noCursorTimeout&&this.addCursorFlag("noCursorTimeout",!0);let c=1e3;this.cmd.cursor&&this.cmd.cursor.batchSize?c=this.cmd.cursor.batchSize:r.cursor&&r.cursor.batchSize?c=r.cursor.batchSize:"number"==typeof r.batchSize&&(c=r.batchSize),this.setCursorBatchSize(c)}get readPreference(){return this.operation?this.operation.readPreference:this.options.readPreference}get sortValue(){return this.cmd.sort}_initializeCursor(e){this.operation&&null!=this.operation.session?this.cursorState.session=this.operation.session:this.s.explicitlyIgnoreSession||this.cursorState.session||!this.topology.hasSessionSupport()||(this.cursorState.session=this.topology.startSession({owner:this}),this.operation&&(this.operation.session=this.cursorState.session)),super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return h(this,e,e=>{const t=this;if(t.isNotified())return e(null,!1);t._next((n,r)=>n?e(n):null==r||t.s.state===S.CLOSED||t.isDead()?e(null,!1):(t.s.state=l.OPEN,t.cursorState.cursorIndex--,t.cursorState.limit>0&&t.cursorState.currentLimit--,void e(null,!0)))})}next(e){return h(this,e,e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead())e(c.create({message:"Cursor is closed",driver:!0}));else{if(t.s.state===l.INIT&&t.cmd.sort)try{t.cmd.sort=d(t.cmd.sort)}catch(t){return e(t)}t._next((n,r)=>{if(n)return e(n);t.s.state=l.OPEN,e(null,r)})}})}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.query=e,this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxScan=e,this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.hint=e,this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.min=e,this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.max=e,this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.returnKey=e,this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.showDiskLoc=e,this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.snapshot=e,this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===b.indexOf(e))throw c.create({message:`option ${e} is not a supported option ${b}`,driver:!0});return this.s[e]=t,"numberOfRetries"===e&&(this.s.currentNumberOfRetries=t),this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if(-1===g.indexOf(e))throw c.create({message:`flag ${e} is not a supported flag ${g}`,driver:!0});if("boolean"!=typeof t)throw c.create({message:`flag ${e} must be a boolean value`,driver:!0});return this.cmd[e]=t,this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("$"!==e[0])throw c.create({message:e+" is not a valid query modifier",driver:!0});const n=e.substr(1);return this.cmd[n]=t,"orderby"===n&&(this.cmd.sort=this.cmd[n]),this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.comment=e,this}maxAwaitTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxAwaitTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxAwaitTimeMS=e,this}maxTimeMS(e){if("number"!=typeof e)throw c.create({message:"maxTimeMS must be a number",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.maxTimeMS=e,this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});return this.cmd.fields=e,this}sort(e,t){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support sorting",driver:!0});if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});let n=e;return Array.isArray(n)&&Array.isArray(n[0])&&(n=new p(n.map(e=>{const t=[e[0],null];if("asc"===e[1])t[1]=1;else if("desc"===e[1])t[1]=-1;else{if(1!==e[1]&&-1!==e[1]&&!e[1].$meta)throw new c("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");t[1]=e[1]}return t}))),null!=t&&(n=[[e,t]]),this.cmd.sort=n,this}batchSize(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support batchSize",driver:!0});if(this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"batchSize requires an integer",driver:!0});return this.cmd.batchSize=e,this.setCursorBatchSize(e),this}collation(e){return this.cmd.collation=e,this}limit(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support limit",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"limit requires an integer",driver:!0});return this.cmd.limit=e,this.setCursorLimit(e),this}skip(e){if(this.options.tailable)throw c.create({message:"Tailable cursor doesn't support skip",driver:!0});if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead())throw c.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw c.create({message:"skip requires an integer",driver:!0});return this.cmd.skip=e,this.setCursorSkip(e),this}each(e){this.rewind(),this.s.state=l.INIT,m(this,e)}forEach(e,t){if(this.rewind(),this.s.state=l.INIT,"function"!=typeof t)return new this.s.promiseLibrary((t,n)=>{m(this,(r,o)=>r?(n(r),!1):null==o?(t(null),!1):(e(o),!0))});m(this,(n,r)=>{if(n)return t(n),!1;if(null!=r)return e(r),!0;if(null==r&&t){const e=t;return t=null,e(null),!1}})}setReadPreference(e){if(this.s.state!==l.INIT)throw c.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof a)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new a(e)}return this}toArray(e){if(this.options.tailable)throw c.create({message:"Tailable cursor cannot be converted to array",driver:!0});return h(this,e,e=>{const t=this,n=[];t.rewind(),t.s.state=l.INIT;const r=()=>{t._next((o,s)=>{if(o)return i(e,o);if(null==s)return t.close({skipKillCursors:!0},()=>i(e,null,n));if(n.push(s),t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(n,e)}r()})};r()})}count(e,t,n){if(null==this.cmd.query)throw c.create({message:"count can only be used with find command",driver:!0});"function"==typeof t&&(n=t,t={}),t=t||{},"function"==typeof e&&(n=e,e=!0),this.cursorState.session&&(t=Object.assign({},t,{session:this.cursorState.session}));const r=new y(this,e,t);return f(this.topology,r,n)}close(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({},{skipKillCursors:!1},e),h(this,t,t=>{this.s.state=l.CLOSED,e.skipKillCursors||this.kill(),this._endSession(()=>{this.emit("close"),t(null,this)})})}map(e){if(this.cursorState.transforms&&this.cursorState.transforms.doc){const t=this.cursorState.transforms.doc;this.cursorState.transforms.doc=n=>e(t(n))}else this.cursorState.transforms={doc:e};return this}isClosed(){return this.isDead()}destroy(e){e&&this.emit("error",e),this.pause(),this.close()}stream(e){return this.cursorState.streamOptions=e||{},this}transformStream(e){const t=e||{};if("function"==typeof t.transform){const e=new r({objectMode:!0,transform:function(e,n,r){this.push(t.transform(e)),r()}});return this.pipe(e)}return this.pipe(new o({objectMode:!0}))}explain(e){return this.operation&&null==this.operation.cmd?(this.operation.options.explain=!0,this.operation.fullResponse=!1,f(this.topology,this.operation,e)):(this.cmd.explain=!0,this.cmd.readConcern&&delete this.cmd.readConcern,h(this,e,e=>{u.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}S.prototype.maxTimeMs=S.prototype.maxTimeMS,s(S.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead."),s(S.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version"),s(S.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version"),e.exports=S},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).OperationBase,s=n(1).ReadPreference,i=n(36),a=n(29),c=n(4).maxWireVersion,u=n(31).commandSupportsReadConcern,l=n(2).MongoError;e.exports=class extends o{constructor(e,t,n){super(t),this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(r.NO_INHERIT_OPTIONS)?void 0:e;this.readPreference=s.resolve(o,this.options),this.readConcern=function(e,t){return i.fromOptions(t)||e&&e.readConcern}(o,this.options),this.writeConcern=function(e,t){return a.fromOptions(t)||e&&e.writeConcern}(o,this.options),this.explain=!1,n&&"boolean"==typeof n.fullResponse&&(this.fullResponse=!0),this.options.readPreference=this.readPreference,e.s.logger?this.logger=e.s.logger:e.s.db&&e.s.db.logger&&(this.logger=e.s.db.logger)}executeCommand(e,t,n){this.server=e;const o=this.options,s=c(e),i=this.session&&this.session.inTransaction();this.readConcern&&u(t)&&!i&&Object.assign(t,{readConcern:this.readConcern}),o.collation&&s<5?n(new l(`Server ${e.name}, which reports wire version ${s}, does not support collation`)):(s>=5&&(this.writeConcern&&this.hasAspect(r.WRITE_OPERATION)&&Object.assign(t,{writeConcern:this.writeConcern}),o.collation&&"object"==typeof o.collation&&Object.assign(t,{collation:o.collation})),"number"==typeof o.maxTimeMS&&(t.maxTimeMS=o.maxTimeMS),"string"==typeof o.comment&&(t.comment=o.comment),this.logger&&this.logger.isDebug()&&this.logger.debug(`executing command ${JSON.stringify(t)} against ${this.ns}`),e.command(this.ns.toString(),t,this.options,(e,t)=>{e?n(e,null):this.fullResponse?n(null,t):n(null,t.result)}))}}},function(e,t,n){"use strict";const r=n(11).retrieveSnappy(),o=n(145),s={snappy:1,zlib:2},i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);e.exports={compressorIDs:s,uncompressibleCommands:i,compress:function(e,t,n){switch(e.options.agreedCompressor){case"snappy":r.compress(t,n);break;case"zlib":var s={};e.options.zlibCompressionLevel&&(s.level=e.options.zlibCompressionLevel),o.deflate(t,s,n);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}},decompress:function(e,t,n){if(e<0||e>s.length)throw new Error("Server sent message compressed using an unsupported compressor. (Received compressor ID "+e+")");switch(e){case s.snappy:r.uncompress(t,n);break;case s.zlib:o.inflate(t,n);break;default:n(null,t)}}}},function(e,t,n){"use strict";function r(e,t){return new Buffer(e,t)}e.exports={normalizedFunctionString:function(e){return e.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof Buffer.alloc?function(){return Buffer.alloc.apply(Buffer,arguments)}:r,toBuffer:"function"==typeof Buffer.from?function(){return Buffer.from.apply(Buffer,arguments)}:r}},function(e,t,n){"use strict";const r=new Set(["w","wtimeout","j","fsync"]);class o{constructor(e,t,n,r){null!=e&&(this.w=e),null!=t&&(this.wtimeout=t),null!=n&&(this.j=n),null!=r&&(this.fsync=r)}static fromOptions(e){if(null!=e&&(null!=e.writeConcern||null!=e.w||null!=e.wtimeout||null!=e.j||null!=e.fsync)){if(e.writeConcern){if("string"==typeof e.writeConcern)return new o(e.writeConcern);if(!Object.keys(e.writeConcern).some(e=>r.has(e)))return;return new o(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j,e.writeConcern.fsync)}return new o(e.w,e.wtimeout,e.j,e.fsync)}}}e.exports=o},function(e,t,n){"use strict";e.exports={AuthContext:class{constructor(e,t,n){this.connection=e,this.credentials=t,this.options=n}},AuthProvider:class{constructor(e){this.bson=e}prepare(e,t,n){n(void 0,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(10),s=r(),i=s.Binary,a=n(4).uuidV4,c=n(2).MongoError,u=n(2).isRetryableError,l=n(2).MongoNetworkError,p=n(2).MongoWriteConcernError,h=n(41).Transaction,f=n(41).TxnState,d=n(4).isPromiseLike,m=n(13),y=n(41).isTransactionCommand,g=n(9).resolveClusterTime,b=n(7).isSharded,S=n(4).maxWireVersion,v=n(0).now,w=n(0).calculateDurationInMs;function _(e,t){if(null==e.serverSession){const e=new c("Cannot use a session that has ended");if("function"==typeof t)return t(e,null),!1;throw e}return!0}const O=Symbol("serverSession");class T extends o{constructor(e,t,n,r){if(super(),null==e)throw new Error("ClientSession requires a topology");if(null==t||!(t instanceof M))throw new Error("ClientSession requires a ServerSessionPool");n=n||{},r=r||{},this.topology=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=r,this[O]=void 0,this.supports={causalConsistency:void 0===n.causalConsistency||n.causalConsistency},this.clusterTime=n.initialClusterTime,this.operationTime=null,this.explicit=!!n.explicit,this.owner=n.owner,this.defaultTransactionOptions=Object.assign({},n.defaultTransactionOptions),this.transaction=new h}get id(){return this.serverSession.id}get serverSession(){return null==this[O]&&(this[O]=this.sessionPool.acquire()),this[O]}endSession(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},this.hasEnded||(this.serverSession&&this.inTransaction()&&this.abortTransaction(),this.sessionPool.release(this.serverSession),this[O]=void 0,this.hasEnded=!0,this.emit("ended",this)),"function"==typeof t&&t(null,null)}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}equals(e){return e instanceof T&&this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){if(_(this),this.inTransaction())throw new c("Transaction already in progress");const t=S(this.topology);if(b(this.topology)&&null!=t&&t<8)throw new c("Transactions are not supported on sharded clusters in MongoDB < 4.2.");this.incrementTransactionNumber(),this.transaction=new h(Object.assign({},this.clientOptions,e||this.defaultTransactionOptions)),this.transaction.transition(f.STARTING_TRANSACTION)}commitTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"commitTransaction",(n,r)=>n?t(n):e(r))});I(this,"commitTransaction",e)}abortTransaction(e){if("function"!=typeof e)return new Promise((e,t)=>{I(this,"abortTransaction",(n,r)=>n?t(n):e(r))});I(this,"abortTransaction",e)}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){return N(this,v(),e,t)}}const E=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function C(e,t){return w(e){if(!function(e){return A.has(e.transaction.state)}(e))return function e(t,n,r,o){return t.commitTransaction().catch(s=>{if(s instanceof c&&C(n,12e4)&&!x(s)){if(s.hasErrorLabel("UnknownTransactionCommitResult"))return e(t,n,r,o);if(s.hasErrorLabel("TransientTransactionError"))return N(t,n,r,o)}throw s})}(e,t,n,r)}).catch(o=>{function s(o){if(o instanceof c&&o.hasErrorLabel("TransientTransactionError")&&C(t,12e4))return N(e,t,n,r);throw x(o)&&o.addErrorLabel("UnknownTransactionCommitResult"),o}return e.transaction.isActive?e.abortTransaction().then(()=>s(o)):s(o)})}function I(e,t,n){if(!_(e,n))return;let r=e.transaction.state;if(r===f.NO_TRANSACTION)return void n(new c("No transaction started"));if("commitTransaction"===t){if(r===f.STARTING_TRANSACTION||r===f.TRANSACTION_COMMITTED_EMPTY)return e.transaction.transition(f.TRANSACTION_COMMITTED_EMPTY),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call commitTransaction after calling abortTransaction"))}else{if(r===f.STARTING_TRANSACTION)return e.transaction.transition(f.TRANSACTION_ABORTED),void n(null,null);if(r===f.TRANSACTION_ABORTED)return void n(new c("Cannot call abortTransaction twice"));if(r===f.TRANSACTION_COMMITTED||r===f.TRANSACTION_COMMITTED_EMPTY)return void n(new c("Cannot call abortTransaction after calling commitTransaction"))}const o={[t]:1};let s;function i(r,o){var s;"commitTransaction"===t?(e.transaction.transition(f.TRANSACTION_COMMITTED),r&&(r instanceof l||r instanceof p||u(r)||x(r))&&(x(s=r)||!E.has(s.codeName)&&100!==s.code&&79!==s.code)&&(r.addErrorLabel("UnknownTransactionCommitResult"),e.transaction.unpinServer())):e.transaction.transition(f.TRANSACTION_ABORTED),n(r,o)}function a(e){return"commitTransaction"===t?e:null}e.transaction.options.writeConcern?s=Object.assign({},e.transaction.options.writeConcern):e.clientOptions&&e.clientOptions.w&&(s={w:e.clientOptions.w}),r===f.TRANSACTION_COMMITTED&&(s=Object.assign({wtimeout:1e4},s,{w:"majority"})),s&&Object.assign(o,{writeConcern:s}),"commitTransaction"===t&&e.transaction.options.maxTimeMS&&Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS}),e.transaction.recoveryToken&&function(e){return!!e.topology.s.options.useRecoveryToken}(e)&&(o.recoveryToken=e.transaction.recoveryToken),e.topology.command("admin.$cmd",o,{session:e},(t,n)=>{if(t&&u(t))return o.commitTransaction&&(e.transaction.unpinServer(),o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})),e.topology.command("admin.$cmd",o,{session:e},(e,t)=>i(a(e),t));i(a(t),n)})}class k{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)},this.lastUse=v(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round(w(this.lastUse)%864e5%36e5/6e4)>e-1}}class M{constructor(e){if(null==e)throw new Error("ServerSessionPool requires a topology");this.topology=e,this.sessions=[]}endAllPooledSessions(e){this.sessions.length?this.topology.endSessions(this.sessions.map(e=>e.id),()=>{this.sessions=[],"function"==typeof e&&e()}):"function"==typeof e&&e()}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){const t=this.sessions.shift();if(!t.hasTimedOut(e))return t}return new k}release(e){const t=this.topology.logicalSessionTimeoutMinutes;for(;this.sessions.length;){if(!this.sessions[this.sessions.length-1].hasTimedOut(t))break;this.sessions.pop()}if(!e.hasTimedOut(t)){if(e.isDirty)return;this.sessions.unshift(e)}}}function R(e,t){return!!(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch)||!(!(e.mapReduce&&t&&t.out)||1!==t.out.inline&&"inline"!==t.out)}e.exports={ClientSession:T,ServerSession:k,ServerSessionPool:M,TxnState:f,applySession:function(e,t,n){if(e.hasEnded)return new c("Cannot use a session that has ended");if(n&&n.writeConcern&&0===n.writeConcern.w)return;const r=e.serverSession;r.lastUse=v(),t.lsid=r.id;const o=e.inTransaction()||y(t),i=n.willRetryWrite,a=R(t,n);if(r.txnNumber&&(i||o)&&(t.txnNumber=s.Long.fromNumber(r.txnNumber)),!o)return e.transaction.state!==f.NO_TRANSACTION&&e.transaction.transition(f.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&a&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})));if(n.readPreference&&!n.readPreference.equals(m.primary))return new c("Read preference in a transaction must be primary, not: "+n.readPreference.mode);if(t.autocommit=!1,e.transaction.state===f.STARTING_TRANSACTION){e.transaction.transition(f.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const n=e.transaction.options.readConcern||e.clientOptions.readConcern;n&&(t.readConcern=n),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},updateSessionFromResponse:function(e,t){t.$clusterTime&&g(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken)},commandSupportsReadConcern:R}},function(e,t,n){"use strict";const r=n(10),o=n(1).MongoError,s=n(5).format,i=n(1).ReadPreference,a=n(1).Sessions.ClientSession;var c=function(e,t){var n=this;t=t||{force:!1,bufferMaxEntries:-1},this.s={storedOps:[],storeOptions:t,topology:e},Object.defineProperty(this,"length",{enumerable:!0,get:function(){return n.s.storedOps.length}})};c.prototype.add=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,n:t,o:n,op:r,c:i})},c.prototype.addObjectAndMethod=function(e,t,n,r,i){if(this.s.storeOptions.force)return i(o.create({message:"db closed by application",driver:!0}));if(0===this.s.storeOptions.bufferMaxEntries)return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}));if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries)for(;this.s.storedOps.length>0;){this.s.storedOps.shift().c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:!0}))}else this.s.storedOps.push({t:e,m:n,o:t,p:r,c:i})},c.prototype.flush=function(e){for(;this.s.storedOps.length>0;)this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:!0}))};var u=["primary","primaryPreferred","nearest","secondaryPreferred"],l=["secondary","secondaryPreferred"];c.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];for(var n="boolean"!=typeof e.executePrimary||e.executePrimary,r="boolean"!=typeof e.executeSecondary||e.executeSecondary;t.length>0;){var o=t.shift();"cursor"===o.t?(n&&r||n&&o.o.options&&o.o.options.readPreference&&-1!==u.indexOf(o.o.options.readPreference.mode)||!n&&r&&o.o.options&&o.o.options.readPreference&&-1!==l.indexOf(o.o.options.readPreference.mode))&&o.o[o.m].apply(o.o,o.p):"auth"===o.t?this.s.topology[o.t].apply(this.s.topology,o.o):(n&&r||n&&o.op&&o.op.readPreference&&-1!==u.indexOf(o.op.readPreference.mode)||!n&&r&&o.op&&o.op.readPreference&&-1!==l.indexOf(o.op.readPreference.mode))&&this.s.topology[o.t](o.n,o.o,o.op,o.c)}},c.prototype.all=function(){return this.s.storedOps};var p=function(e){var t=function(e,t,n){Object.defineProperty(e,t,{enumerable:!0,get:function(){return n}})},n=!1,r=!1,o=!1,s=!1,i=!1,a=!1,c=e.maxWriteBatchSize||1e3,u=!1,l=!1;e.minWireVersion>=0&&(o=!0),e.maxWireVersion>=1&&(n=!0,s=!0),e.maxWireVersion>=2&&(r=!0),e.maxWireVersion>=3&&(i=!0,a=!0),e.maxWireVersion>=5&&(u=!0,l=!0),null==e.minWireVersion&&(e.minWireVersion=0),null==e.maxWireVersion&&(e.maxWireVersion=0),t(this,"hasAggregationCursor",n),t(this,"hasWriteCommands",r),t(this,"hasTextSearch",o),t(this,"hasAuthCommands",s),t(this,"hasListCollectionsCommand",i),t(this,"hasListIndexesCommand",a),t(this,"minWireVersion",e.minWireVersion),t(this,"maxWireVersion",e.maxWireVersion),t(this,"maxNumberOfDocsInBatch",c),t(this,"commandsTakeWriteConcern",u),t(this,"commandsTakeCollation",l)};class h extends r{constructor(){super(),this.setMaxListeners(1/0)}hasSessionSupport(){return null!=this.logicalSessionTimeoutMinutes}startSession(e,t){const n=new a(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.s.coreTopology.lastIsMaster()?null:(this.s.sCapabilities=new p(this.s.coreTopology.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){this.s.coreTopology.command(e.toString(),t,i.translate(n),r)}insert(e,t,n,r){this.s.coreTopology.insert(e.toString(),t,n,r)}update(e,t,n,r){this.s.coreTopology.update(e.toString(),t,n,r)}remove(e,t,n,r){this.s.coreTopology.remove(e.toString(),t,n,r)}isConnected(e){return e=e||{},e=i.translate(e),this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,n){return n=n||{},(n=i.translate(n)).disconnectHandler=this.s.store,n.topology=this,this.s.coreTopology.cursor(e,t,n)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,n){return this.s.coreTopology.selectServer(e,t,n)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool&&this.s.sessionPool.endAllPooledSessions(),!0===e&&(this.s.storeOptions.force=e,this.s.store.flush()),this.s.coreTopology.destroy({force:"boolean"==typeof e&&e},t)}}Object.defineProperty(h.prototype,"bson",{enumerable:!0,get:function(){return this.s.coreTopology.s.bson}}),Object.defineProperty(h.prototype,"parserType",{enumerable:!0,get:function(){return this.s.coreTopology.parserType}}),Object.defineProperty(h.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}}),Object.defineProperty(h.prototype,"type",{enumerable:!0,get:function(){return this.s.coreTopology.type}}),t.Store=c,t.ServerCapabilities=p,t.TopologyBase=h},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Long",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i{void 0!==t[e]&&(this[e]=t[e])}),this.me&&(this.me=this.me.toLowerCase()),this.hosts=this.hosts.map(e=>e.toLowerCase()),this.passives=this.passives.map(e=>e.toLowerCase()),this.arbiters=this.arbiters.map(e=>e.toLowerCase())}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===i.RSSecondary||this.isWritable}get isDataBearing(){return u.has(this.type)}get isWritable(){return c.has(this.type)}get host(){const e=(":"+this.port).length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):e}equals(e){const t=this.topologyVersion===e.topologyVersion||0===h(this.topologyVersion,e.topologyVersion);return null!=e&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&r(this.hosts,e.hosts)&&o(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&(this.electionId?e.electionId&&this.electionId.equals(e.electionId):this.electionId===e.electionId)&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}},parseServerType:p,compareTopologyVersion:h}},function(e,t,n){"use strict";const r=n(16).Buffer,o=n(7).opcodes,s=n(7).databaseNamespace,i=n(13);let a=0;class c{constructor(e,t,n,r){if(null==n)throw new Error("query must be specified for query");this.bson=e,this.ns=t,this.command=n,this.command.$db=s(t),r.readPreference&&r.readPreference.mode!==i.PRIMARY&&(this.command.$readPreference=r.readPreference.toJSON()),this.options=r||{},this.requestId=r.requestId?r.requestId:c.getRequestId(),this.serializeFunctions="boolean"==typeof r.serializeFunctions&&r.serializeFunctions,this.ignoreUndefined="boolean"==typeof r.ignoreUndefined&&r.ignoreUndefined,this.checkKeys="boolean"==typeof r.checkKeys&&r.checkKeys,this.maxBsonSize=r.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=r.moreToCome||!1,this.exhaustAllowed="boolean"==typeof r.exhaustAllowed&&r.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const n=r.alloc(20);e.push(n);let s=n.length;const i=this.command;return s+=this.makeDocumentSegment(e,i),n.writeInt32LE(s,0),n.writeInt32LE(this.requestId,4),n.writeInt32LE(0,8),n.writeInt32LE(o.OP_MSG,12),n.writeUInt32LE(t,16),e}makeDocumentSegment(e,t){const n=r.alloc(1);n[0]=0;const o=this.serializeBson(t);return e.push(n),e.push(o),n.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}c.getRequestId=function(){return a=a+1&2147483647,a};e.exports={Msg:c,BinMsg:class{constructor(e,t,n,r,o){o=o||{promoteLongs:!0,promoteValues:!0,promoteBuffers:!1},this.parsed=!1,this.raw=t,this.data=r,this.bson=e,this.opts=o,this.length=n.length,this.requestId=n.requestId,this.responseTo=n.responseTo,this.opCode=n.opCode,this.fromCompressed=n.fromCompressed,this.responseFlags=r.readInt32LE(0),this.checksumPresent=0!=(1&this.responseFlags),this.moreToCome=0!=(2&this.responseFlags),this.exhaustAllowed=0!=(65536&this.responseFlags),this.promoteLongs="boolean"!=typeof o.promoteLongs||o.promoteLongs,this.promoteValues="boolean"!=typeof o.promoteValues||o.promoteValues,this.promoteBuffers="boolean"==typeof o.promoteBuffers&&o.promoteBuffers,this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{},this.index=4;const t=e.raw||!1,n=e.documentsReturnedIn||null,r={promoteLongs:"boolean"==typeof e.promoteLongs?e.promoteLongs:this.opts.promoteLongs,promoteValues:"boolean"==typeof e.promoteValues?e.promoteValues:this.opts.promoteValues,promoteBuffers:"boolean"==typeof e.promoteBuffers?e.promoteBuffers:this.opts.promoteBuffers};for(;this.index255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(t="string"==typeof e?e.charCodeAt(0):null!=e.length?e[0]:e,this.buffer.length>this.position)this.buffer[this.position++]=t;else if(void 0!==r&&r.isBuffer(this.buffer)){var n=o.allocBuffer(s.BUFFER_SIZE+this.buffer.length);this.buffer.copy(n,0,0,this.buffer.length),this.buffer=n,this.buffer[this.position++]=t}else{n=null,n="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(s.BUFFER_SIZE+this.buffer.length)):new Array(s.BUFFER_SIZE+this.buffer.length);for(var i=0;ithis.position?t+e.length:this.position;else if(void 0!==r&&"string"==typeof e&&r.isBuffer(this.buffer))this.buffer.write(e,t,"binary"),this.position=t+e.length>this.position?t+e.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(e)||"[object Array]"===Object.prototype.toString.call(e)&&"string"!=typeof e){for(s=0;sthis.position?t:this.position}else if("string"==typeof e){for(s=0;sthis.position?t:this.position}},s.prototype.read=function(e,t){if(t=t&&t>0?t:this.position,this.buffer.slice)return this.buffer.slice(e,e+t);for(var n="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(t)):new Array(t),r=0;r=6&&null==t.__nodejs_mock_server__}(e),b=h.session;let S=e.clusterTime,v=Object.assign({},n);if(function(e){if(null==e)return!1;if(e.description)return e.description.maxWireVersion>=6;return null!=e.ismaster&&e.ismaster.maxWireVersion>=6}(e)&&b){b.clusterTime&&b.clusterTime.clusterTime.greaterThan(S.clusterTime)&&(S=b.clusterTime);const e=l(b,v,h);if(e)return f(e)}S&&(v.$clusterTime=S),a(e)&&!g&&y&&"primary"!==y.mode&&(v={$query:v,$readPreference:y.toJSON()});const w=Object.assign({command:!0,numberToSkip:0,numberToReturn:-1,checkKeys:!1},h);w.slaveOk=y.slaveOk();const _=c(t)+".$cmd",O=g?new o(d,_,v,w):new r(d,_,v,w),T=b&&(b.inTransaction()||u(v))?function(e){return e&&e instanceof p&&!e.hasErrorLabel("TransientTransactionError")&&e.addErrorLabel("TransientTransactionError"),!n.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")&&b.transaction.unpinServer(),f.apply(null,arguments)}:f;try{m.write(O,w,T)}catch(e){T(e)}}e.exports=function(e,t,n,r,o){if("function"==typeof r&&(o=r,r={}),r=r||{},null==n)return o(new s(`command ${JSON.stringify(n)} does not return a cursor`));if(!function(e){return h(e)&&e.autoEncrypter}(e))return void f(e,t,n,r,o);const i=h(e);"number"!=typeof i||i<8?o(new s("Auto-encryption requires a minimum MongoDB version of 4.2")):function(e,t,n,r,o){const s=e.autoEncrypter;function i(e,t){e||null==t?o(e,t):s.decrypt(t.result,r,(e,n)=>{e?o(e,null):(t.result=n,t.message.documents=[n],o(null,t))})}s.encrypt(t,n,r,(n,s)=>{n?o(n,null):f(e,t,s,r,i)})}(e,t,n,r,o)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(3).Aspect,s=n(3).OperationBase,i=n(13),a=n(2).isRetryableError,c=n(4).maxWireVersion,u=n(4).isUnifiedTopology;function l(e,t,n){if(null==e)throw new TypeError("This method requires a valid topology instance");if(!(t instanceof s))throw new TypeError("This method requires a valid operation instance");if(u(e)&&e.shouldCheckForSessionSupport())return function(e,t,n){const r=e.s.promiseLibrary;let o;"function"!=typeof n&&(o=new r((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));return e.selectServer(i.primaryPreferred,r=>{r?n(r):l(e,t,n)}),o}(e,t,n);const c=e.s.promiseLibrary;let h,f,d;if(e.hasSessionSupport())if(null==t.session)f=Symbol(),h=e.startSession({owner:f}),t.session=h;else if(t.session.hasEnded)throw new r("Use of expired sessions is not permitted");function m(e,r){h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),n(e,r)}"function"!=typeof n&&(d=new c((e,t)=>{n=(n,r)=>{if(n)return t(n);e(r)}}));try{t.hasAspect(o.EXECUTE_WITH_SELECTION)?function(e,t,n){const s=t.readPreference||i.primary,c=t.session&&t.session.inTransaction();if(c&&!s.equals(i.primary))return void n(new r("Read preference in a transaction must be primary, not: "+s.mode));const u={readPreference:s,session:t.session};function l(r,o){return null==r?n(null,o):a(r)?void e.selectServer(u,(e,r)=>{!e&&p(r)?t.execute(r,n):n(e,null)}):n(r)}e.selectServer(u,(r,s)=>{if(r)return void n(r,null);const i=!1!==e.s.options.retryReads&&t.session&&!c&&p(s)&&t.canRetryRead;t.hasAspect(o.RETRYABLE)&&i?t.execute(s,l):t.execute(s,n)})}(e,t,m):t.execute(m)}catch(e){throw h&&h.owner===f&&(h.endSession(),t.session===h&&t.clearSession()),e}return d}function p(e){return c(e)>=6}e.exports=l},function(e,t){function n(e){return Object.prototype.toString.call(e)}t.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===n(e)},t.isBoolean=function(e){return"boolean"==typeof e},t.isNull=function(e){return null===e},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e},t.isString=function(e){return"string"==typeof e},t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=function(e){return void 0===e},t.isRegExp=function(e){return"[object RegExp]"===n(e)},t.isObject=function(e){return"object"==typeof e&&null!==e},t.isDate=function(e){return"[object Date]"===n(e)},t.isError=function(e){return"[object Error]"===n(e)||e instanceof Error},t.isFunction=function(e){return"function"==typeof e},t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=Buffer.isBuffer},function(e,t,n){try{var r=n(5);if("function"!=typeof r.inherits)throw"";e.exports=r.inherits}catch(t){e.exports=n(170)}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(14).createIndex,i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern,c=n(14).ensureIndex,u=n(14).evaluate,l=n(14).executeCommand,p=n(0).handleCallback,h=n(14).indexInformation,f=n(1).BSON.Long,d=n(1).MongoError,m=n(1).ReadPreference,y=n(12).insertDocuments,g=n(12).updateDocuments;function b(e,t,n){h(e.s.db,e.collectionName,t,n)}e.exports={createIndex:function(e,t,n,r){s(e.s.db,e.collectionName,t,n,r)},createIndexes:function(e,t,n,r){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}),h.group.key=e}(f=Object.assign({},f)).readPreference=m.resolve(e,f),a(h,e,f);try{i(h,e,f)}catch(e){return d(e,null)}l(e.s.db,h,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.retval)})}else{const i=null!=s&&"Code"===s._bsontype?s.scope:{};i.ns=e.collectionName,i.keys=t,i.condition=n,i.initial=r;const a='function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'.replace(/ reduce;/,s.toString()+";");u(e.s.db,new o(a,i),null,f,(e,t)=>{if(e)return p(d,e,null);p(d,null,t.result||t)})}},indexes:function(e,t,n){t=Object.assign({},{full:!0},t),h(e.s.db,e.collectionName,t,n)},indexExists:function(e,t,n,r){b(e,n,(e,n)=>{if(null!=e)return p(r,e,null);if(!Array.isArray(t))return p(r,null,null!=n[t]);for(let e=0;e{if(r)return p(n,r,null);if(null==s)return p(n,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:!0},t);const i=[];o&&(t.raw=o);for(let n=0;n{if(null!=o)return null==t?p(o,null,null):e?p(o,e,null):void p(o,null,n)})}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(0).deprecateOptions,s=n(0).checkCollectionName,i=n(1).BSON.ObjectID,a=n(1).MongoError,c=n(0).normalizeHintField,u=n(0).decorateCommand,l=n(0).decorateWithCollation,p=n(0).decorateWithReadConcern,h=n(0).formattedOrderClause,f=n(1).ReadPreference,d=n(183),m=n(184),y=n(79),g=n(0).executeLegacyOperation,b=n(29),S=n(36),v=n(0).MongoDBNamespace,w=n(82),_=n(83),O=n(46).ensureIndex,T=n(46).group,E=n(46).parallelCollectionScan,C=n(12).removeDocuments,x=n(46).save,A=n(12).updateDocuments,N=n(63),I=n(113),k=n(185),M=n(114),R=n(186),D=n(187),B=n(188),P=n(84).DropCollectionOperation,L=n(115),j=n(189),U=n(190),z=n(191),F=n(192),W=n(64),q=n(193),$=n(194),H=n(195),V=n(196),Y=n(197),G=n(198),K=n(116),X=n(199),J=n(200),Z=n(201),Q=n(202),ee=n(203),te=n(117),ne=n(121),re=n(212),oe=n(213),se=n(214),ie=n(215),ae=n(216),ce=n(43),ue=["ignoreUndefined"];function le(e,t,n,r,o,a){s(r);const c=null==a||null==a.slaveOk?e.slaveOk:a.slaveOk,u=null==a||null==a.serializeFunctions?e.s.options.serializeFunctions:a.serializeFunctions,l=null==a||null==a.raw?e.s.options.raw:a.raw,p=null==a||null==a.promoteLongs?e.s.options.promoteLongs:a.promoteLongs,h=null==a||null==a.promoteValues?e.s.options.promoteValues:a.promoteValues,d=null==a||null==a.promoteBuffers?e.s.options.promoteBuffers:a.promoteBuffers,m=new v(n,r),y=a.promiseLibrary||Promise;o=null==o?i:o,this.s={pkFactory:o,db:e,topology:t,options:a,namespace:m,readPreference:f.fromOptions(a),slaveOk:c,serializeFunctions:u,raw:l,promoteLongs:p,promoteValues:h,promoteBuffers:d,internalHint:null,collectionHint:null,promiseLibrary:y,readConcern:S.fromOptions(a),writeConcern:b.fromOptions(a)}}Object.defineProperty(le.prototype,"dbName",{enumerable:!0,get:function(){return this.s.namespace.db}}),Object.defineProperty(le.prototype,"collectionName",{enumerable:!0,get:function(){return this.s.namespace.collection}}),Object.defineProperty(le.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),Object.defineProperty(le.prototype,"readConcern",{enumerable:!0,get:function(){return null==this.s.readConcern?this.s.db.readConcern:this.s.readConcern}}),Object.defineProperty(le.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?this.s.db.readPreference:this.s.readPreference}}),Object.defineProperty(le.prototype,"writeConcern",{enumerable:!0,get:function(){return null==this.s.writeConcern?this.s.db.writeConcern:this.s.writeConcern}}),Object.defineProperty(le.prototype,"hint",{enumerable:!0,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const pe=["maxScan","fields","snapshot","oplogReplay"];function he(e,t,n,r,o){const s=Array.prototype.slice.call(arguments,1);return o="function"==typeof s[s.length-1]?s.pop():void 0,t=s.length&&s.shift()||[],n=s.length?s.shift():null,r=s.length&&s.shift()||{},(r=Object.assign({},r)).readPreference=f.PRIMARY,ce(this.s.topology,new W(this,e,t,n,r),o)}le.prototype.find=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `find()` must be a callback or undefined");let r=e;"function"!=typeof n&&("function"==typeof t?(n=t,t=void 0):null==t&&(n="function"==typeof r?r:void 0,r="object"==typeof r?r:void 0)),r=null==r?{}:r;const o=r;if(Buffer.isBuffer(o)){const e=o[0]|o[1]<<8|o[2]<<16|o[3]<<24;if(e!==o.length){const t=new Error("query selector raw message size does not match message header size ["+o.length+"] != ["+e+"]");throw t.name="MongoError",t}}null!=r&&"ObjectID"===r._bsontype&&(r={_id:r}),t||(t={});let s=t.projection||t.fields;s&&!Buffer.isBuffer(s)&&Array.isArray(s)&&(s=s.length?s.reduce((e,t)=>(e[t]=1,e),{}):{_id:1});let i=Object.assign({},t);for(let e in this.s.options)-1!==ue.indexOf(e)&&(i[e]=this.s.options[e]);if(i.skip=t.skip?t.skip:0,i.limit=t.limit?t.limit:0,i.raw="boolean"==typeof t.raw?t.raw:this.s.raw,i.hint=null!=t.hint?c(t.hint):this.s.collectionHint,i.timeout=void 0===t.timeout?void 0:t.timeout,i.slaveOk=null!=t.slaveOk?t.slaveOk:this.s.db.slaveOk,i.readPreference=f.resolve(this,i),null==i.readPreference||"primary"===i.readPreference&&"primary"===i.readPreference.mode||(i.slaveOk=!0),null!=r&&"object"!=typeof r)throw a.create({message:"query selector must be an object",driver:!0});const d={find:this.s.namespace.toString(),limit:i.limit,skip:i.skip,query:r};"boolean"==typeof t.allowDiskUse&&(d.allowDiskUse=t.allowDiskUse),"boolean"==typeof i.awaitdata&&(i.awaitData=i.awaitdata),"boolean"==typeof i.timeout&&(i.noCursorTimeout=i.timeout),u(d,i,["session","collation"]),s&&(d.fields=s),i.db=this.s.db,i.promiseLibrary=this.s.promiseLibrary,null==i.raw&&"boolean"==typeof this.s.raw&&(i.raw=this.s.raw),null==i.promoteLongs&&"boolean"==typeof this.s.promoteLongs&&(i.promoteLongs=this.s.promoteLongs),null==i.promoteValues&&"boolean"==typeof this.s.promoteValues&&(i.promoteValues=this.s.promoteValues),null==i.promoteBuffers&&"boolean"==typeof this.s.promoteBuffers&&(i.promoteBuffers=this.s.promoteBuffers),d.sort&&(d.sort=h(d.sort)),p(d,this,t);try{l(d,this,t)}catch(e){if("function"==typeof n)return n(e,null);throw e}const m=this.s.topology.cursor(new z(this,this.s.namespace,d,i),i);if("function"!=typeof n)return m;n(null,m)})),le.prototype.insertOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new J(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insertMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?Object.assign({},t):{ordered:!0};const r=new X(this,e,t);return ce(this.s.topology,r,n)},le.prototype.bulkWrite=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{ordered:!0},!Array.isArray(e))throw a.create({message:"operations must be an array of documents",driver:!0});const r=new I(this,e,t);return ce(this.s.topology,r,n)},le.prototype.insert=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{ordered:!1},e=Array.isArray(e)?e:[e],!0===t.keepGoing&&(t.ordered=!1),this.insertMany(e,t,n)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead."),le.prototype.updateOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ae(this,e,t,n),r)},le.prototype.replaceOne=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new oe(this,e,t,n),r)},le.prototype.updateMany=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=Object.assign({},n),this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),ce(this.s.topology,new ie(this,e,t,n),r)},le.prototype.update=r((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},this.s.options.ignoreUndefined&&((n=Object.assign({},n)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,A,[this,e,t,n,r])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead."),le.prototype.deleteOne=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new D(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeOne=le.prototype.deleteOne,le.prototype.deleteMany=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t),this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined);const r=new R(this,e,t);return ce(this.s.topology,r,n)},le.prototype.removeMany=le.prototype.deleteMany,le.prototype.remove=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,C,[this,e,t,n])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead."),le.prototype.save=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},this.s.options.ignoreUndefined&&((t=Object.assign({},t)).ignoreUndefined=this.s.options.ignoreUndefined),g(this.s.topology,x,[this,e,t,n])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead."),le.prototype.findOne=o({name:"collection.find",deprecatedOptions:pe,optionsIndex:1},(function(e,t,n){"object"==typeof n&&console.warn("Third parameter to `findOne()` must be a callback or undefined"),"function"==typeof e&&(n=e,e={},t={}),"function"==typeof t&&(n=t,t={});const r=new F(this,e=e||{},t=t||{});return ce(this.s.topology,r,n)})),le.prototype.rename=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t,{readPreference:f.PRIMARY});const r=new ne(this,e,t);return ce(this.s.topology,r,n)},le.prototype.drop=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new P(this.s.db,this.collectionName,e);return ce(this.s.topology,n,t)},le.prototype.options=function(e,t){"function"==typeof e&&(t=e,e={});const n=new te(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.isCapped=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Z(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.createIndex=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.createIndexes=function(e,t,n){"function"==typeof t&&(n=t,t={}),"number"!=typeof(t=t?Object.assign({},t):{}).maxTimeMS&&delete t.maxTimeMS;const r=new M(this,this.collectionName,e,t);return ce(this.s.topology,r,n)},le.prototype.dropIndex=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,(t=r.length&&r.shift()||{}).readPreference=f.PRIMARY;const o=new L(this,e,t);return ce(this.s.topology,o,n)},le.prototype.dropIndexes=function(e,t){"function"==typeof e&&(t=e,e={}),"number"!=typeof(e=e?Object.assign({},e):{}).maxTimeMS&&delete e.maxTimeMS;const n=new j(this,e);return ce(this.s.topology,n,t)},le.prototype.dropAllIndexes=r(le.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead."),le.prototype.reIndex=r((function(e,t){"function"==typeof e&&(t=e,e={});const n=new re(this,e=e||{});return ce(this.s.topology,n,t)}),"collection.reIndex is deprecated. Use db.command instead."),le.prototype.listIndexes=function(e){return new _(this.s.topology,new Q(this,e),e)},le.prototype.ensureIndex=r((function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},g(this.s.topology,O,[this,e,t,n])}),"collection.ensureIndex is deprecated. Use createIndexes instead."),le.prototype.indexExists=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new G(this,e,t=t||{});return ce(this.s.topology,r,n)},le.prototype.indexInformation=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new K(this.s.db,this.collectionName,e);return ce(this.s.topology,r,t)},le.prototype.count=r((function(e,t,n){const r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},"function"==typeof(t=r.length&&r.shift()||{})&&(n=t,t={}),t=t||{},ce(this.s.topology,new U(this,e,t),n)}),"collection.count is deprecated, and will be removed in a future version. Use Collection.countDocuments or Collection.estimatedDocumentCount instead"),le.prototype.estimatedDocumentCount=function(e,t){"function"==typeof e&&(t=e,e={});const n=new U(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.countDocuments=function(e,t,n){const r=Array.prototype.slice.call(arguments,0);n="function"==typeof r[r.length-1]?r.pop():void 0,e=r.length&&r.shift()||{},t=r.length&&r.shift()||{};const o=new k(this,e,t);return ce(this.s.topology,o,n)},le.prototype.distinct=function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);r="function"==typeof o[o.length-1]?o.pop():void 0;const s=o.length&&o.shift()||{},i=o.length&&o.shift()||{},a=new B(this,e,s,i);return ce(this.s.topology,a,r)},le.prototype.indexes=function(e,t){"function"==typeof e&&(t=e,e={});const n=new Y(this,e=e||{});return ce(this.s.topology,n,t)},le.prototype.stats=function(e,t){const n=Array.prototype.slice.call(arguments,0);t="function"==typeof n[n.length-1]?n.pop():void 0,e=n.length&&n.shift()||{};const r=new se(this,e);return ce(this.s.topology,r,t)},le.prototype.findOneAndDelete=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},ce(this.s.topology,new q(this,e,t),n)},le.prototype.findOneAndReplace=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new $(this,e,t,n),r)},le.prototype.findOneAndUpdate=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},ce(this.s.topology,new H(this,e,t,n),r)},le.prototype.findAndModify=r(he,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead."),le.prototype._findAndModify=he,le.prototype.findAndRemove=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length&&o.shift()||[],(n=o.length&&o.shift()||{}).remove=!0,ce(this.s.topology,new W(this,e,t,null,n),r)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead."),le.prototype.aggregate=function(e,t,n){if(Array.isArray(e))"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});else{const r=Array.prototype.slice.call(arguments,0);n=r.pop();const o=r[r.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?r.pop():{},e=r}const r=new w(this.s.topology,new N(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},le.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new y(this,e,t)},le.prototype.parallelCollectionScan=r((function(e,t){return"function"==typeof e&&(t=e,e={numCursors:1}),e.numCursors=e.numCursors||1,e.batchSize=e.batchSize||1e3,(e=Object.assign({},e)).readPreference=f.resolve(this,e),e.promiseLibrary=this.s.promiseLibrary,e.session&&(e.session=void 0),g(this.s.topology,E,[this,e,t],{skipSessions:!0})}),"parallelCollectionScan is deprecated in MongoDB v4.1"),le.prototype.geoHaystackSearch=r((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,2);r="function"==typeof o[o.length-1]?o.pop():void 0,n=o.length&&o.shift()||{};const s=new V(this,e,t,n);return ce(this.s.topology,s,r)}),"geoHaystackSearch is deprecated, and will be removed in a future version."),le.prototype.group=r((function(e,t,n,r,o,s,i,a){const c=Array.prototype.slice.call(arguments,3);return a="function"==typeof c[c.length-1]?c.pop():void 0,r=c.length?c.shift():null,o=c.length?c.shift():null,s=c.length?c.shift():null,i=c.length&&c.shift()||{},"function"!=typeof o&&(s=o,o=null),!Array.isArray(e)&&e instanceof Object&&"function"!=typeof e&&"Code"!==e._bsontype&&(e=Object.keys(e)),"function"==typeof r&&(r=r.toString()),"function"==typeof o&&(o=o.toString()),s=null==s||s,g(this.s.topology,T,[this,e,t,n,r,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework."),le.prototype.mapReduce=function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),null==n.out)throw new Error("the out option parameter must be defined, see mongodb docs for possible values");"function"==typeof e&&(e=e.toString()),"function"==typeof t&&(t=t.toString()),"function"==typeof n.finalize&&(n.finalize=n.finalize.toString());const o=new ee(this,e,t,n);return ce(this.s.topology,o,r)},le.prototype.initializeUnorderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,d(this.s.topology,this,e)},le.prototype.initializeOrderedBulkOp=function(e){return null==(e=e||{}).ignoreUndefined&&(e.ignoreUndefined=this.s.options.ignoreUndefined),e.promiseLibrary=this.s.promiseLibrary,m(this.s.topology,this,e)},le.prototype.getLogger=function(){return this.s.db.s.logger},e.exports=le},function(e,t){function n(e){if(!(this instanceof n))return new n(e);this._bsontype="Double",this.value=e}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this._bsontype="Timestamp",this.low_=0|e,this.high_=0|t}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var e=0!==this.high_?this.high_:this.low_,t=31;t>0&&0==(e&1<0},n.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},n.prototype.compare=function(e){if(this.equals(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.subtract(e).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(e){var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=0,l=0,p=0,h=0;return p+=(h+=s+(65535&e.low_))>>>16,h&=65535,l+=(p+=o+c)>>>16,p&=65535,u+=(l+=r+a)>>>16,l&=65535,u+=t+i,u&=65535,n.fromBits(p<<16|h,u<<16|l)},n.prototype.subtract=function(e){return this.add(e.negate())},n.prototype.multiply=function(e){if(this.isZero())return n.ZERO;if(e.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return e.isOdd()?n.MIN_VALUE:n.ZERO;if(e.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&e.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*e.toNumber());var t=this.high_>>>16,r=65535&this.high_,o=this.low_>>>16,s=65535&this.low_,i=e.high_>>>16,a=65535&e.high_,c=e.low_>>>16,u=65535&e.low_,l=0,p=0,h=0,f=0;return h+=(f+=s*u)>>>16,f&=65535,p+=(h+=o*u)>>>16,h&=65535,p+=(h+=s*c)>>>16,h&=65535,l+=(p+=r*u)>>>16,p&=65535,l+=(p+=o*c)>>>16,p&=65535,l+=(p+=s*a)>>>16,p&=65535,l+=t*u+r*c+o*a+s*i,l&=65535,n.fromBits(h<<16|f,l<<16|p)},n.prototype.div=function(e){if(e.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(e.equals(n.ONE)||e.equals(n.NEG_ONE))return n.MIN_VALUE;if(e.equals(n.MIN_VALUE))return n.ONE;var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(n.ZERO))return e.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(e.multiply(t));return t.add(r.div(e))}if(e.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate();if(e.isNegative())return this.div(e.negate()).negate();var o=n.ZERO;for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),i=s<=48?1:Math.pow(2,s-48),a=n.fromNumber(t),c=a.multiply(e);c.isNegative()||c.greaterThan(r);)t-=i,c=(a=n.fromNumber(t)).multiply(e);a.isZero()&&(a=n.ONE),o=o.add(a),r=r.subtract(c)}return o},n.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(e){return n.fromBits(this.low_&e.low_,this.high_&e.high_)},n.prototype.or=function(e){return n.fromBits(this.low_|e.low_,this.high_|e.high_)},n.prototype.xor=function(e){return n.fromBits(this.low_^e.low_,this.high_^e.high_)},n.prototype.shiftLeft=function(e){if(0===(e&=63))return this;var t=this.low_;if(e<32){var r=this.high_;return n.fromBits(t<>>32-e)}return n.fromBits(0,t<>>e|t<<32-e,t>>e)}return n.fromBits(t>>e-32,t>=0?0:-1)},n.prototype.shiftRightUnsigned=function(e){if(0===(e&=63))return this;var t=this.high_;if(e<32){var r=this.low_;return n.fromBits(r>>>e|t<<32-e,t>>>e)}return 32===e?n.fromBits(t,0):n.fromBits(t>>>e-32,0)},n.fromInt=function(e){if(-128<=e&&e<128){var t=n.INT_CACHE_[e];if(t)return t}var r=new n(0|e,e<0?-1:0);return-128<=e&&e<128&&(n.INT_CACHE_[e]=r),r},n.fromNumber=function(e){return isNaN(e)||!isFinite(e)?n.ZERO:e<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:e+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:e<0?n.fromNumber(-e).negate():new n(e%n.TWO_PWR_32_DBL_|0,e/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(e,t){return new n(e,t)},n.fromString=function(e,t){if(0===e.length)throw Error("number format error: empty string");var r=t||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+e);for(var o=n.fromNumber(Math.pow(r,8)),s=n.ZERO,i=0;i>8&255,r[1]=e>>16&255,r[0]=e>>24&255,r[6]=255&s,r[5]=s>>8&255,r[4]=s>>16&255,r[8]=255&t,r[7]=t>>8&255,r[11]=255&n,r[10]=n>>8&255,r[9]=n>>16&255,r},c.prototype.toString=function(e){return this.id&&this.id.copy?this.id.toString("string"==typeof e?e:"hex"):this.toHexString()},c.prototype[r]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(e){return e instanceof c?this.toString()===e.toString():"string"==typeof e&&c.isValid(e)&&12===e.length&&this.id instanceof h?e===this.id.toString("binary"):"string"==typeof e&&c.isValid(e)&&24===e.length?e.toLowerCase()===this.toHexString():"string"==typeof e&&c.isValid(e)&&12===e.length?e===this.id:!(null==e||!(e instanceof c||e.toHexString))&&e.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=e>>8&255,t[1]=e>>16&255,t[0]=e>>24&255,new c(t)};var p=[];for(l=0;l<10;)p[48+l]=l++;for(;l<16;)p[55+l]=p[87+l]=l++;var h=Buffer,f=function(e){return e.toString("hex")};c.createFromHexString=function(e){if(void 0===e||null!=e&&24!==e.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(a)return new c(o.toBuffer(e,"hex"));for(var t=new h(12),n=0,r=0;r<24;)t[n++]=p[e.charCodeAt(r++)]<<4|p[e.charCodeAt(r++)];return new c(t)},c.isValid=function(e){return null!=e&&("number"==typeof e||("string"==typeof e?12===e.length||24===e.length&&i.test(e):e instanceof c||(e instanceof h||"function"==typeof e.toHexString&&(e.id instanceof h||"string"==typeof e.id)&&(12===e.id.length||24===e.id.length&&i.test(e.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=255&e,this.id[2]=e>>8&255,this.id[1]=e>>16&255,this.id[0]=e>>24&255}}),e.exports=c,e.exports.ObjectID=c,e.exports.ObjectId=c},function(e,t){function n(e,t){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=e||"",this.options=t||"";for(var r=0;r=7e3)throw new Error(e+" not a valid Decimal128 string");var M=e.match(o),R=e.match(s),D=e.match(i);if(!M&&!R&&!D||0===e.length)throw new Error(e+" not a valid Decimal128 string");if(M&&M[4]&&void 0===M[2])throw new Error(e+" not a valid Decimal128 string");if("+"!==e[k]&&"-"!==e[k]||(n="-"===e[k++]),!f(e[k])&&"."!==e[k]){if("i"===e[k]||"I"===e[k])return new m(h.toBuffer(n?u:l));if("N"===e[k])return new m(h.toBuffer(c))}for(;f(e[k])||"."===e[k];)if("."!==e[k])O<34&&("0"!==e[k]||y)&&(y||(w=b),y=!0,_[T++]=parseInt(e[k],10),O+=1),y&&(S+=1),d&&(v+=1),b+=1,k+=1;else{if(d)return new m(h.toBuffer(c));d=!0,k+=1}if(d&&!b)throw new Error(e+" not a valid Decimal128 string");if("e"===e[k]||"E"===e[k]){var B=e.substr(++k).match(p);if(!B||!B[2])return new m(h.toBuffer(c));x=parseInt(B[0],10),k+=B[0].length}if(e[k])return new m(h.toBuffer(c));if(E=0,O){if(C=O-1,g=S,0!==x&&1!==g)for(;"0"===e[w+g-1];)g-=1}else E=0,C=0,_[0]=0,S=1,O=1,g=0;for(x<=v&&v-x>16384?x=-6176:x-=v;x>6111;){if((C+=1)-E>34){var P=_.join("");if(P.match(/^0+$/)){x=6111;break}return new m(h.toBuffer(n?u:l))}x-=1}for(;x<-6176||O=5&&(U=1,5===j))for(U=_[C]%2==1,A=w+C+2;A=0&&++_[z]>9;z--)if(_[z]=0,0===z){if(!(x<6111))return new m(h.toBuffer(n?u:l));x+=1,_[z]=1}}if(N=r.fromNumber(0),I=r.fromNumber(0),0===g)N=r.fromNumber(0),I=r.fromNumber(0);else if(C-E<17)for(z=E,I=r.fromNumber(_[z++]),N=new r(0,0);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));else{for(z=E,N=r.fromNumber(_[z++]);z<=C-17;z++)N=(N=N.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]));for(I=r.fromNumber(_[z++]);z<=C;z++)I=(I=I.multiply(r.fromNumber(10))).add(r.fromNumber(_[z]))}var F,W,q,$,H=function(e,t){if(!e&&!t)return{high:r.fromNumber(0),low:r.fromNumber(0)};var n=e.shiftRightUnsigned(32),o=new r(e.getLowBits(),0),s=t.shiftRightUnsigned(32),i=new r(t.getLowBits(),0),a=n.multiply(s),c=n.multiply(i),u=o.multiply(s),l=o.multiply(i);return a=a.add(c.shiftRightUnsigned(32)),c=new r(c.getLowBits(),0).add(u).add(l.shiftRightUnsigned(32)),{high:a=a.add(c.shiftRightUnsigned(32)),low:l=c.shiftLeft(32).add(new r(l.getLowBits(),0))}}(N,r.fromString("100000000000000000"));H.low=H.low.add(I),F=H.low,W=I,q=F.high_>>>0,$=W.high_>>>0,(q<$||q===$&&F.low_>>>0>>0)&&(H.high=H.high.add(r.fromNumber(1))),t=x+a;var V={low:r.fromNumber(0),high:r.fromNumber(0)};H.high.shiftRightUnsigned(49).and(r.fromNumber(1)).equals(r.fromNumber)?(V.high=V.high.or(r.fromNumber(3).shiftLeft(61)),V.high=V.high.or(r.fromNumber(t).and(r.fromNumber(16383).shiftLeft(47))),V.high=V.high.or(H.high.and(r.fromNumber(0x7fffffffffff)))):(V.high=V.high.or(r.fromNumber(16383&t).shiftLeft(49)),V.high=V.high.or(H.high.and(r.fromNumber(562949953421311)))),V.low=H.low,n&&(V.high=V.high.or(r.fromString("9223372036854775808")));var Y=h.allocBuffer(16);return k=0,Y[k++]=255&V.low.low_,Y[k++]=V.low.low_>>8&255,Y[k++]=V.low.low_>>16&255,Y[k++]=V.low.low_>>24&255,Y[k++]=255&V.low.high_,Y[k++]=V.low.high_>>8&255,Y[k++]=V.low.high_>>16&255,Y[k++]=V.low.high_>>24&255,Y[k++]=255&V.high.low_,Y[k++]=V.high.low_>>8&255,Y[k++]=V.high.low_>>16&255,Y[k++]=V.high.low_>>24&255,Y[k++]=255&V.high.high_,Y[k++]=V.high.high_>>8&255,Y[k++]=V.high.high_>>16&255,Y[k++]=V.high.high_>>24&255,new m(Y)};a=6176,m.prototype.toString=function(){for(var e,t,n,o,s,i,c=0,u=new Array(36),l=0;l>26&31)>>3==3){if(30===s)return v.join("")+"Infinity";if(31===s)return"NaN";i=e>>15&16383,f=8+(e>>14&1)}else f=e>>14&7,i=e>>17&16383;if(p=i-a,S.parts[0]=(16383&e)+((15&f)<<14),S.parts[1]=t,S.parts[2]=n,S.parts[3]=o,0===S.parts[0]&&0===S.parts[1]&&0===S.parts[2]&&0===S.parts[3])b=!0;else for(y=3;y>=0;y--){var _=0,O=d(S);if(S=O.quotient,_=O.rem.low_)for(m=8;m>=0;m--)u[9*y+m]=_%10,_=Math.floor(_/10)}if(b)c=1,u[g]=0;else for(c=36,l=0;!u[g];)l++,c-=1,g+=1;if((h=c-1+p)>=34||h<=-7||p>0){for(v.push(u[g++]),(c-=1)&&v.push("."),l=0;l0?v.push("+"+h):v.push(h)}else if(p>=0)for(l=0;l0)for(l=0;l{if(r)return n(r);Object.assign(t,{nonce:s});const i=t.credentials,a=Object.assign({},e,{speculativeAuthenticate:Object.assign(f(o,i,s),{db:i.source})});n(void 0,a)})}auth(e,t){const n=e.response;n&&n.speculativeAuthenticate?d(this.cryptoMethod,n.speculativeAuthenticate,e,t):function(e,t,n){const r=t.connection,o=t.credentials,s=t.nonce,i=o.source,a=f(e,o,s);r.command(i+".$cmd",a,(r,o)=>{const s=v(r,o);if(s)return n(s);d(e,o.result,t,n)})}(this.cryptoMethod,e,t)}}function p(e){return e.replace("=","=3D").replace(",","=2C")}function h(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function f(e,t,n){const r=p(t.username);return{saslStart:1,mechanism:"sha1"===e?"SCRAM-SHA-1":"SCRAM-SHA-256",payload:new c(o.concat([o.from("n,,","utf8"),h(r,n)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}function d(e,t,n,s){const a=n.connection,l=n.credentials,f=n.nonce,d=l.source,w=p(l.username),_=l.password;let O;if("sha256"===e)O=u?u(_):_;else try{O=function(e,t){if("string"!=typeof e)throw new i("username must be a string");if("string"!=typeof t)throw new i("password must be a string");if(0===t.length)throw new i("password cannot be empty");const n=r.createHash("md5");return n.update(`${e}:mongo:${t}`,"utf8"),n.digest("hex")}(w,_)}catch(e){return s(e)}const T=o.isBuffer(t.payload)?new c(t.payload):t.payload,E=m(T.value()),C=parseInt(E.i,10);if(C&&C<4096)return void s(new i("Server returned an invalid iteration count "+C),!1);const x=E.s,A=E.r;if(A.startsWith("nonce"))return void s(new i("Server returned an invalid nonce: "+A),!1);const N="c=biws,r="+A,I=function(e,t,n,o){const s=[e,t.toString("base64"),n].join("_");if(void 0!==g[s])return g[s];const i=r.pbkdf2Sync(e,t,n,S[o],o);b>=200&&(g={},b=0);return g[s]=i,b+=1,i}(O,o.from(x,"base64"),C,e),k=y(e,I,"Client Key"),M=y(e,I,"Server Key"),R=(D=e,B=k,r.createHash(D).update(B).digest());var D,B;const P=[h(w,f),T.value().toString("base64"),N].join(","),L=[N,"p="+function(e,t){o.isBuffer(e)||(e=o.from(e));o.isBuffer(t)||(t=o.from(t));const n=Math.max(e.length,t.length),r=[];for(let o=0;o{const n=v(e,t);if(n)return s(n);const c=t.result,u=m(c.payload.value());if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof r.timingSafeEqual)return r.timingSafeEqual(e,t);let n=0;for(let r=0;r{const n=m(t.s.options);if(n)return e(n);d(t,t.s.url,t.s.options,n=>{if(n)return e(n);e(null,t)})})},y.prototype.logout=c((function(e,t){"function"==typeof e&&(t=e,e={}),"function"==typeof t&&t(null,!0)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient"),y.prototype.close=function(e,t){"function"==typeof e&&(t=e,e=!1);const n=this;return h(this,t,t=>{const r=e=>{if(n.emit("close",n),!(n.topology instanceof f))for(const e of n.s.dbCache)e[1].emit("close",n);n.removeAllListeners("close"),t(e)};null!=n.topology?n.topology.close(e,t=>{const o=n.topology.s.options.autoEncrypter;o?o.teardown(e,e=>r(t||e)):r(t)}):r()})},y.prototype.db=function(e,t){t=t||{},e||(e=this.s.options.dbName);const n=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&!0!==n.returnNonCachedInstance)return this.s.dbCache.get(e);if(n.promiseLibrary=this.s.promiseLibrary,!this.topology)throw new a("MongoClient must be connected before calling MongoClient.prototype.db");const r=new o(e,this.topology,n);return this.s.dbCache.set(e,r),r},y.prototype.isConnected=function(e){return e=e||{},!!this.topology&&this.topology.isConnected(e)},y.connect=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0;const o=new y(e,t=(t=r.length?r.shift():null)||{});return o.connect(n)},y.prototype.startSession=function(e){if(e=Object.assign({explicit:!0},e),!this.topology)throw new a("Must connect to a server before calling this method");if(!this.topology.hasSessionSupport())throw new a("Current topology does not support sessions");return this.topology.startSession(e,this.s.options)},y.prototype.withSession=function(e,t){"function"==typeof e&&(t=e,e=void 0);const n=this.startSession(e);let r=(e,t,o)=>{if(r=()=>{throw new ReferenceError("cleanupHandler was called too many times")},o=Object.assign({throw:!0},o),n.endSession(),e){if(o.throw)throw e;return Promise.reject(e)}};try{const e=t(n);return Promise.resolve(e).then(e=>r(null,e)).catch(e=>r(e,null,{throw:!0}))}catch(e){return r(e,null,{throw:!1})}},y.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new r(this,e,t)},y.prototype.getLogger=function(){return this.s.options.logger},e.exports=y},function(e,t,n){"use strict";const r=n(26),o=n(1).MongoError,s=n(4).maxWireVersion,i=n(1).ReadPreference,a=n(3).Aspect,c=n(3).defineAspects;class u extends r{constructor(e,t,n){if(super(e,n,{fullResponse:!0}),this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:1,this.pipeline=t,this.hasWriteStage=!1,"string"==typeof n.out)this.pipeline=this.pipeline.concat({$out:n.out}),this.hasWriteStage=!0;else if(t.length>0){const e=t[t.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage&&(this.readPreference=i.primary),n.explain&&(this.readConcern||this.writeConcern))throw new o('"explain" cannot be used on an aggregate call with readConcern/writeConcern');if(null!=n.cursor&&"object"!=typeof n.cursor)throw new o("cursor options must be an object")}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const n=this.options,r=s(e),o={aggregate:this.target,pipeline:this.pipeline};this.hasWriteStage&&r<8&&(this.readConcern=null),r>=5&&this.hasWriteStage&&this.writeConcern&&Object.assign(o,{writeConcern:this.writeConcern}),!0===n.bypassDocumentValidation&&(o.bypassDocumentValidation=n.bypassDocumentValidation),"boolean"==typeof n.allowDiskUse&&(o.allowDiskUse=n.allowDiskUse),n.hint&&(o.hint=n.hint),n.explain&&(n.full=!1,o.explain=n.explain),o.cursor=n.cursor||{},n.batchSize&&!this.hasWriteStage&&(o.cursor.batchSize=n.batchSize),super.executeCommand(e,o,t)}}c(u,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyRetryableWrites,s=n(0).applyWriteConcern,i=n(0).decorateWithCollation,a=n(14).executeCommand,c=n(0).formattedOrderClause,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(4).maxWireVersion,h=n(112).MongoError;e.exports=class extends r{constructor(e,t,n,r,o){super(o),this.collection=e,this.query=t,this.sort=n,this.doc=r}execute(e){const t=this.collection,n=this.query,r=c(this.sort),f=this.doc;let d=this.options;const m={findAndModify:t.collectionName,query:n};r&&(m.sort=r),m.new=!!d.new,m.remove=!!d.remove,m.upsert=!!d.upsert;const y=d.projection||d.fields;y&&(m.fields=y),d.arrayFilters&&(m.arrayFilters=d.arrayFilters),f&&!d.remove&&(m.update=f),d.maxTimeMS&&(m.maxTimeMS=d.maxTimeMS),d.serializeFunctions=d.serializeFunctions||t.s.serializeFunctions,d.checkKeys=!1,d=o(d,t.s.db),d=s(d,{db:t.s.db,collection:t},d),d.writeConcern&&(m.writeConcern=d.writeConcern),!0===d.bypassDocumentValidation&&(m.bypassDocumentValidation=d.bypassDocumentValidation),d.readPreference=l.primary;try{i(m,t,d)}catch(t){return e(t,null)}if(d.hint){if(d.writeConcern&&0===d.writeConcern.w||p(t.s.topology)<8)return void e(new h("The current topology does not support a hint on findAndModify commands"));m.hint=d.hint}a(t.s.db,m,d,(t,n)=>t?u(e,t,null):u(e,null,n))}}},function(e,t,n){"use strict";const r=n(10).EventEmitter,o=n(5).inherits,s=n(0).getSingleProperty,i=n(83),a=n(0).handleCallback,c=n(0).filterOptions,u=n(0).toError,l=n(1).ReadPreference,p=n(1).MongoError,h=n(1).ObjectID,f=n(1).Logger,d=n(47),m=n(0).mergeOptionsAndWriteConcern,y=n(0).executeLegacyOperation,g=n(79),b=n(5).deprecate,S=n(0).deprecateOptions,v=n(0).MongoDBNamespace,w=n(80),_=n(29),O=n(36),T=n(82),E=n(14).createListener,C=n(14).ensureIndex,x=n(14).evaluate,A=n(14).profilingInfo,N=n(14).validateDatabaseName,I=n(63),k=n(118),M=n(204),R=n(23),D=n(205),B=n(206),P=n(114),L=n(84).DropCollectionOperation,j=n(84).DropDatabaseOperation,U=n(119),z=n(116),F=n(207),W=n(208),q=n(120),$=n(121),H=n(209),V=n(43),Y=["w","wtimeout","fsync","j","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promoteLongs","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","compression","retryWrites"];function G(e,t,n){if(n=n||{},!(this instanceof G))return new G(e,t,n);r.call(this);const o=n.promiseLibrary||Promise;(n=c(n,Y)).promiseLibrary=o,this.s={dbCache:{},children:[],topology:t,options:n,logger:f("Db",n),bson:t?t.bson:null,readPreference:l.fromOptions(n),bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:-1,parentDb:n.parentDb||null,pkFactory:n.pkFactory||h,nativeParser:n.nativeParser||n.native_parser,promiseLibrary:o,noListener:"boolean"==typeof n.noListener&&n.noListener,readConcern:O.fromOptions(n),writeConcern:_.fromOptions(n),namespace:new v(e)},N(e),s(this,"serverConfig",this.s.topology),s(this,"bufferMaxEntries",this.s.bufferMaxEntries),s(this,"databaseName",this.s.namespace.db),n.parentDb||this.s.noListener||(t.on("error",E(this,"error",this)),t.on("timeout",E(this,"timeout",this)),t.on("close",E(this,"close",this)),t.on("parseError",E(this,"parseError",this)),t.once("open",E(this,"open",this)),t.once("fullsetup",E(this,"fullsetup",this)),t.once("all",E(this,"all",this)),t.on("reconnect",E(this,"reconnect",this)))}o(G,r),Object.defineProperty(G.prototype,"topology",{enumerable:!0,get:function(){return this.s.topology}}),Object.defineProperty(G.prototype,"options",{enumerable:!0,get:function(){return this.s.options}}),Object.defineProperty(G.prototype,"slaveOk",{enumerable:!0,get:function(){return null!=this.s.options.readPreference&&("primary"!==this.s.options.readPreference||"primary"!==this.s.options.readPreference.mode)}}),Object.defineProperty(G.prototype,"readConcern",{enumerable:!0,get:function(){return this.s.readConcern}}),Object.defineProperty(G.prototype,"readPreference",{enumerable:!0,get:function(){return null==this.s.readPreference?l.primary:this.s.readPreference}}),Object.defineProperty(G.prototype,"writeConcern",{enumerable:!0,get:function(){return this.s.writeConcern}}),Object.defineProperty(G.prototype,"namespace",{enumerable:!0,get:function(){return this.s.namespace.toString()}}),G.prototype.command=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},t);const r=new D(this,e,t);return V(this.s.topology,r,n)},G.prototype.aggregate=function(e,t,n){"function"==typeof t&&(n=t,t={}),null==t&&null==n&&(t={});const r=new T(this.s.topology,new I(this,e,t),t);if("function"!=typeof n)return r;n(null,r)},G.prototype.admin=function(){return new(n(122))(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs"];G.prototype.collection=function(e,t,n){if("function"==typeof t&&(n=t,t={}),t=t||{},(t=Object.assign({},t)).promiseLibrary=this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern,this.s.options.ignoreUndefined&&(t.ignoreUndefined=this.s.options.ignoreUndefined),null==(t=m(t,this.s.options,K,!0))||!t.strict)try{const r=new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);return n&&n(null,r),r}catch(e){if(e instanceof p&&n)return n(e);throw e}if("function"!=typeof n)throw u("A callback is required in strict mode. While getting collection "+e);if(this.serverConfig&&this.serverConfig.isDestroyed())return n(new p("topology was destroyed"));const r=Object.assign({},t,{nameOnly:!0});this.listCollections({name:e},r).toArray((r,o)=>{if(null!=r)return a(n,r,null);if(0===o.length)return a(n,u(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(n,null,new d(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(r){return a(n,r,null)}})},G.prototype.createCollection=S({name:"Db.createCollection",deprecatedOptions:["autoIndexId"],optionsIndex:1},(function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).promiseLibrary=t.promiseLibrary||this.s.promiseLibrary,t.readConcern=t.readConcern?new O(t.readConcern.level):this.readConcern;const r=new B(this,e,t);return V(this.s.topology,r,n)})),G.prototype.stats=function(e,t){"function"==typeof e&&(t=e,e={});const n={dbStats:!0};null!=(e=e||{}).scale&&(n.scale=e.scale),null==e.readPreference&&this.s.readPreference&&(e.readPreference=this.s.readPreference);const r=new R(this,e,null,n);return V(this.s.topology,r,t)},G.prototype.listCollections=function(e,t){return e=e||{},t=t||{},new i(this.s.topology,new F(this,e,t),t)},G.prototype.eval=b((function(e,t,n,r){const o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():t,n=o.length&&o.shift()||{},y(this.s.topology,x,[this,e,t,n,r])}),"Db.eval is deprecated as of MongoDB version 3.2"),G.prototype.renameCollection=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),(n=Object.assign({},n,{readPreference:l.PRIMARY})).new_collection=!0;const o=new $(this.collection(e),t,n);return V(this.s.topology,o,r)},G.prototype.dropCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new L(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.dropDatabase=function(e,t){"function"==typeof e&&(t=e,e={});const n=new j(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.collections=function(e,t){"function"==typeof e&&(t=e,e={});const n=new M(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.executeDbAdminCommand=function(e,t,n){"function"==typeof t&&(n=t,t={}),(t=t||{}).readPreference=l.resolve(this,t);const r=new U(this,e,t);return V(this.s.topology,r,n)},G.prototype.createIndex=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n?Object.assign({},n):{};const o=new P(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.ensureIndex=b((function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},y(this.s.topology,C,[this,e,t,n,r])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0"),G.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)},G.prototype.addUser=function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n=n||{},"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null);const o=new k(this,e,t,n);return V(this.s.topology,o,r)},G.prototype.removeUser=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new q(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.setProfilingLevel=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new H(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.profilingInfo=b((function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},y(this.s.topology,A,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly."),G.prototype.profilingLevel=function(e,t){"function"==typeof e&&(t=e,e={});const n=new W(this,e=e||{});return V(this.s.topology,n,t)},G.prototype.indexInformation=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new z(this,e,t=t||{});return V(this.s.topology,r,n)},G.prototype.unref=function(){this.s.topology.unref()},G.prototype.watch=function(e,t){return e=e||[],t=t||{},Array.isArray(e)||(t=e,e=[]),new g(this,e,t)},G.prototype.getLogger=function(){return this.s.logger},G.SYSTEM_NAMESPACE_COLLECTION=w.SYSTEM_NAMESPACE_COLLECTION,G.SYSTEM_INDEX_COLLECTION=w.SYSTEM_INDEX_COLLECTION,G.SYSTEM_PROFILE_COLLECTION=w.SYSTEM_PROFILE_COLLECTION,G.SYSTEM_USER_COLLECTION=w.SYSTEM_USER_COLLECTION,G.SYSTEM_COMMAND_COLLECTION=w.SYSTEM_COMMAND_COLLECTION,G.SYSTEM_JS_COLLECTION=w.SYSTEM_JS_COLLECTION,e.exports=G},function(e,t,n){"use strict";const r=n(1).Server,o=n(25),s=n(32).TopologyBase,i=n(32).Store,a=n(1).MongoError,c=n(0).MAX_JS_INT,u=n(0).translateOptions,l=n(0).filterOptions,p=n(0).mergeOptions;var h=["ha","haInterval","acceptableLatencyMS","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCRL","sslCert","ciphers","ecdhCurve","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","family","loggerLevel","logger","reconnectTries","reconnectInterval","monitoring","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","compression","promiseLibrary","monitorCommands"];class f extends s{constructor(e,t,n){super();const s=(n=l(n,h)).promiseLibrary;var f={force:!1,bufferMaxEntries:"number"==typeof n.bufferMaxEntries?n.bufferMaxEntries:c},d=n.store||new i(this,f);if(-1!==e.indexOf("/"))null!=t&&"object"==typeof t&&(n=t,t=null);else if(null==t)throw a.create({message:"port must be specified",driver:!0});var m="boolean"!=typeof n.auto_reconnect||n.auto_reconnect;m="boolean"==typeof n.autoReconnect?n.autoReconnect:m;var y=p({},{host:e,port:t,disconnectHandler:d,cursorFactory:o,reconnect:m,emitError:"boolean"!=typeof n.emitError||n.emitError,size:"number"==typeof n.poolSize?n.poolSize:5,monitorCommands:"boolean"==typeof n.monitorCommands&&n.monitorCommands});y=u(y,n);var g=n.socketOptions&&Object.keys(n.socketOptions).length>0?n.socketOptions:n;y=u(y,g),this.s={coreTopology:new r(y),sCapabilities:null,clonedOptions:y,reconnect:y.reconnect,emitError:y.emitError,poolSize:y.size,storeOptions:f,store:d,host:e,port:t,options:n,sessionPool:null,sessions:new Set,promiseLibrary:s||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e=this.s.clonedOptions),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,a[e])})),n.s.coreTopology.removeListener("connect",r);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(){n.s.store.flush()},i=function(e){return function(t,r){n.emit(e,t,r)}},a={timeout:r("timeout"),error:r("error"),close:r("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.once("timeout",a.timeout),n.s.coreTopology.once("error",a.error),n.s.coreTopology.once("close",a.close),n.s.coreTopology.once("connect",(function(){["timeout","error","close","destroy"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.once("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("destroy",s),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect",n),n.s.store.execute()})),n.s.coreTopology.on("reconnectFailed",(function(e){n.emit("reconnectFailed",e),n.s.store.flush(e)})),n.s.coreTopology.on("serverDescriptionChanged",i("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",i("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",i("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",i("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",i("serverOpening")),n.s.coreTopology.on("serverClosed",i("serverClosed")),n.s.coreTopology.on("topologyOpening",i("topologyOpening")),n.s.coreTopology.on("topologyClosed",i("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",i("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",i("commandStarted")),n.s.coreTopology.on("commandSucceeded",i("commandSucceeded")),n.s.coreTopology.on("commandFailed",i("commandFailed")),n.s.coreTopology.on("attemptReconnect",i("attemptReconnect")),n.s.coreTopology.on("monitoring",i("monitoring")),n.s.coreTopology.connect(e)}}Object.defineProperty(f.prototype,"poolSize",{enumerable:!0,get:function(){return this.s.coreTopology.connections().length}}),Object.defineProperty(f.prototype,"autoReconnect",{enumerable:!0,get:function(){return this.s.reconnect}}),Object.defineProperty(f.prototype,"host",{enumerable:!0,get:function(){return this.s.host}}),Object.defineProperty(f.prototype,"port",{enumerable:!0,get:function(){return this.s.port}}),e.exports=f},function(e,t,n){"use strict";class r extends Error{constructor(e){super(e),this.name="MongoCryptError",Error.captureStackTrace(this,this.constructor)}}e.exports={debug:function(e){process.env.MONGODB_CRYPT_DEBUG&&console.log(e)},databaseNamespace:function(e){return e.split(".")[0]},collectionNamespace:function(e){return e.split(".").slice(1).join(".")},MongoCryptError:r,promiseOrCallback:function(e,t){if("function"!=typeof e)return new Promise((e,n)=>{t((function(t,r){return null!=t?n(t):arguments.length>2?e(Array.prototype.slice.call(arguments,1)):void e(r)}))});t((function(t){if(null==t)e.apply(this,arguments);else try{e(t)}catch(e){return process.nextTick(()=>{throw e})}}))}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.shuffle=void 0;var r=n(229);function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,s=void 0;try{for(var i,a=e[Symbol.iterator]();!(r=(i=a.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(o)throw s}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return i(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);np()(1,100),w=e=>36e5*Math.floor(e/36e5),_=e=>{const t=(Math.floor(e/1e3).toString(16)+b+(++g).toString(16)).padEnd(24,"0");return new r.ObjectId(t)},O=await y.deleteMany({_id:{$lt:_(Date.now()-6048e5)}});!e&&console.info(`api - Deleted ${O.deletedCount} flights older than 7 days`);const T=w((null!==(t=null===(n=await y.find().sort({_id:-1}).limit(1).next())||void 0===n?void 0:n._id)&&void 0!==t?t:new r.ObjectId).getTimestamp().getTime()),E=(w(Date.now()+S)-T)/36e5;if(!e&&console.info(`api - Generating ${E} hours worth of flights...`),!E)return 0;const C=[...Array(9999)].map((e,t)=>t+1),x="abcdefghijklmnopqrstuvwxyz".split("").slice(0,Object(o.a)().AIRPORT_NUM_OF_GATE_LETTERS).map(e=>[...Array(Object(o.a)().AIRPORT_GATE_NUMBERS_PER_LETTER)].map((t,n)=>`${e}${n+1}`)).flat(),A=[];let N=!1;[...Array(E)].forEach((t,n)=>{if(v()>Object(o.a)().FLIGHT_HOUR_HAS_FLIGHTS_PERCENT)return;const r=T+36e5+36e5*n,s=Object(a.shuffle)(l).slice(0,p()(2,l.length)),i=s.reduce((e,t)=>({...e,[t._id.toHexString()]:f()(u()(C))}),{});!e&&console.info(`api ↳ Generating flights for hour ${r} (${n+1}/${E})`),c.forEach(e=>{const t=Object(a.shuffle)(u()(x)),n=e=>t.push(e),l=()=>{const e=t.shift();if(!e)throw new d.d("ran out of gates");return e},f=[];c.forEach(t=>{e._id.equals(t._id)||v()>Object(o.a)().AIRPORT_PAIR_USED_PERCENT||s.forEach(n=>{N=!N;const o=p()(0,10),s=p()(0,4),u={};let l=p()(60,150),d=p()(5e3,8e3);const m=[...Array(h.seatClasses.length)].map(e=>p()(10,100/h.seatClasses.length)).sort((e,t)=>t-e);m[0]+=100-m.reduce((e,t)=>e+t,0);for(const[e,t]of Object.entries(h.seatClasses))l=p()(l,2*l)+Number(Math.random().toFixed(2)),d=p()(d,2*d),u[t]={total:m[Number(e)],priceDollars:l,priceFfms:d};const y={};let g=1,b=p()(10,150);for(const e of h.allExtras)v()>75||(g=p()(g,2.5*g)+Number(Math.random().toFixed(2)),b=p()(b,2*b),y[e]={priceDollars:g,priceFfms:b});f.push({_id:_(r),bookerKey:N?null:e.chapterKey,type:N?"arrival":"departure",airline:n.name,comingFrom:N?t.shortName:Object(a.shuffle)(c).filter(t=>t.shortName!=e.shortName)[0].shortName,landingAt:e.shortName,departingTo:N?null:t.shortName,flightNumber:n.codePrefix+i[n._id.toHexString()]().toString(),baggage:{checked:{max:o,prices:[...Array(o)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||35))]},[])},carry:{max:s,prices:[...Array(s)].reduce(e=>{const t=e.slice(-1)[0];return[...e,p()(t||0,2*(t||15))]},[])}},ffms:p()(2e3,6e3),seats:u,extras:y})})});const m=e=>{if(!e.stochasticStates)throw new d.d("expected stochastic state to exist");return Object.values(e.stochasticStates).slice(-1)[0]};f.forEach(e=>{let t=0,n=!1;const o="arrival"==e.type,s=p()(r,r+36e5-(o?96e4:186e4));e.stochasticStates={0:{arriveAtReceiver:s,departFromSender:s-p()(72e5,18e6),departFromReceiver:o?null:s+9e5,status:"scheduled",gate:null}};for(let r=1;!n&&r<3;++r){const o={...m(e)};switch(r){case 1:t=o.departFromSender,v()>80?(o.status="cancelled",n=!0):o.status="on time",e.stochasticStates[t.toString()]=o;break;case 2:v()>75&&(t=p()(o.arriveAtReceiver-72e5,o.departFromSender+9e5),o.status="delayed",o.arriveAtReceiver+=p()(3e5,9e5),o.departFromReceiver&&(o.departFromReceiver+=p()(3e5,9e5)),e.stochasticStates[t.toString()]=o);break;default:throw new d.d("unreachable stage encountered (1)")}}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 3 encountered impossible condition");const t=m(e);"cancelled"!=t.status&&(e.stochasticStates[p()(t.arriveAtReceiver-72e5,t.arriveAtReceiver-9e5).toString()]={...t,gate:l()})}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 4 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>50&&(n(r),r=l()),e.stochasticStates[p()(t.arriveAtReceiver-18e5,t.arriveAtReceiver-3e5).toString()]={...t,gate:r,status:"landed"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 5 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let r=t.gate;if(!r)throw new d.d("gate was not predetermined?!");v()>85&&(n(r),r=l()),e.stochasticStates[t.arriveAtReceiver]={...t,gate:r,status:"arrived"}}),f.forEach(e=>{if(!e.stochasticStates)throw new d.d("stage 6-9 encountered impossible condition");const t=m(e);if("cancelled"==t.status)return;let n=0,o=!1;const s="arrival"==e.type;for(let i=6;!o&&i<10;++i){const a={...t};switch(i){case 6:if(!s)continue;n=r+36e5,a.status="past",a.gate=null,o=!0;break;case 7:if(s)throw new d.d("arrival type encountered in departure-only model");n=a.arriveAtReceiver+p()(18e4,6e5),a.status="boarding";break;case 8:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (1)");n=a.departFromReceiver,a.status="departed";break;case 9:if(!a.departFromReceiver)throw new d.d("illegal departure state encountered in model (2)");n=a.departFromReceiver+p()(72e5,18e6),a.status="past",a.gate=null;break;default:throw new d.d("unreachable stage encountered (2)")}e.stochasticStates[n.toString()]=a}}),A.push(...f)})});try{if(!A.length)return 0;!e&&console.info(`api - Committing ${A.length} flights into database...`);const t=await y.insertMany(A);if(!t.result.ok)throw new d.c("flight insertion failed");if(t.insertedCount!=A.length)throw new d.d("assert failed: operation.insertedCount != totalHoursToGenerate");return!e&&console.info("api - Operation completed successfully!"),t.insertedCount}catch(e){throw e instanceof d.b?e:new d.c(e)}}},function(e,t,n){"use strict";if(void 0!==global.Map)e.exports=global.Map,e.exports.Map=global.Map;else{var r=function(e){this._keys=[],this._values={};for(var t=0;t{t.lastIsMasterMS=(new Date).getTime()-n,t.s.pool.isDestroyed()||(o&&(t.ismaster=o.result),t.monitoringProcessId=setTimeout(e(t),t.s.monitoringInterval))})}}}(e),e.s.monitoringInterval)),m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.s.inTopology||m.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}]}),e.s.logger.isInfo()&&e.s.logger.info(o("server %s connected with ismaster [%s]",e.name,JSON.stringify(e.ismaster))),e.emit("connect",e)}else{if(T&&-1!==["close","timeout","error","parseError","reconnectFailed"].indexOf(t)&&(e.s.inTopology||e.emit("topologyOpening",{topologyId:e.id}),delete E[e.id]),"close"===t&&m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}),"reconnectFailed"===t)return e.emit("reconnectFailed",n),void(e.listeners("error").length>0&&e.emit("error",n));if(-1!==["disconnected","connecting"].indexOf(e.s.pool.state)&&e.initialConnect&&-1!==["close","timeout","error","parseError"].indexOf(t))return e.initialConnect=!1,e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,n)));if("reconnect"===t)return m.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:m.getTopologyType(e)}),e.emit(t,e);e.emit(t,n)}}};function k(e){return e.s.pool?e.s.pool.isDestroyed()?new p("server instance pool was destroyed"):void 0:new p("server instance is not connected")}A.prototype.connect=function(e){if(e=e||{},T&&(E[this.id]=this),this.s.pool&&!this.s.pool.isDisconnected()&&!this.s.pool.isDestroyed())throw new p(o("server instance in invalid state %s",this.s.pool.state));this.s.pool=new l(this,Object.assign(this.s.options,e,{bson:this.s.bson})),this.s.pool.on("close",I(this,"close")),this.s.pool.on("error",I(this,"error")),this.s.pool.on("timeout",I(this,"timeout")),this.s.pool.on("parseError",I(this,"parseError")),this.s.pool.on("connect",I(this,"connect")),this.s.pool.on("reconnect",I(this,"reconnect")),this.s.pool.on("reconnectFailed",I(this,"reconnectFailed")),S(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"]),this.s.inTopology||this.emit("topologyOpening",{topologyId:x(this)}),this.emit("serverOpening",{topologyId:x(this),address:this.name}),this.s.pool.connect()},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.getDescription=function(){var e=this.ismaster||{},t={type:m.getTopologyType(this),address:this.name};return e.hosts&&(t.hosts=e.hosts),e.arbiters&&(t.arbiters=e.arbiters),e.passives&&(t.passives=e.passives),e.setName&&(t.setName=e.setName),t},A.prototype.lastIsMaster=function(){return this.ismaster},A.prototype.unref=function(){this.s.pool.unref()},A.prototype.isConnected=function(){return!!this.s.pool&&this.s.pool.isConnected()},A.prototype.isDestroyed=function(){return!!this.s.pool&&this.s.pool.isDestroyed()},A.prototype.command=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var s=function(e,t){if(k(e),t.readPreference&&!(t.readPreference instanceof i))throw new Error("readPreference must be an instance of ReadPreference")}(this,n);return s?r(s):(n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:t,options:c(_,n)}),this.name)),N(this,"command",e,t,n,r)?void 0:v(this,t)?r(new p(`server ${this.name} does not support collation`)):void f.command(this,e,t,n,r))},A.prototype.query=function(e,t,n,r,o){f.query(this,e,t,n,r,o)},A.prototype.getMore=function(e,t,n,r,o){f.getMore(this,e,t,n,r,o)},A.prototype.killCursors=function(e,t,n){f.killCursors(this,e,t,n)},A.prototype.insert=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"insert",e,t,n,r)?void 0:(t=Array.isArray(t)?t:[t],f.insert(this,e,t,n,r))},A.prototype.update=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"update",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.update(this,e,t,n,r))},A.prototype.remove=function(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{});var o=k(this);return o?r(o):N(this,"remove",e,t,n,r)?void 0:v(this,n)?r(new p(`server ${this.name} does not support collation`)):(t=Array.isArray(t)?t:[t],f.remove(this,e,t,n,r))},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},A.prototype.equals=function(e){return"string"==typeof e?this.name.toLowerCase()===e.toLowerCase():!!e.name&&this.name.toLowerCase()===e.name.toLowerCase()},A.prototype.connections=function(){return this.s.pool.allConnections()},A.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0),n(null,this)};var M=["close","error","timeout","parseError","connect"];A.prototype.destroy=function(e,t){if(this._destroyed)"function"==typeof t&&t(null,null);else{"function"==typeof e&&(t=e,e={}),e=e||{};var n=this;if(T&&delete E[this.id],this.monitoringProcessId&&clearTimeout(this.monitoringProcessId),!n.s.pool)return this._destroyed=!0,void("function"==typeof t&&t(null,null));e.emitClose&&n.emit("close",n),e.emitDestroy&&n.emit("destroy",n),M.forEach((function(e){n.s.pool.removeAllListeners(e)})),n.listeners("serverClosed").length>0&&n.emit("serverClosed",{topologyId:x(n),address:n.name}),n.listeners("topologyClosed").length>0&&!n.s.inTopology&&n.emit("topologyClosed",{topologyId:x(n)}),n.s.logger.isDebug()&&n.s.logger.debug(o("destroy called on server %s",n.name)),this.s.pool.destroy(e.force,t),this._destroyed=!0}},e.exports=A},function(e,t,n){"use strict";const r=n(147),o=n(95),s=n(90),i=n(2).MongoError,a=n(2).MongoNetworkError,c=n(2).MongoNetworkTimeoutError,u=n(96).defaultAuthProviders,l=n(30).AuthContext,p=n(93),h=n(4).makeClientMetadata,f=p.MAX_SUPPORTED_WIRE_VERSION,d=p.MAX_SUPPORTED_SERVER_VERSION,m=p.MIN_SUPPORTED_WIRE_VERSION,y=p.MIN_SUPPORTED_SERVER_VERSION;let g;const b=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function S(e,t){const n="string"==typeof t.host?t.host:"localhost";if(-1!==n.indexOf("/"))return{path:n};return{family:e,host:n,port:"number"==typeof t.port?t.port:27017,rejectUnauthorized:!1}}const v=new Set(["error","close","timeout","parseError"]);e.exports=function(e,t,n){"function"==typeof t&&(n=t,t=void 0);const p=e&&e.connectionType?e.connectionType:s;null==g&&(g=u(e.bson)),function(e,t,n,s){const i="boolean"==typeof t.ssl&&t.ssl,u="boolean"!=typeof t.keepAlive||t.keepAlive;let l="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4;const p="boolean"!=typeof t.noDelay||t.noDelay,h="number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:3e4,f="number"==typeof t.socketTimeout?t.socketTimeout:36e4,d="boolean"!=typeof t.rejectUnauthorized||t.rejectUnauthorized;l>f&&(l=Math.round(f/2));let m;const y=function(e,t){e&&m&&m.destroy(),s(e,t)};try{i?(m=o.connect(function(e,t){const n=S(e,t);for(const e in t)null!=t[e]&&-1!==b.indexOf(e)&&(n[e]=t[e]);!1===t.checkServerIdentity?n.checkServerIdentity=function(){}:"function"==typeof t.checkServerIdentity&&(n.checkServerIdentity=t.checkServerIdentity);null==n.servername&&(n.servername=n.host);return n}(e,t)),"function"==typeof m.disableRenegotiation&&m.disableRenegotiation()):m=r.createConnection(S(e,t))}catch(e){return y(e)}m.setKeepAlive(u,l),m.setTimeout(h),m.setNoDelay(p);const g=i?"secureConnect":"connect";let w;function _(e){return t=>{v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.removeListener(g,O),y(function(e,t){switch(e){case"error":return new a(t);case"timeout":return new c("connection timed out");case"close":return new a("connection closed");case"cancel":return new a("connection establishment was cancelled");default:return new a("unknown network error")}}(e,t))}}function O(){if(v.forEach(e=>m.removeAllListeners(e)),w&&n.removeListener("cancel",w),m.authorizationError&&d)return y(m.authorizationError);m.setTimeout(f),y(null,m)}v.forEach(e=>m.once(e,_(e))),n&&(w=_("cancel"),n.once("cancel",w));m.once(g,O)}(void 0!==e.family?e.family:0,e,t,(t,r)=>{t?n(t,r):function(e,t,n){const r=function(t,r){t&&e&&e.destroy(),n(t,r)},o=t.credentials;if(o&&!o.mechanism.match(/DEFAULT/i)&&!g[o.mechanism])return void r(new i(`authMechanism '${o.mechanism}' not supported`));const a=new l(e,o,t);!function(e,t){const n=e.options,r=n.compression&&n.compression.compressors?n.compression.compressors:[],o={ismaster:!0,client:n.metadata||h(n),compression:r},s=e.credentials;if(s){if(s.mechanism.match(/DEFAULT/i)&&s.username)return Object.assign(o,{saslSupportedMechs:`${s.source}.${s.username}`}),void g["scram-sha-256"].prepare(o,e,t);return void g[s.mechanism].prepare(o,e,t)}t(void 0,o)}(a,(n,c)=>{if(n)return r(n);const u=Object.assign({},t);(t.connectTimeoutMS||t.connectionTimeout)&&(u.socketTimeout=t.connectTimeoutMS||t.connectionTimeout);const l=(new Date).getTime();e.command("admin.$cmd",c,u,(n,u)=>{if(n)return void r(n);const p=u.result;if(0===p.ok)return void r(new i(p));const h=function(e,t){const n=e&&"number"==typeof e.maxWireVersion&&e.maxWireVersion>=m,r=e&&"number"==typeof e.minWireVersion&&e.minWireVersion<=f;if(n){if(r)return null;const n=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${f} (MongoDB ${d})`;return new i(n)}const o=`Server at ${t.host}:${t.port} reports maximum wire version ${e.maxWireVersion||0}, but this version of the Node.js Driver requires at least ${m} (MongoDB ${y})`;return new i(o)}(p,t);if(h)r(h);else{if(!function(e){return!(e instanceof s)}(e)&&p.compression){const n=c.compression.filter(e=>-1!==p.compression.indexOf(e));n.length&&(e.agreedCompressor=n[0]),t.compression&&t.compression.zlibCompressionLevel&&(e.zlibCompressionLevel=t.compression.zlibCompressionLevel)}if(e.ismaster=p,e.lastIsMasterMS=(new Date).getTime()-l,p.arbiterOnly||!o)r(void 0,e);else{Object.assign(a,{response:p});const t=o.resolveAuthMechanism(p);g[t.mechanism].auth(a,t=>{if(t)return r(t);r(void 0,e)})}}})})}(new p(r,e),e,n)})}},function(e,t,n){"use strict";function r(e){this._head=0,this._tail=0,this._capacityMask=3,this._list=new Array(4),Array.isArray(e)&&this._fromArray(e)}r.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},r.prototype.get=function(e){return this.peekAt(e)},r.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},r.prototype.peekFront=function(){return this.peek()},r.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(r.prototype,"length",{get:function(){return this.size()}}),r.prototype.size=function(){return this._head===this._tail?0:this._head1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}},r.prototype.push=function(e){if(void 0===e)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._head1e4&&e<=t>>>2&&this._shrinkArray(),n}},r.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var o,s=this._list[t];if(e0;o--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(o=n-1-e;o>0;o--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return s}}},r.prototype.remove=function(e,t){var n,r=e,o=t;if(r===(0|r)&&this._head!==this._tail){var s=this.size(),i=this._list.length;if(!(r>=s||r<-s||t<1)){if(r<0&&(r+=s),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=s)return n=this.toArray(),this.clear(),n;var a;for(r+t>s&&(t=s-r),n=new Array(t),a=0;a0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+i&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+i&this._capacityMask]=void 0;return n}if(r0;a--)this.unshift(this._list[r=r-1+i&this._capacityMask]);for(r=this._head-1+i&this._capacityMask;o>0;)this._list[r=r-1+i&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+i&this._capacityMask,a=s-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+i&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=i>>>2&&this._shrinkArray(),n}}},r.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var o,s,i,a=arguments.length,c=this._list.length,u=2;if(!r||n0&&(this._head=this._head+n+c&this._capacityMask)):(i=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>u;)this.unshift(arguments[--a]);for(o=n;o>0;o--)this.unshift(s[o-1])}else{var l=(s=new Array(r-(n+t))).length;for(o=0;othis._tail){for(t=this._head;t>>=1,this._capacityMask>>>=1},e.exports=r},function(e,t){e.exports=require("dns")},function(e,t,n){"use strict";const r=n(77),o=n(10),s=n(112).isResumableError,i=n(1).MongoError,a=n(25),c=n(4).relayEvents,u=n(4).maxWireVersion,l=n(0).maybePromise,p=n(0).now,h=n(0).calculateDurationInMs,f=n(63),d=Symbol("resumeQueue"),m=["resumeAfter","startAfter","startAtOperationTime","fullDocument"],y=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(m),g={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class b extends a{constructor(e,t,n){super(e,t,n),n=n||{},this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of y)this.options[t]&&(e[t]=this.options[t]);if(this.resumeToken||this.startAtOperationTime)if(["resumeAfter","startAfter","startAtOperationTime"].forEach(t=>delete e[t]),this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else this.startAtOperationTime&&u(this.server)>=7&&(e.startAtOperationTime=this.startAtOperationTime);return e}cacheResumeToken(e){0===this.bufferedCount()&&this.cursorState.postBatchResumeToken?this.resumeToken=this.cursorState.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e,t){const n=t.cursor;n.postBatchResumeToken&&(this.cursorState.postBatchResumeToken=n.postBatchResumeToken,0===n[e].length&&(this.resumeToken=n.postBatchResumeToken))}_initializeCursor(e){super._initializeCursor((t,n)=>{if(t||null==n)return void e(t,n);const r=n.documents[0];null==this.startAtOperationTime&&null==this.resumeAfter&&null==this.startAfter&&u(this.server)>=7&&(this.startAtOperationTime=r.operationTime),this._processBatch("firstBatch",r),this.emit("init",n),this.emit("response"),e(t,n)})}_getMore(e){super._getMore((t,n)=>{t?e(t):(this._processBatch("nextBatch",n),this.emit("more",n),this.emit("response"),e(t,n))})}}function S(e,t){const n={fullDocument:t.fullDocument||"default"};v(n,t,m),e.type===g.CLUSTER&&(n.allChangesForCluster=!0);const r=[{$changeStream:n}].concat(e.pipeline),o=v({},t,y),s=new b(e.topology,new f(e.parent,r,t),o);if(c(s,e,["resumeTokenChanged","end","close"]),e.listenerCount("change")>0&&s.on("data",(function(t){w(e,t)})),s.on("error",(function(t){_(e,t)})),e.pipeDestinations){const t=s.stream(e.streamOptions);for(let n in e.pipeDestinations)t.pipe(n)}return s}function v(e,t,n){return n.forEach(n=>{t[n]&&(e[n]=t[n])}),e}function w(e,t,n){const r=e.cursor;if(null==t&&(e.closed=!0),!e.closed){if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");return n?n(t):e.emit("error",t)}return r.cacheResumeToken(t._id),e.options.startAtOperationTime=void 0,n?n(void 0,t):e.emit("change",t)}n&&n(new i("ChangeStream is closed"))}function _(e,t,n){const r=e.topology,o=e.cursor;if(!e.closed)return o&&s(t,u(o.server))?(e.cursor=void 0,["data","close","end","error"].forEach(e=>o.removeAllListeners(e)),o.close(),void function e(t,n,r){setTimeout(()=>{n&&null==n.start&&(n.start=p());const o=n.start||p(),s=n.timeout||3e4,a=n.readPreference;return t.isConnected({readPreference:a})?r():h(o)>s?r(new i("Timed out waiting for connection")):void e(t,n,r)},500)}(r,{readPreference:o.options.readPreference},t=>{if(t)return c(t);const r=S(e,o.resumeOptions);if(!n)return a(r);r.hasNext(e=>{if(e)return c(e);a(r)})})):n?n(t):e.emit("error",t);function a(t){e.cursor=t,T(e)}function c(t){n||(e.emit("error",t),e.emit("close")),T(e,t),e.closed=!0}n&&n(new i("ChangeStream is closed"))}function O(e,t){e.isClosed()?t(new i("ChangeStream is closed.")):e.cursor?t(void 0,e.cursor):e[d].push(t)}function T(e,t){for(;e[d].length;){const n=e[d].pop();if(e.isClosed()&&!t)return void n(new i("Change Stream is not open."));n(t,e.cursor)}}e.exports=class extends o{constructor(e,t,o){super();const s=n(47),i=n(65),a=n(62);if(this.pipeline=t||[],this.options=o||{},this.parent=e,this.namespace=e.s.namespace,e instanceof s)this.type=g.COLLECTION,this.topology=e.s.db.serverConfig;else if(e instanceof i)this.type=g.DATABASE,this.topology=e.serverConfig;else{if(!(e instanceof a))throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient");this.type=g.CLUSTER,this.topology=e.topology}this.promiseLibrary=e.s.promiseLibrary,!this.options.readPreference&&e.s.readPreference&&(this.options.readPreference=e.s.readPreference),this[d]=new r,this.cursor=S(this,o),this.closed=!1,this.on("newListener",e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this.cursor.on("data",e=>w(this,e))}),this.on("removeListener",e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursor.removeAllListeners("data")})}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.hasNext(e)})})}next(e){return l(this.parent,e,e=>{O(this,(t,n)=>{if(t)return e(t);n.next((t,n)=>{if(t)return this[d].push(()=>this.next(e)),void _(this,t,e);w(this,n,e)})})})}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,e=>{if(this.closed)return e();if(this.closed=!0,!this.cursor)return e();const t=this.cursor;return t.close(n=>(["data","close","end","error"].forEach(e=>t.removeAllListeners(e)),this.cursor=void 0,e(n)))})}pipe(e,t){return this.pipeDestinations||(this.pipeDestinations=[]),this.pipeDestinations.push(e),this.cursor.pipe(e,t)}unpipe(e){return this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1&&this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1),this.cursor.unpipe(e)}stream(e){return this.streamOptions=e,this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}},function(e,t,n){"use strict";e.exports={SYSTEM_NAMESPACE_COLLECTION:"system.namespaces",SYSTEM_INDEX_COLLECTION:"system.indexes",SYSTEM_PROFILE_COLLECTION:"system.profile",SYSTEM_USER_COLLECTION:"system.users",SYSTEM_COMMAND_COLLECTION:"$cmd",SYSTEM_JS_COLLECTION:"system.js"}},function(e,t,n){"use strict";const r=n(1).BSON.Long,o=n(1).MongoError,s=n(1).BSON.ObjectID,i=n(1).BSON,a=n(1).MongoWriteConcernError,c=n(0).toError,u=n(0).handleCallback,l=n(0).applyRetryableWrites,p=n(0).applyWriteConcern,h=n(0).executeLegacyOperation,f=n(0).isPromiseLike,d=n(0).hasAtomicOperators,m=n(4).maxWireVersion,y=new i([i.Binary,i.Code,i.DBRef,i.Decimal128,i.Double,i.Int32,i.Long,i.Map,i.MaxKey,i.MinKey,i.ObjectId,i.BSONRegExp,i.Symbol,i.Timestamp]);class g{constructor(e){this.result=e}get ok(){return this.result.ok}get nInserted(){return this.result.nInserted}get nUpserted(){return this.result.nUpserted}get nMatched(){return this.result.nMatched}get nModified(){return this.result.nModified}get nRemoved(){return this.result.nRemoved}getInsertedIds(){return this.result.insertedIds}getUpsertedIds(){return this.result.upserted}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return ee.multi)),3===e.batch.batchType&&(n.retryWrites=n.retryWrites&&!e.batch.operations.some(e=>0===e.limit)));try{1===e.batch.batchType?this.s.topology.insert(this.s.namespace,e.batch.operations,n,e.resultHandler):2===e.batch.batchType?this.s.topology.update(this.s.namespace,e.batch.operations,n,e.resultHandler):3===e.batch.batchType&&this.s.topology.remove(this.s.namespace,e.batch.operations,n,e.resultHandler)}catch(n){n.ok=0,u(t,null,v(e.batch,this.s.bulkResult,n,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const n=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";return u(e,new _(c({message:n,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null),!0}if(t.getWriteConcernError())return u(e,new _(c(t.getWriteConcernError()),t),null),!0}}Object.defineProperty(T.prototype,"length",{enumerable:!0,get:function(){return this.s.currentIndex}}),e.exports={Batch:class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}},BulkOperationBase:T,bson:y,INSERT:1,UPDATE:2,REMOVE:3,BulkWriteError:_}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(25),s=n(20).CursorState,i=n(5).deprecate;class a extends o{constructor(e,t,n){super(e,t,n)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead())throw r.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw r.create({message:"batchSize requires an integer",driver:!0});return this.operation.options.batchSize=e,this.setCursorBatchSize(e),this}geoNear(e){return this.operation.addToPipeline({$geoNear:e}),this}group(e){return this.operation.addToPipeline({$group:e}),this}limit(e){return this.operation.addToPipeline({$limit:e}),this}match(e){return this.operation.addToPipeline({$match:e}),this}maxTimeMS(e){return this.operation.options.maxTimeMS=e,this}out(e){return this.operation.addToPipeline({$out:e}),this}project(e){return this.operation.addToPipeline({$project:e}),this}lookup(e){return this.operation.addToPipeline({$lookup:e}),this}redact(e){return this.operation.addToPipeline({$redact:e}),this}skip(e){return this.operation.addToPipeline({$skip:e}),this}sort(e){return this.operation.addToPipeline({$sort:e}),this}unwind(e){return this.operation.addToPipeline({$unwind:e}),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,i(a.prototype.geoNear,"The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2."),e.exports=a},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(1).MongoError,s=n(25),i=n(20).CursorState;class a extends s{constructor(e,t,n,r){super(e,t,n,r)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if(this.s.state!==i.INIT)throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:!0});if(e instanceof r)this.options.readPreference=e;else{if("string"!=typeof e)throw new TypeError("Invalid read preference: "+e);this.options.readPreference=new r(e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead())throw o.create({message:"Cursor is closed",driver:!0});if("number"!=typeof e)throw o.create({message:"batchSize requires an integer",driver:!0});return this.cmd.cursor&&(this.cmd.cursor.batchSize=e),this.setCursorBatchSize(e),this}maxTimeMS(e){return this.topology.lastIsMaster().minWireVersion>2&&(this.cmd.maxTimeMS=e),this}getLogger(){return this.logger}}a.prototype.get=a.prototype.toArray,e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback;class a extends o{constructor(e,t){const n=Object.assign({},t,e.s.options);t.session&&(n.session=t.session),super(e,n)}execute(e){super.execute((t,n)=>t?i(e,t):n.ok?i(e,null,!0):void i(e,null,!1))}}s(a,r.WRITE_OPERATION);e.exports={DropOperation:a,DropCollectionOperation:class extends a{constructor(e,t,n){super(e,n),this.name=t,this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}},DropDatabaseOperation:class extends a{_buildCommand(){return{dropDatabase:1}}}}},function(e,t,n){"use strict";let r,o,s;e.exports={loadCollection:function(){return r||(r=n(47)),r},loadCursor:function(){return o||(o=n(25)),o},loadDb:function(){return s||(s=n(65)),s}}},function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=n(228);function s(e){if(!o.existy(e))return null;if(o.not.string(e))throw new TypeError('Expected a string, got "'.concat(r(e),'"'));return e.split(",").map((function(e){var t=e.trim();if(t.includes(":")){var n=t.split(":");if(2===n.length)return n[0]}return t})).find(o.ip)}function i(e){if(e.headers){if(o.ip(e.headers["x-client-ip"]))return e.headers["x-client-ip"];var t=s(e.headers["x-forwarded-for"]);if(o.ip(t))return t;if(o.ip(e.headers["cf-connecting-ip"]))return e.headers["cf-connecting-ip"];if(o.ip(e.headers["fastly-client-ip"]))return e.headers["fastly-client-ip"];if(o.ip(e.headers["true-client-ip"]))return e.headers["true-client-ip"];if(o.ip(e.headers["x-real-ip"]))return e.headers["x-real-ip"];if(o.ip(e.headers["x-cluster-client-ip"]))return e.headers["x-cluster-client-ip"];if(o.ip(e.headers["x-forwarded"]))return e.headers["x-forwarded"];if(o.ip(e.headers["forwarded-for"]))return e.headers["forwarded-for"];if(o.ip(e.headers.forwarded))return e.headers.forwarded}if(o.existy(e.connection)){if(o.ip(e.connection.remoteAddress))return e.connection.remoteAddress;if(o.existy(e.connection.socket)&&o.ip(e.connection.socket.remoteAddress))return e.connection.socket.remoteAddress}return o.existy(e.socket)&&o.ip(e.socket.remoteAddress)?e.socket.remoteAddress:o.existy(e.info)&&o.ip(e.info.remoteAddress)?e.info.remoteAddress:o.existy(e.requestContext)&&o.existy(e.requestContext.identity)&&o.ip(e.requestContext.identity.sourceIp)?e.requestContext.identity.sourceIp:null}e.exports={getClientIpFromXForwardedFor:s,getClientIp:i,mw:function(e){var t=o.not.existy(e)?{}:e;if(o.not.object(t))throw new TypeError("Options must be an object!");var n=t.attributeName||"clientIp";return function(e,t,r){var o=i(e);Object.defineProperty(e,n,{get:function(){return o},configurable:!0}),r()}}}},function(e,t,n){"use strict";const r=n(230),o=n(131),s=n(231);function i(e,t){switch(o(e)){case"object":return function(e,t){if("function"==typeof t)return t(e);if(t||s(e)){const n=new e.constructor;for(let r in e)n[r]=i(e[r],t);return n}return e}(e,t);case"array":return function(e,t){const n=new e.constructor(e.length);for(let r=0;r{if(r)return void e.emit("error",r);if(o.length!==n.length)return void e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));const s=n.opCode===m?u:c;e.emit("message",new s(e.bson,t,n,o,e.responseOptions),e)})}e.exports=class extends r{constructor(e,t){if(super(),!(t=t||{}).bson)throw new TypeError("must pass in valid bson parser");this.id=v++,this.options=t,this.logger=f("Connection",t),this.bson=t.bson,this.tag=t.tag,this.maxBsonMessageSize=t.maxBsonMessageSize||67108864,this.port=t.port||27017,this.host=t.host||"localhost",this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.keepAlive="boolean"!=typeof t.keepAlive||t.keepAlive,this.keepAliveInitialDelay="number"==typeof t.keepAliveInitialDelay?t.keepAliveInitialDelay:12e4,this.connectionTimeout="number"==typeof t.connectionTimeout?t.connectionTimeout:3e4,this.keepAliveInitialDelay>this.socketTimeout&&(this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)),this.logger.isDebug()&&this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(w,t))}]`),this.responseOptions={promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers},this.flushing=!1,this.queue=[],this.writeStream=null,this.destroyed=!1,this.timedOut=!1;const n=o.createHash("sha1");var r,i,a;n.update(this.address),this.hashedName=n.digest("hex"),this.workItems=[],this.socket=e,this.socket.once("error",(r=this,function(e){O&&C(r.id),r.logger.isDebug()&&r.logger.debug(`connection ${r.id} for [${r.address}] errored out with [${JSON.stringify(e)}]`),r.emit("error",new l(e),r)})),this.socket.once("timeout",function(e){return function(){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} for [${e.address}] timed out`),e.timedOut=!0,e.emit("timeout",new p(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:null==e.ismaster}),e)}}(this)),this.socket.once("close",function(e){return function(t){O&&C(e.id),e.logger.isDebug()&&e.logger.debug(`connection ${e.id} with for [${e.address}] closed`),t||e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}(this)),this.socket.on("data",function(e){return function(t){for(;t.length>0;)if(e.bytesRead>0&&e.sizeOfMessage>0){const n=e.sizeOfMessage-e.bytesRead;if(n>t.length)t.copy(e.buffer,e.bytesRead),e.bytesRead=e.bytesRead+t.length,t=g.alloc(0);else{t.copy(e.buffer,e.bytesRead,0,n),t=t.slice(n);const r=e.buffer;e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,x(e,r)}}else if(null!=e.stubBuffer&&e.stubBuffer.length>0)if(e.stubBuffer.length+t.length>4){const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=n,e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null}else{const n=g.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(n,0),t.copy(n,e.stubBuffer.length),t=g.alloc(0)}else if(t.length>4){const n=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(n<0||n>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:n,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};return void e.emit("parseError",t,e)}if(n>4&&nt.length)e.buffer=g.alloc(n),t.copy(e.buffer,0),e.bytesRead=t.length,e.sizeOfMessage=n,e.stubBuffer=null,t=g.alloc(0);else if(n>4&&ne.maxBsonMessageSize){const r={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:n,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",r,e),e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=g.alloc(0)}else{const r=t.slice(0,n);e.buffer=null,e.sizeOfMessage=0,e.bytesRead=0,e.stubBuffer=null,t=t.slice(n),x(e,r)}}else e.stubBuffer=g.alloc(t.length),t.copy(e.stubBuffer,0),t=g.alloc(0)}}(this)),O&&(i=this.id,a=this,T[i]=a,_&&_.addConnection(i,a))}setSocketTimeout(e){this.socket&&this.socket.setTimeout(e)}resetSocketTimeout(){this.socket&&this.socket.setTimeout(this.socketTimeout)}static enableConnectionAccounting(e){e&&(_=e),O=!0,T={}}static disableConnectionAccounting(){O=!1,_=void 0}static connections(){return T}get address(){return`${this.host}:${this.port}`}unref(){null!=this.socket?this.socket.unref():this.once("connect",()=>this.socket.unref())}flush(e){for(;this.workItems.length>0;){const t=this.workItems.shift();t.cb&&t.cb(e)}}destroy(e,t){if("function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),O&&C(this.id),null!=this.socket)return e.force||this.timedOut?(this.socket.destroy(),this.destroyed=!0,void("function"==typeof t&&t(null,null))):void this.socket.end(e=>{this.destroyed=!0,"function"==typeof t&&t(e,null)});this.destroyed=!0}write(e){if(this.logger.isDebug())if(Array.isArray(e))for(let t=0;t{};function u(e,t){r(e,t),r=c}function l(e){o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),null==e&&(e=new h(`runCommand failed for connection to '${o.address}'`)),o.on("error",c),u(e)}function p(e){if(e.responseTo!==a.requestId)return;o.resetSocketTimeout(),E.forEach(e=>o.removeListener(e,l)),o.removeListener("message",p),e.parse({promoteValues:!0});const t=e.documents[0];0===t.ok||t.$err||t.errmsg||t.code?u(new h(t)):u(void 0,new S(t,this,e))}o.setSocketTimeout(s),E.forEach(e=>o.once(e,l)),o.on("message",p),o.write(a.toBin())}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(34).ServerDescription,s=n(93),i=n(15).TopologyType,a=s.MIN_SUPPORTED_SERVER_VERSION,c=s.MAX_SUPPORTED_SERVER_VERSION,u=s.MIN_SUPPORTED_WIRE_VERSION,l=s.MAX_SUPPORTED_WIRE_VERSION;class p{constructor(e,t,n,o,s,p,h){h=h||{},this.type=e||i.Unknown,this.setName=n||null,this.maxSetVersion=o||null,this.maxElectionId=s||null,this.servers=t||new Map,this.stale=!1,this.compatible=!0,this.compatibilityError=null,this.logicalSessionTimeoutMinutes=null,this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0,this.localThresholdMS=h.localThresholdMS||0,this.commonWireVersion=p||null,Object.defineProperty(this,"options",{value:h,enumberable:!1});for(const e of this.servers.values())if(e.type!==r.Unknown&&(e.minWireVersion>l&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${c})`),e.maxWireVersione.isReadable);this.logicalSessionTimeoutMinutes=f.reduce((e,t)=>null==t.logicalSessionTimeoutMinutes?null:null==e?t.logicalSessionTimeoutMinutes:Math.min(e,t.logicalSessionTimeoutMinutes),null)}updateFromSrvPollingEvent(e){const t=e.addresses(),n=new Map(this.servers);for(const e of this.servers)t.has(e[0])?t.delete(e[0]):n.delete(e[0]);if(n.size===this.servers.size&&0===t.size)return this;for(const e of t)n.set(e,new o(e));return new p(this.type,n,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,this.options,null)}update(e){const t=e.address;let n=this.type,s=this.setName,a=this.maxSetVersion,c=this.maxElectionId,u=this.commonWireVersion;e.setName&&s&&e.setName!==s&&(e=new o(t,null));const l=e.type;let d=new Map(this.servers);if(0!==e.maxWireVersion&&(u=null==u?e.maxWireVersion:Math.min(u,e.maxWireVersion)),d.set(t,e),n===i.Single)return new p(i.Single,d,s,a,c,u,this.options);if(n===i.Unknown&&(l===r.Standalone&&1!==this.servers.size?d.delete(t):n=function(e){if(e===r.Standalone)return i.Single;if(e===r.Mongos)return i.Sharded;if(e===r.RSPrimary)return i.ReplicaSetWithPrimary;if(e===r.RSGhost||e===r.Unknown)return i.Unknown;return i.ReplicaSetNoPrimary}(l)),n===i.Sharded&&-1===[r.Mongos,r.Unknown].indexOf(l)&&d.delete(t),n===i.ReplicaSetNoPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0&&d.delete(t),l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else if([r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0){const t=function(e,t,n){let r=i.ReplicaSetNoPrimary;if((t=t||n.setName)!==n.setName)return e.delete(n.address),[r,t];n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))}),n.me&&n.address!==n.me&&e.delete(n.address);return[r,t]}(d,s,e);n=t[0],s=t[1]}if(n===i.ReplicaSetWithPrimary)if([r.Standalone,r.Mongos].indexOf(l)>=0)d.delete(t),n=f(d);else if(l===r.RSPrimary){const t=h(d,s,e,a,c);n=t[0],s=t[1],a=t[2],c=t[3]}else n=[r.RSSecondary,r.RSArbiter,r.RSOther].indexOf(l)>=0?function(e,t,n){if(null==t)throw new TypeError("setName is required");(t!==n.setName||n.me&&n.address!==n.me)&&e.delete(n.address);return f(e)}(d,s,e):f(d);return new p(n,d,s,a,c,u,this.options)}get error(){const e=Array.from(this.servers.values()).filter(e=>e.error);if(e.length>0)return e[0].error}get hasKnownServers(){return Array.from(this.servers.values()).some(e=>e.type!==r.Unknown)}get hasDataBearingServers(){return Array.from(this.servers.values()).some(e=>e.isDataBearing)}hasServer(e){return this.servers.has(e)}}function h(e,t,n,s,i){if((t=t||n.setName)!==n.setName)return e.delete(n.address),[f(e),t,s,i];const a=n.electionId?n.electionId:null;if(n.setVersion&&a){if(s&&i&&(s>n.setVersion||function(e,t){if(null==e)return-1;if(null==t)return 1;if(e.id instanceof Buffer&&t.id instanceof Buffer){const n=e.id,r=t.id;return n.compare(r)}const n=e.toString(),r=t.toString();return n.localeCompare(r)}(i,a)>0))return e.set(n.address,new o(n.address)),[f(e),t,s,i];i=n.electionId}null!=n.setVersion&&(null==s||n.setVersion>s)&&(s=n.setVersion);for(const t of e.keys()){const s=e.get(t);if(s.type===r.RSPrimary&&s.address!==n.address){e.set(t,new o(s.address));break}}n.allHosts.forEach(t=>{e.has(t)||e.set(t,new o(t))});const c=Array.from(e.keys()),u=n.allHosts;return c.filter(e=>-1===u.indexOf(e)).forEach(t=>{e.delete(t)}),[f(e),t,s,i]}function f(e){for(const t of e.keys())if(e.get(t).type===r.RSPrimary)return i.ReplicaSetWithPrimary;return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:p}},function(e,t,n){"use strict";t.asyncIterator=function(){const e=this;return{next:function(){return Promise.resolve().then(()=>e.next()).then(t=>t?{value:t,done:!1}:e.close().then(()=>({value:t,done:!0})))}}}},function(e,t,n){"use strict";e.exports={MIN_SUPPORTED_SERVER_VERSION:"2.6",MAX_SUPPORTED_SERVER_VERSION:"4.4",MIN_SUPPORTED_WIRE_VERSION:2,MAX_SUPPORTED_WIRE_VERSION:9}},function(e,t,n){"use strict";const r=n(35).Msg,o=n(22).KillCursor,s=n(22).GetMore,i=n(0).calculateDurationInMs,a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]),c=e=>Object.keys(e)[0],u=e=>e.ns,l=e=>e.ns.split(".")[0],p=e=>e.ns.split(".")[1],h=e=>e.options?`${e.options.host}:${e.options.port}`:e.address,f=(e,t)=>a.has(e)?{}:t,d={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},m={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"},y=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"],g=e=>{if(e instanceof s)return{getMore:e.cursorId,collection:p(e),batchSize:e.numberToReturn};if(e instanceof o)return{killCursors:p(e),cursors:e.cursorIds};if(e instanceof r)return e.command;if(e.query&&e.query.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:p(e)},Object.keys(d).forEach(n=>{void 0!==e.query[n]&&(t[d[n]]=e.query[n])})),Object.keys(m).forEach(n=>{void 0!==e[n]&&(t[m[n]]=e[n])}),y.forEach(n=>{e[n]&&(t[n]=e[n])}),void 0!==e.pre32Limit&&(t.limit=e.pre32Limit),e.query.$explain?{explain:t}:t}return e.query?e.query:e},b=(e,t)=>e instanceof s?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),nextBatch:t.message.documents}}:e instanceof o?{ok:1,cursorsUnknown:e.cursorIds}:e.query&&void 0!==e.query.$query?{ok:1,cursor:{id:t.message.cursorId,ns:u(e),firstBatch:t.message.documents}}:t&&t.result?t.result:t,S=e=>{if((e=>e.s&&e.queue)(e))return{connectionId:h(e)};const t=e;return{address:t.address,connectionId:t.id}};e.exports={CommandStartedEvent:class{constructor(e,t){const n=g(t),r=c(n),o=S(e);a.has(r)&&(this.commandObj={},this.commandObj[r]=!0),Object.assign(this,o,{requestId:t.requestId,databaseName:l(t),commandName:r,command:n})}},CommandSucceededEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),reply:f(s,b(t,n))})}},CommandFailedEvent:class{constructor(e,t,n,r){const o=g(t),s=c(o),a=S(e);Object.assign(this,a,{requestId:t.requestId,commandName:s,duration:i(r),failure:f(s,n)})}}}},function(e,t){e.exports=require("tls")},function(e,t,n){"use strict";const r=n(97),o=n(98),s=n(99),i=n(100),a=n(58).ScramSHA1,c=n(58).ScramSHA256,u=n(152);e.exports={defaultAuthProviders:function(e){return{"mongodb-aws":new u(e),mongocr:new r(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new c(e)}}}},function(e,t,n){"use strict";const r=n(21),o=n(30).AuthProvider;e.exports=class extends o{auth(e,t){const n=e.connection,o=e.credentials,s=o.username,i=o.password,a=o.source;n.command(a+".$cmd",{getnonce:1},(e,o)=>{let c=null,u=null;if(null==e){c=o.result.nonce;let e=r.createHash("md5");e.update(s+":mongo:"+i,"utf8");const t=e.digest("hex");e=r.createHash("md5"),e.update(c+s+t,"utf8"),u=e.digest("hex")}const l={authenticate:1,user:s,nonce:c,key:u};n.command(a+".$cmd",l,t)})}}},function(e,t,n){"use strict";const r=n(30).AuthProvider;function o(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&Object.apply(t,{user:e.username}),t}e.exports=class extends r{prepare(e,t,n){const r=t.credentials;Object.assign(e,{speculativeAuthenticate:o(r)}),n(void 0,e)}auth(e,t){const n=e.connection,r=e.credentials;if(e.response.speculativeAuthenticate)return t();n.command("$external.$cmd",o(r),t)}}},function(e,t,n){"use strict";const r=n(11).retrieveBSON,o=n(30).AuthProvider,s=r().Binary;e.exports=class extends o{auth(e,t){const n=e.connection,r=e.credentials,o=r.username,i=r.password,a={saslStart:1,mechanism:"PLAIN",payload:new s(`\0${o}\0${i}`),autoAuthorize:1};n.command("$external.$cmd",a,t)}}},function(e,t,n){"use strict";const r=n(30).AuthProvider,o=n(4).retrieveKerberos;let s;e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(null==s)try{s=o()}catch(e){return t(e,null)}const i=r.username,a=r.password,c=r.mechanismProperties,u=c.gssapiservicename||c.gssapiServiceName||"mongodb",l=new(0,s.processes.MongoAuthProcess)(n.host,n.port,u,c);l.init(i,a,e=>{if(e)return t(e,!1);l.transition("",(e,r)=>{if(e)return t(e,!1);const o={saslStart:1,mechanism:"GSSAPI",payload:r,autoAuthorize:1};n.command("$external.$cmd",o,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,r)=>{if(e)return t(e,!1);const o=r.result;l.transition(o.payload,(e,r)=>{if(e)return t(e,!1);const s={saslContinue:1,conversationId:o.conversationId,payload:r};n.command("$external.$cmd",s,(e,n)=>{if(e)return t(e,!1);const r=n.result;l.transition(null,e=>{if(e)return t(e,null);t(null,r)})})})})})})})})}}},function(e,t,n){"use strict";function r(e){if(e){if(Array.isArray(e.saslSupportedMechs))return e.saslSupportedMechs.indexOf("SCRAM-SHA-256")>=0?"scram-sha-256":"scram-sha-1";if(e.maxWireVersion>=3)return"scram-sha-1"}return"mongocr"}class o{constructor(e){e=e||{},this.username=e.username,this.password=e.password,this.source=e.source||e.db,this.mechanism=e.mechanism||"default",this.mechanismProperties=e.mechanismProperties||{},this.mechanism.match(/MONGODB-AWS/i)&&(null==this.username&&process.env.AWS_ACCESS_KEY_ID&&(this.username=process.env.AWS_ACCESS_KEY_ID),null==this.password&&process.env.AWS_SECRET_ACCESS_KEY&&(this.password=process.env.AWS_SECRET_ACCESS_KEY),null==this.mechanismProperties.AWS_SESSION_TOKEN&&process.env.AWS_SESSION_TOKEN&&(this.mechanismProperties.AWS_SESSION_TOKEN=process.env.AWS_SESSION_TOKEN)),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new o({username:this.username,password:this.password,source:this.source,mechanism:r(e),mechanismProperties:this.mechanismProperties}):this}}e.exports={MongoCredentials:o}},function(e,t){e.exports=require("querystring")},function(e,t,n){"use strict";const r=n(156);e.exports={insert:function(e,t,n,o,s){r(e,"insert","documents",t,n,o,s)},update:function(e,t,n,o,s){r(e,"update","updates",t,n,o,s)},remove:function(e,t,n,o,s){r(e,"delete","deletes",t,n,o,s)},killCursors:n(157),getMore:n(158),query:n(159),command:n(42)}},function(e,t,n){"use strict";e.exports={ServerDescriptionChangedEvent:class{constructor(e,t,n,r){Object.assign(this,{topologyId:e,address:t,previousDescription:n,newDescription:r})}},ServerOpeningEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},ServerClosedEvent:class{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}},TopologyDescriptionChangedEvent:class{constructor(e,t,n){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:n})}},TopologyOpeningEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},TopologyClosedEvent:class{constructor(e){Object.assign(this,{topologyId:e})}},ServerHeartbeatStartedEvent:class{constructor(e){Object.assign(this,{connectionId:e})}},ServerHeartbeatSucceededEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,reply:t})}},ServerHeartbeatFailedEvent:class{constructor(e,t,n){Object.assign(this,{connectionId:n,duration:e,failure:t})}}}},function(e,t,n){"use strict";const r=n(10),o=n(166),s=n(2).MongoError,i=n(2).MongoNetworkError,a=n(2).MongoNetworkTimeoutError,c=n(2).MongoWriteConcernError,u=n(74),l=n(174).StreamDescription,p=n(103),h=n(94),f=n(31).updateSessionFromResponse,d=n(4).uuidV4,m=n(0).now,y=n(0).calculateDurationInMs,g=Symbol("stream"),b=Symbol("queue"),S=Symbol("messageStream"),v=Symbol("generation"),w=Symbol("lastUseTime"),_=Symbol("clusterTime"),O=Symbol("description"),T=Symbol("ismaster"),E=Symbol("autoEncrypter");function C(e){const t={description:e.description,clusterTime:e[_],s:{bson:e.bson,pool:{write:x.bind(e),isConnected:()=>!0}}};return e[E]&&(t.autoEncrypter=e[E]),t}function x(e,t,n){"function"==typeof t&&(n=t),t=t||{};const r={requestId:e.requestId,cb:n,session:t.session,fullResult:"boolean"==typeof t.fullResult&&t.fullResult,noResponse:"boolean"==typeof t.noResponse&&t.noResponse,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:"boolean"!=typeof t.promoteLongs||t.promoteLongs,promoteValues:"boolean"!=typeof t.promoteValues||t.promoteValues,promoteBuffers:"boolean"==typeof t.promoteBuffers&&t.promoteBuffers,raw:"boolean"==typeof t.raw&&t.raw};this[O]&&this[O].compressor&&(r.agreedCompressor=this[O].compressor,this[O].zlibCompressionLevel&&(r.zlibCompressionLevel=this[O].zlibCompressionLevel)),"number"==typeof t.socketTimeout&&(r.socketTimeoutOverride=!0,this[g].setTimeout(t.socketTimeout)),this.monitorCommands&&(this.emit("commandStarted",new h.CommandStartedEvent(this,e)),r.started=m(),r.cb=(t,o)=>{t?this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,r.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,r.started)):this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,r.started)),"function"==typeof n&&n(t,o)}),r.noResponse||this[b].set(r.requestId,r);try{this[S].writeCommand(e,r)}catch(e){if(!r.noResponse)return this[b].delete(r.requestId),void r.cb(e)}r.noResponse&&r.cb()}e.exports={Connection:class extends r{constructor(e,t){var n;super(t),this.id=t.id,this.address=function(e){if("function"==typeof e.address)return`${e.remoteAddress}:${e.remotePort}`;return d().toString("hex")}(e),this.bson=t.bson,this.socketTimeout="number"==typeof t.socketTimeout?t.socketTimeout:36e4,this.monitorCommands="boolean"==typeof t.monitorCommands&&t.monitorCommands,this.closed=!1,this.destroyed=!1,this[O]=new l(this.address,t),this[v]=t.generation,this[w]=m(),t.autoEncrypter&&(this[E]=t.autoEncrypter),this[b]=new Map,this[S]=new o(t),this[S].on("message",(n=this,function(e){if(n.emit("message",e),!n[b].has(e.responseTo))return;const t=n[b].get(e.responseTo),r=t.cb;n[b].delete(e.responseTo),e.moreToCome?n[b].set(e.requestId,t):t.socketTimeoutOverride&&n[g].setTimeout(n.socketTimeout);try{e.parse(t)}catch(e){return void r(new s(e))}if(e.documents[0]){const o=e.documents[0],i=t.session;if(i&&f(i,o),o.$clusterTime&&(n[_]=o.$clusterTime,n.emit("clusterTimeReceived",o.$clusterTime)),t.command){if(o.writeConcernError)return void r(new c(o.writeConcernError,o));if(0===o.ok||o.$err||o.errmsg||o.code)return void r(new s(o))}}r(void 0,new u(t.fullResult?e:e.documents[0],n,e))})),this[g]=e,e.on("error",()=>{}),e.on("close",()=>{this.closed||(this.closed=!0,this[b].forEach(e=>e.cb(new i(`connection ${this.id} to ${this.address} closed`))),this[b].clear(),this.emit("close"))}),e.on("timeout",()=>{this.closed||(e.destroy(),this.closed=!0,this[b].forEach(e=>e.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:null==this[T]}))),this[b].clear(),this.emit("close"))}),e.pipe(this[S]),this[S].pipe(e)}get description(){return this[O]}get ismaster(){return this[T]}set ismaster(e){this[O].receiveResponse(e),this[T]=e}get generation(){return this[v]||0}get idleTime(){return y(this[w])}get clusterTime(){return this[_]}get stream(){return this[g]}markAvailable(){this[w]=m()}destroy(e,t){return"function"==typeof e&&(t=e,e={}),e=Object.assign({force:!1},e),null==this[g]||this.destroyed?(this.destroyed=!0,void("function"==typeof t&&t())):e.force?(this[g].destroy(),this.destroyed=!0,void("function"==typeof t&&t())):void this[g].end(e=>{this.destroyed=!0,"function"==typeof t&&t(e)})}command(e,t,n,r){p.command(C(this),e,t,n,r)}query(e,t,n,r,o){p.query(C(this),e,t,n,r,o)}getMore(e,t,n,r,o){p.getMore(C(this),e,t,n,r,o)}killCursors(e,t,n){p.killCursors(C(this),e,t,n)}insert(e,t,n,r){p.insert(C(this),e,t,n,r)}update(e,t,n,r){p.update(C(this),e,t,n,r)}remove(e,t,n,r){p.remove(C(this),e,t,n,r)}}}},function(e,t,n){"use strict";var r=n(60);e.exports=b;var o,s=n(169);b.ReadableState=g;n(10).EventEmitter;var i=function(e,t){return e.listeners(t).length},a=n(107),c=n(16).Buffer,u=global.Uint8Array||function(){};var l=Object.create(n(44));l.inherits=n(45);var p=n(5),h=void 0;h=p&&p.debuglog?p.debuglog("stream"):function(){};var f,d=n(171),m=n(108);l.inherits(b,a);var y=["error","close","destroy","pause","resume"];function g(e,t){e=e||{};var r=t instanceof(o=o||n(37));this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var s=e.highWaterMark,i=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=s||0===s?s:r&&(i||0===i)?i:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=n(110).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(37),!(this instanceof b))return new b(e);this._readableState=new g(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),a.call(this)}function S(e,t,n,r,o){var s,i=e._readableState;null===t?(i.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,_(e)}(e,i)):(o||(s=function(e,t){var n;r=t,c.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var r;return n}(i,t)),s?e.emit("error",s):i.objectMode||t&&t.length>0?("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r?i.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):v(e,i,t,!0):i.ended?e.emit("error",new Error("stream.push() after EOF")):(i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?v(e,i,t,!1):T(e,i)):v(e,i,t,!1))):r||(i.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function _(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(h("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(O,e):O(e))}function O(e){h("emit readable"),e.emit("readable"),A(e)}function T(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(E,e,t))}function E(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var r;es.length?s.length:e;if(i===s.length?o+=s:o+=s.slice(0,e),0===(e-=i)){i===s.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(i));break}++r}return t.length-=r,o}(e,t):function(e,t){var n=c.allocUnsafe(e),r=t.head,o=1;r.data.copy(n),e-=r.data.length;for(;r=r.next;){var s=r.data,i=e>s.length?s.length:e;if(s.copy(n,n.length-e,0,i),0===(e-=i)){i===s.length?(++o,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(i));break}++o}return t.length-=o,n}(e,t);return r}(e,t.buffer,t.decoder),n);var n}function I(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(k,t,e))}function k(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function M(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return h("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?I(this):_(this),null;if(0===(e=w(e,t))&&t.ended)return 0===t.length&&I(this),null;var r,o=t.needReadable;return h("need readable",o),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&I(this)),null!==r&&this.emit("data",r),r},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,h("pipe count=%d opts=%j",o.pipesCount,t);var a=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr?u:b;function c(t,r){h("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,h("cleanup"),e.removeListener("close",y),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",d),p=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){h("onend"),e.end()}o.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",c);var l=function(e){return function(){var t=e._readableState;h("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,A(e))}}(n);e.on("drain",l);var p=!1;var f=!1;function d(t){h("ondata"),f=!1,!1!==e.write(t)||f||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==M(o.pipes,e))&&!p&&(h("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,f=!0),n.pause())}function m(t){h("onerror",t),b(),e.removeListener("error",m),0===i(e,"error")&&e.emit("error",t)}function y(){e.removeListener("finish",g),b()}function g(){h("onfinish"),e.removeListener("close",y),b()}function b(){h("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",y),e.once("finish",g),e.emit("pipe",n),o.flowing||(h("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s-1?setImmediate:r.nextTick;y.WritableState=m;var a=Object.create(n(44));a.inherits=n(45);var c={deprecate:n(172)},u=n(107),l=n(16).Buffer,p=global.Uint8Array||function(){};var h,f=n(108);function d(){}function m(e,t){s=s||n(37),e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode,a&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var c=e.highWaterMark,u=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=c||0===c?c:a&&(u||0===u)?u:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var p=!1===e.decodeStrings;this.decodeStrings=!p,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,o=n.sync,s=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,o,s){--t.pendingcb,n?(r.nextTick(s,o),r.nextTick(_,e,t),e._writableState.errorEmitted=!0,e.emit("error",o)):(s(o),e._writableState.errorEmitted=!0,e.emit("error",o),_(e,t))}(e,n,o,t,s);else{var a=v(n);a||n.corked||n.bufferProcessing||!n.bufferedRequest||S(e,n),o?i(b,e,n,a,s):b(e,n,a,s)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function y(e){if(s=s||n(37),!(h.call(y,this)||this instanceof s))return new y(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),u.call(this)}function g(e,t,n,r,o,s,i){t.writelen=r,t.writecb=i,t.writing=!0,t.sync=!0,n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function b(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),_(e,t)}function S(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),i=t.corkedRequestsFree;i.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,g(e,t,!0,t.length,s,"",i.finish),t.pendingcb++,t.lastBufferedRequest=null,i.next?(t.corkedRequestsFree=i.next,i.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,p=n.callback;if(g(e,t,!1,t.objectMode?1:u.length,u,l,p),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function v(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function w(e,t){e._final((function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),_(e,t)}))}function _(e,t){var n=v(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(w,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}a.inherits(y,u),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===y&&(e&&e._writableState instanceof m)}})):h=function(e){return e instanceof this},y.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},y.prototype.write=function(e,t,n){var o,s=this._writableState,i=!1,a=!s.objectMode&&(o=e,l.isBuffer(o)||o instanceof p);return a&&!l.isBuffer(e)&&(e=function(e){return l.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=s.defaultEncoding),"function"!=typeof n&&(n=d),s.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,o){var s=!0,i=!1;return null===n?i=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(i=new TypeError("Invalid non-string/buffer chunk")),i&&(e.emit("error",i),r.nextTick(o,i),s=!1),s}(this,s,e,n))&&(s.pendingcb++,i=function(e,t,n,r,o,s){if(!n){var i=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,n));return t}(t,r,o);r!==i&&(n=!0,o="buffer",r=i)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},y.prototype._writev=null,y.prototype.end=function(e,t,n){var o=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),o.corked&&(o.corked=1,this.uncork()),o.ending||o.finished||function(e,t,n){t.ending=!0,_(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,o,n)},Object.defineProperty(y.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),y.prototype.destroy=f.destroy,y.prototype._undestroy=f.undestroy,y.prototype._destroy=function(e,t){this.end(),t(e)}},function(e,t,n){"use strict";var r=n(16).Buffer,o=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=u,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=p,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function i(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function u(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return o>0&&(e.lastNeed=o-1),o;if(--r=0)return o>0&&(e.lastNeed=o-2),o;if(--r=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";e.exports=i;var r=n(37),o=Object.create(n(44));function s(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(!r)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length=9?43===e.code||e.hasErrorLabel("ResumableChangeStreamError"):o.has(e.code))}}},function(e,t,n){"use strict";const r=n(0).applyRetryableWrites,o=n(0).applyWriteConcern,s=n(1).MongoError,i=n(3).OperationBase;e.exports=class extends i{constructor(e,t,n){super(n),this.collection=e,this.operations=t}execute(e){const t=this.collection,n=this.operations;let i=this.options;t.s.options.ignoreUndefined&&(i=Object.assign({},i),i.ignoreUndefined=t.s.options.ignoreUndefined);const a=!0===i.ordered||null==i.ordered?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let c=!1;try{for(let e=0;e{if(!n&&t)return e(t,null);n.insertedCount=n.nInserted,n.matchedCount=n.nMatched,n.modifiedCount=n.nModified||0,n.deletedCount=n.nRemoved,n.upsertedCount=n.getUpsertedIds().length,n.upsertedIds={},n.insertedIds={},n.n=n.insertedCount;const r=n.getInsertedIds();for(let e=0;e{e?t(e):t(null,this.onlyReturnNameOfCreatedIndex?r[0].name:n)})}}o(l,[r.WRITE_OPERATION,r.EXECUTE_WITH_SELECTION]),e.exports=l},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(0).handleCallback;class c extends s{constructor(e,t,n){super(e.s.db,n,e),this.collection=e,this.indexName=t}_buildCommand(){const e=this.collection,t=this.indexName,n=this.options;let r={dropIndexes:e.collectionName,index:t};return r=i(r,{db:e.s.db,collection:e},n),r}execute(e){super.execute((t,n)=>{if("function"==typeof e)return t?a(e,t,null):void a(e,null,n)})}}o(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.name=t}execute(e){const t=this.db,n=this.name,r=this.options;o(t,n,r,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection,n=this.options;t.s.db.listCollections({name:t.collectionName},n).toArray((n,r)=>n?o(e,n):0===r.length?o(e,s.create({message:`collection ${t.namespace} not found`,driver:!0})):void o(e,n,r[0].options||null))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(21),a=n(0).handleCallback,c=n(0).toError;class u extends o{constructor(e,t,n,r){super(e,r),this.username=t,this.password=n}_buildCommand(){const e=this.db,t=this.username,n=this.password,r=this.options;let o=Array.isArray(r.roles)?r.roles:[];0===o.length&&console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"),"admin"!==e.databaseName.toLowerCase()&&"admin"!==r.dbName||Array.isArray(r.roles)?Array.isArray(r.roles)||(o=["dbOwner"]):o=["root"];const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=n;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+n),a=e.digest("hex")}const c={createUser:t,customData:r.customData||{},roles:o,digestPassword:s};return"string"==typeof n&&(c.pwd=a),c}execute(e){if(null!=this.options.digestPassword)return e(c("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."));super.execute((t,n)=>a(e,t,t?null:n))}}s(u,r.WRITE_OPERATION),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(1).MongoError,i=n(0).MongoDBNamespace;e.exports=class extends r{constructor(e,t,n){super(n),this.db=e,this.selector=t}execute(e){const t=this.db,n=this.selector,r=this.options,a=new i("admin","$cmd");t.s.topology.command(a,n,r,(n,r)=>t.serverConfig&&t.serverConfig.isDestroyed()?e(new s("topology was destroyed")):n?o(e,n):void o(e,null,r.result))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects,i=n(0).handleCallback,a=n(29);class c extends o{constructor(e,t,n){const r={},o=a.fromOptions(n);null!=o&&(r.writeConcern=o),n.dbName&&(r.dbName=n.dbName),"number"==typeof n.maxTimeMS&&(r.maxTimeMS=n.maxTimeMS),super(e,r),this.username=t}_buildCommand(){return{dropUser:this.username}}execute(e){super.execute((t,n)=>{if(t)return i(e,t,null);i(e,t,!!n.ok)})}}s(c,r.WRITE_OPERATION),e.exports=c},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).applyWriteConcern,s=n(0).checkCollectionName,i=n(14).executeDbAdminCommand,a=n(0).handleCallback,c=n(85).loadCollection,u=n(0).toError;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.newName=t}execute(e){const t=this.collection,n=this.newName,r=this.options;let l=c();s(n);const p={renameCollection:t.namespace,to:t.s.namespace.withCollection(n).toString(),dropTarget:"boolean"==typeof r.dropTarget&&r.dropTarget};o(p,{db:t.s.db,collection:t},r),i(t.s.db.admin().s.db,p,r,(r,o)=>{if(r)return a(e,r,null);if(o.errmsg)return a(e,u(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,n,t.s.pkFactory,t.s.options))}catch(r){return a(e,u(r),null)}})}}},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(118),s=n(119),i=n(120),a=n(210),c=n(211),u=n(43);function l(e,t,n){if(!(this instanceof l))return new l(e,t);this.s={db:e,topology:t,promiseLibrary:n}}l.prototype.command=function(e,t,n){const r=Array.prototype.slice.call(arguments,1);n="function"==typeof r[r.length-1]?r.pop():void 0,t=r.length?r.shift():{};const o=new s(this.s.db,e,t);return u(this.s.db.s.topology,o,n)},l.prototype.buildInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverInfo=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{buildinfo:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.serverStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{serverStatus:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.ping=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{ping:1},e);return u(this.s.db.s.topology,n,t)},l.prototype.addUser=function(e,t,n,s){const i=Array.prototype.slice.call(arguments,2);s="function"==typeof i[i.length-1]?i.pop():void 0,"string"==typeof e&&null!=t&&"object"==typeof t&&(n=t,t=null),n=i.length?i.shift():{},n=Object.assign({},n),(n=r(n,{db:this.s.db})).dbName="admin";const a=new o(this.s.db,e,t,n);return u(this.s.db.s.topology,a,s)},l.prototype.removeUser=function(e,t,n){const o=Array.prototype.slice.call(arguments,1);n="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():{},t=Object.assign({},t),(t=r(t,{db:this.s.db})).dbName="admin";const s=new i(this.s.db,e,t);return u(this.s.db.s.topology,s,n)},l.prototype.validateCollection=function(e,t,n){"function"==typeof t&&(n=t,t={});const r=new a(this,e,t=t||{});return u(this.s.db.s.topology,r,n)},l.prototype.listDatabases=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},u(this.s.db.s.topology,new c(this.s.db,e),t)},l.prototype.replSetGetStatus=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const n=new s(this.s.db,{replSetGetStatus:1},e);return u(this.s.db.s.topology,n,t)},e.exports=l},function(e,t,n){"use strict";const r=n(1).Topology,o=n(32).ServerCapabilities,s=n(25),i=n(0).translateOptions;e.exports=class extends r{constructor(e,t){t=t||{};let n=Object.assign({},{cursorFactory:s,reconnect:!1,emitError:"boolean"!=typeof t.emitError||t.emitError,maxPoolSize:"number"==typeof t.maxPoolSize?t.maxPoolSize:"number"==typeof t.poolSize?t.poolSize:10,minPoolSize:"number"==typeof t.minPoolSize?t.minPoolSize:"number"==typeof t.minSize?t.minSize:0,monitorCommands:"boolean"==typeof t.monitorCommands&&t.monitorCommands});n=i(n,t);var r=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;n=i(n,r),super(e,n)}capabilities(){return this.s.sCapabilities?this.s.sCapabilities:null==this.lastIsMaster()?null:(this.s.sCapabilities=new o(this.lastIsMaster()),this.s.sCapabilities)}command(e,t,n,r){super.command(e.toString(),t,n,r)}insert(e,t,n,r){super.insert(e.toString(),t,n,r)}update(e,t,n,r){super.update(e.toString(),t,n,r)}remove(e,t,n,r){super.remove(e.toString(),t,n,r)}}},function(e,t,n){"use strict";const r=n(5).deprecate,o=n(1).Logger,s=n(1).MongoCredentials,i=n(1).MongoError,a=n(125),c=n(123),u=n(1).parseConnectionString,l=n(36),p=n(1).ReadPreference,h=n(126),f=n(66),d=n(1).Sessions.ServerSessionPool,m=n(0).emitDeprecationWarning,y=n(40),g=n(11).retrieveBSON(),b=n(61).CMAP_EVENT_NAMES;let S;const v=r(n(217),"current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."),w={DEFAULT:"default",PLAIN:"plain",GSSAPI:"gssapi","MONGODB-CR":"mongocr","MONGODB-X509":"x509","MONGODB-AWS":"mongodb-aws","SCRAM-SHA-1":"scram-sha-1","SCRAM-SHA-256":"scram-sha-256"},_=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"],O=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]),T=["poolSize","ssl","sslValidate","sslCA","sslCert","sslKey","sslPass","sslCRL","autoReconnect","noDelay","keepAlive","keepAliveInitialDelay","connectTimeoutMS","family","socketTimeoutMS","reconnectTries","reconnectInterval","ha","haInterval","replicaSet","secondaryAcceptableLatencyMS","acceptableLatencyMS","connectWithNoPrimary","authSource","w","wtimeout","j","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","retryWrites","retryReads","useNewUrlParser","useUnifiedTopology","serverSelectionTimeoutMS","useRecoveryToken","autoEncryption","driverInfo","tls","tlsInsecure","tlsinsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","tlsCAFile","tlsCertificateFile","tlsCertificateKeyFile","tlsCertificateKeyFilePassword","minHeartbeatFrequencyMS","heartbeatFrequencyMS","directConnection","appName","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"],E=["native_parser"],C=["server","replset","replSet","mongos","db"];const x=T.reduce((e,t)=>(e[t.toLowerCase()]=t,e),{});function A(e,t){t.on("authenticated",M(e,"authenticated")),t.on("error",M(e,"error")),t.on("timeout",M(e,"timeout")),t.on("close",M(e,"close")),t.on("parseError",M(e,"parseError")),t.once("open",M(e,"open")),t.once("fullsetup",M(e,"fullsetup")),t.once("all",M(e,"all")),t.on("reconnect",M(e,"reconnect"))}function N(e,t){e.topology=t,t instanceof c||(t.s.sessionPool=new d(t.s.coreTopology))}function I(e,t){let r=(S||(S=n(62)),S);const o=[];return e instanceof r&&_.forEach(n=>{t.on(n,(t,r)=>{"open"===n?o.push({event:n,object1:e}):o.push({event:n,object1:t,object2:r})})}),o}const k=r(()=>{},"current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.");function M(e,t){const n=new Set(["all","fullsetup","open","reconnect"]);return(r,o)=>{if(n.has(t))return e.emit(t,e);e.emit(t,r,o)}}const R=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function D(e,t,r,o){r.promiseLibrary=e.s.promiseLibrary;const s={};"unified"===t&&(s.createServers=!1);const u=F(r,s);if(null!=r.autoEncryption){let t;try{let e=n(127);"function"!=typeof e.extension&&o(new i("loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`")),t=e.extension(n(17)).AutoEncrypter}catch(e){return void o(e)}const s=Object.assign({bson:r.bson||new g([g.Binary,g.Code,g.DBRef,g.Decimal128,g.Double,g.Int32,g.Long,g.Map,g.MaxKey,g.MinKey,g.ObjectId,g.BSONRegExp,g.Symbol,g.Timestamp])},r.autoEncryption);r.autoEncrypter=new t(e,s)}let l;"mongos"===t?l=new a(u,r):"replicaset"===t?l=new h(u,r):"unified"===t&&(l=new c(r.servers,r),function(e){e.on("newListener",e=>{R.has(e)&&m(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")})}(e)),A(e,l),U(e,l),N(e,l),r.autoEncrypter?r.autoEncrypter.init(e=>{e?o(e):l.connect(r,e=>{if(e)return l.close(!0),void o(e);o(void 0,l)})}):l.connect(r,e=>{if(e)return l.close(!0),o(e);o(void 0,l)})}function B(e,t){const n=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"],r=["readconcern","compression","autoencryption"];for(const o in t)-1!==r.indexOf(o.toLowerCase())?e[o]=t[o]:-1!==n.indexOf(o.toLowerCase())?e=j(e,t[o],!1):!t[o]||"object"!=typeof t[o]||Buffer.isBuffer(t[o])||Array.isArray(t[o])?e[o]=t[o]:e=j(e,t[o],!0);return e}function P(e,t,n,r){const o=(r=Object.assign({},r)).authSource||r.authdb||r.dbName,a=r.authMechanism||"DEFAULT",c=a.toUpperCase(),u=r.authMechanismProperties;if(!O.has(c))throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:!0});return new s({mechanism:w[c],mechanismProperties:u,source:o,username:t,password:n})}function L(e){return j(B({},e),e,!1)}function j(e,t,n){for(const r in t)t[r]&&"object"==typeof t[r]&&n?e=j(e,t[r],n):e[r]=t[r];return e}function U(e,t){["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(b).forEach(n=>{t.on(n,(t,r)=>{e.emit(n,t,r)})})}function z(e){let t=Object.assign({servers:e.hosts},e.options);for(let e in t){const n=x[e];n&&(t[n]=t[e])}const n=e.auth&&e.auth.username,r=e.options&&e.options.authMechanism;return(n||r)&&(t.auth=Object.assign({},e.auth),t.auth.db&&(t.authSource=t.authSource||t.auth.db),t.auth.username&&(t.auth.user=t.auth.username)),e.defaultDatabase&&(t.dbName=e.defaultDatabase),t.maxPoolSize&&(t.poolSize=t.maxPoolSize),t.readConcernLevel&&(t.readConcern=new l(t.readConcernLevel)),t.wTimeoutMS&&(t.wtimeout=t.wTimeoutMS),e.srvHost&&(t.srvHost=e.srvHost),t}function F(e,t){if(t=Object.assign({},{createServers:!0},t),"string"!=typeof e.readPreference&&"string"!=typeof e.read_preference||(e.readPreference=new p(e.readPreference||e.read_preference)),e.readPreference&&(e.readPreferenceTags||e.read_preference_tags)&&(e.readPreference.tags=e.readPreferenceTags||e.read_preference_tags),e.maxStalenessSeconds&&(e.readPreference.maxStalenessSeconds=e.maxStalenessSeconds),null==e.socketTimeoutMS&&(e.socketTimeoutMS=36e4),null==e.connectTimeoutMS&&(e.connectTimeoutMS=1e4),t.createServers)return e.servers.map(t=>t.domain_socket?new f(t.domain_socket,27017,e):new f(t.host,t.port,e))}e.exports={validOptions:function(e){const t=T.concat(C);for(const n in e)if(-1===E.indexOf(n)){if(-1===t.indexOf(n)){if(e.validateOptions)return new i(`option ${n} is not supported`);console.warn(`the options [${n}] is not supported`)}-1!==C.indexOf(n)&&console.warn(`the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [${T}]`)}},connect:function(e,t,n,r){if(n=Object.assign({},n),null==r)throw new Error("no callback function provided");let s=!1;const c=o("MongoClient",n);if(t instanceof f||t instanceof h||t instanceof a)return function(e,t,n,r){N(e,t),A(e,t),U(e,t);let o=Object.assign({},n);"string"!=typeof n.readPreference&&"string"!=typeof n.read_preference||(o.readPreference=new p(n.readPreference||n.read_preference));if((o.user||o.password||o.authMechanism)&&!o.credentials)try{o.credentials=P(e,o.user,o.password,o)}catch(e){return r(e,t)}return t.connect(o,r)}(e,t,n,m);const l=!1!==n.useNewUrlParser,d=l?z:L;function m(t,n){const o="seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name";if(t&&"no mongos proxies found in seed list"===t.message)return c.isWarn()&&c.warn(o),r(new i(o));s&&e.emit("authenticated",null,!0),r(t,n)}(l?u:v)(t,n,(t,o)=>{if(t)return r(t);const i=d(o),a=B(i,n);if(null==a.socketTimeoutMS&&(a.socketTimeoutMS=36e4),null==a.connectTimeoutMS&&(a.connectTimeoutMS=1e4),null==a.retryWrites&&(a.retryWrites=!0),null==a.useRecoveryToken&&(a.useRecoveryToken=!0),null==a.readPreference&&(a.readPreference="primary"),a.db_options&&a.db_options.auth&&delete a.db_options.auth,null!=a.journal&&(a.j=a.journal,a.journal=void 0),function(e){null!=e.tls&&["sslCA","sslKey","sslCert"].forEach(t=>{e[t]&&(e[t]=y.readFileSync(e[t]))})}(a),e.s.options=a,0===i.servers.length)return r(new Error("connection string must contain at least one seed host"));if(a.auth&&!a.credentials)try{s=!0,a.credentials=P(e,a.auth.user,a.auth.password,a)}catch(t){return r(t)}return a.useUnifiedTopology?D(e,"unified",a,m):(k(),a.replicaSet||a.rs_name?D(e,"replicaset",a,m):i.servers.length>1?D(e,"mongos",a,m):function(e,t,n){t.promiseLibrary=e.s.promiseLibrary;const r=F(t)[0],o=I(e,r);r.connect(t,(s,i)=>{if(s)return r.close(!0),n(s);!function(e){_.forEach(t=>e.removeAllListeners(t))}(r),U(e,r),A(e,r);const a=i.lastIsMaster();if(N(e,i),a&&"isdbgrid"===a.msg)return i.close(),D(e,"mongos",t,n);!function(e,t){for(let n=0;n0?t.socketOptions:t;g=l(g,b),this.s={coreTopology:new s(m,g),sCapabilities:null,debug:g.debug,storeOptions:r,clonedOptions:g,store:d,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(){return function(e){["timeout","error","close"].forEach((function(e){n.removeListener(e,r)})),n.s.coreTopology.removeListener("connect",r),n.close(!0);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}},o=function(e){return function(t){"error"!==e&&n.emit(e,t)}},s=function(e){return function(t,r){n.emit(e,t,r)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.s.coreTopology.once("connect",(function(){["timeout","error","close","fullsetup"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)})),n.s.coreTopology.on("timeout",o("timeout")),n.s.coreTopology.on("error",o("error")),n.s.coreTopology.on("close",o("close")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n)})),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.on("joined",s("joined")),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("reconnect",(function(){n.emit("reconnect"),n.s.store.execute()})),n.s.coreTopology.connect(e)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";const r=n(66),o=n(25),s=n(1).MongoError,i=n(32).TopologyBase,a=n(32).Store,c=n(1).ReplSet,u=n(0).MAX_JS_INT,l=n(0).translateOptions,p=n(0).filterOptions,h=n(0).mergeOptions;var f=["ha","haInterval","replicaSet","rs_name","secondaryAcceptableLatencyMS","connectWithNoPrimary","poolSize","ssl","checkServerIdentity","sslValidate","sslCA","sslCert","ciphers","ecdhCurve","sslCRL","sslKey","sslPass","socketOptions","bufferMaxEntries","store","auto_reconnect","autoReconnect","emitError","keepAlive","keepAliveInitialDelay","noDelay","connectTimeoutMS","socketTimeoutMS","strategy","debug","family","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class d extends i{constructor(e,t){super();var n=this;t=p(t=t||{},f);for(var i=0;i0?t.socketOptions:t;g=l(g,b);var S=new c(y,g);S.on("reconnect",(function(){n.emit("reconnect"),m.execute()})),this.s={coreTopology:S,sCapabilities:null,tag:t.tag,storeOptions:d,clonedOptions:g,store:m,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise},g.debug&&Object.defineProperty(this,"replset",{enumerable:!0,get:function(){return S}})}connect(e,t){var n=this;"function"==typeof e&&(t=e,e={}),null==e&&(e={}),"function"!=typeof t&&(t=null),e=Object.assign({},this.s.clonedOptions,e),n.s.options=e,n.s.storeOptions.bufferMaxEntries="number"==typeof e.bufferMaxEntries?e.bufferMaxEntries:-1;var r=function(e){return function(t){"error"!==e&&n.emit(e,t)}};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"].forEach((function(e){n.s.coreTopology.removeAllListeners(e)}));var o,s=function(e){return function(t,r){n.emit(e,t,r)}};n.s.coreTopology.on("joined",(o="joined",function(e,t){n.emit(o,e,t.lastIsMaster(),t)})),n.s.coreTopology.on("left",s("left")),n.s.coreTopology.on("ping",s("ping")),n.s.coreTopology.on("ha",(function(e,t){n.emit("ha",e,t),"start"===e?n.emit("ha_connect",e,t):"end"===e&&n.emit("ha_ismaster",e,t)})),n.s.coreTopology.on("serverDescriptionChanged",s("serverDescriptionChanged")),n.s.coreTopology.on("serverHeartbeatStarted",s("serverHeartbeatStarted")),n.s.coreTopology.on("serverHeartbeatSucceeded",s("serverHeartbeatSucceeded")),n.s.coreTopology.on("serverHeartbeatFailed",s("serverHeartbeatFailed")),n.s.coreTopology.on("serverOpening",s("serverOpening")),n.s.coreTopology.on("serverClosed",s("serverClosed")),n.s.coreTopology.on("topologyOpening",s("topologyOpening")),n.s.coreTopology.on("topologyClosed",s("topologyClosed")),n.s.coreTopology.on("topologyDescriptionChanged",s("topologyDescriptionChanged")),n.s.coreTopology.on("commandStarted",s("commandStarted")),n.s.coreTopology.on("commandSucceeded",s("commandSucceeded")),n.s.coreTopology.on("commandFailed",s("commandFailed")),n.s.coreTopology.on("fullsetup",(function(){n.emit("fullsetup",n,n)})),n.s.coreTopology.on("all",(function(){n.emit("all",null,n)}));var i=function(){return function(e){["timeout","error","close"].forEach((function(e){n.s.coreTopology.removeListener(e,i)})),n.s.coreTopology.removeListener("connect",i),n.s.coreTopology.destroy();try{t(e)}catch(e){n.s.coreTopology.isConnected()||process.nextTick((function(){throw e}))}}};n.s.coreTopology.once("timeout",i("timeout")),n.s.coreTopology.once("error",i("error")),n.s.coreTopology.once("close",i("close")),n.s.coreTopology.once("connect",(function(){n.s.coreTopology.once("timeout",r("timeout")),n.s.coreTopology.once("error",r("error")),n.s.coreTopology.once("close",r("close")),n.emit("open",null,n);try{t(null,n)}catch(e){process.nextTick((function(){throw e}))}})),n.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach(e=>this.removeAllListeners(e)),super.close(e,t)}}Object.defineProperty(d.prototype,"haInterval",{enumerable:!0,get:function(){return this.s.coreTopology.s.haInterval}}),e.exports=d},function(e,t,n){"use strict";let r;function o(){return r||(r=i(n(17))),r}const s=n(67).MongoCryptError;function i(e){const t={mongodb:e};return t.stateMachine=n(218)(t),t.autoEncrypter=n(219)(t),t.clientEncryption=n(223)(t),{AutoEncrypter:t.autoEncrypter.AutoEncrypter,ClientEncryption:t.clientEncryption.ClientEncryption,MongoCryptError:s}}e.exports={extension:i,MongoCryptError:s,get AutoEncrypter(){const t=o();return delete e.exports.AutoEncrypter,e.exports.AutoEncrypter=t.AutoEncrypter,t.AutoEncrypter},get ClientEncryption(){const t=o();return delete e.exports.ClientEncryption,e.exports.ClientEncryption=t.ClientEncryption,t.ClientEncryption}}},function(e,t,n){(function(r){var o=n(40),s=n(39),i=n(220),a=s.join,c=s.dirname,u=o.accessSync&&function(e){try{o.accessSync(e)}catch(e){return!1}return!0}||o.existsSync||s.existsSync,l={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};e.exports=t=function(e){"string"==typeof e?e={bindings:e}:e||(e={}),Object.keys(l).map((function(t){t in e||(e[t]=l[t])})),e.module_root||(e.module_root=t.getRoot(t.getFileName())),".node"!=s.extname(e.bindings)&&(e.bindings+=".node");for(var n,r,o,i=require,c=[],u=0,p=e.try.length;u{let s;try{s=r.createHmac(e,t).update(n).digest()}catch(e){return e}return s.copy(o),s.length}}e.exports={aes256CbcEncryptHook:function(e,t,n,o){let s;try{let o=r.createCipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},aes256CbcDecryptHook:function(e,t,n,o){let s;try{let o=r.createDecipheriv("aes-256-cbc",e,t);o.setAutoPadding(!1),s=o.update(n)}catch(e){return e}return s.copy(o),s.length},randomHook:"function"==typeof r.randomFillSync?function(e,t){try{r.randomFillSync(e,0,t)}catch(e){return e}return t}:function(e,t){let n;try{n=r.randomBytes(t)}catch(e){return e}return n.copy(e),t},hmacSha512Hook:o("sha512"),hmacSha256Hook:o("sha256"),sha256Hook:function(e,t){let n;try{n=r.createHash("sha256").update(e).digest()}catch(e){return e}return n.copy(t),n.length}}},function(e,t,n){"use strict";var r=n(1).BSON.Binary,o=n(1).BSON.ObjectID,s=n(16).Buffer,i=function(e,t,n){if(!(this instanceof i))return new i(e,t);this.file=e;var a=null==t?{}:t;if(this.writeConcern=n||{w:1},this.objectId=null==a._id?new o:a._id,this.chunkNumber=null==a.n?0:a.n,this.data=new r,"string"==typeof a.data){var c=s.alloc(a.data.length);c.write(a.data,0,a.data.length,"binary"),this.data=new r(c)}else if(Array.isArray(a.data)){c=s.alloc(a.data.length);var u=a.data.join("");c.write(u,0,u.length,"binary"),this.data=new r(c)}else if(a.data&&"Binary"===a.data._bsontype)this.data=a.data;else if(!s.isBuffer(a.data)&&null!=a.data)throw Error("Illegal chunk format");this.internalPosition=0};i.prototype.write=function(e,t){return this.data.write(e,this.internalPosition,e.length,"binary"),this.internalPosition=this.data.length(),null!=t?t(null,this):this},i.prototype.read=function(e){if(e=null==e||0===e?this.length():e,this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);return this.internalPosition=this.internalPosition+e,t}return""},i.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;return null!=this.data.buffer?t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e):(t=s.alloc(e),e=this.data.readInto(t,this.internalPosition)),this.internalPosition=this.internalPosition+e,t}return null},i.prototype.eof=function(){return this.internalPosition===this.length()},i.prototype.getc=function(){return this.read(1)},i.prototype.rewind=function(){this.internalPosition=0,this.data=new r},i.prototype.save=function(e,t){var n=this;"function"==typeof e&&(t=e,e={}),n.file.chunkCollection((function(r,o){if(r)return t(r);var s={upsert:!0};for(var i in e)s[i]=e[i];for(i in n.writeConcern)s[i]=n.writeConcern[i];n.data.length()>0?n.buildMongoObject((function(e){var r={forceServerObjectId:!0};for(var i in n.writeConcern)r[i]=n.writeConcern[i];o.replaceOne({_id:n.objectId},e,s,(function(e){t(e,n)}))})):t(null,n)}))},i.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};null!=this.objectId&&(t._id=this.objectId),e(t)},i.prototype.length=function(){return this.data.length()},Object.defineProperty(i.prototype,"position",{enumerable:!0,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}}),i.DEFAULT_CHUNK_SIZE=261120,e.exports=i},function(e,t){var n=Object.prototype.toString;function r(e){return"function"==typeof e.constructor?e.constructor.name:null}e.exports=function(e){if(void 0===e)return"undefined";if(null===e)return"null";var t=typeof e;if("boolean"===t)return"boolean";if("string"===t)return"string";if("number"===t)return"number";if("symbol"===t)return"symbol";if("function"===t)return"GeneratorFunction"===r(e)?"generatorfunction":"function";if(function(e){return Array.isArray?Array.isArray(e):e instanceof Array}(e))return"array";if(function(e){if(e.constructor&&"function"==typeof e.constructor.isBuffer)return e.constructor.isBuffer(e);return!1}(e))return"buffer";if(function(e){try{if("number"==typeof e.length&&"function"==typeof e.callee)return!0}catch(e){if(-1!==e.message.indexOf("callee"))return!0}return!1}(e))return"arguments";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";if(function(e){return e instanceof RegExp||"string"==typeof e.flags&&"boolean"==typeof e.ignoreCase&&"boolean"==typeof e.multiline&&"boolean"==typeof e.global}(e))return"regexp";switch(r(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(function(e){return"function"==typeof e.throw&&"function"==typeof e.return&&"function"==typeof e.next}(e))return"generator";switch(t=n.call(e)){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")}},function(e,t,n){"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */e.exports=function(e,t){if("string"==typeof e)return c(e);if("number"==typeof e)return a(e,t);return null},e.exports.format=a,e.exports.parse=c;var r=/\B(?=(\d{3})+(?!\d))/g,o=/(?:\.0*|(\.[^0]+)0+)$/,s={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},i=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function a(e,t){if(!Number.isFinite(e))return null;var n=Math.abs(e),i=t&&t.thousandsSeparator||"",a=t&&t.unitSeparator||"",c=t&&void 0!==t.decimalPlaces?t.decimalPlaces:2,u=Boolean(t&&t.fixedDecimals),l=t&&t.unit||"";l&&s[l.toLowerCase()]||(l=n>=s.pb?"PB":n>=s.tb?"TB":n>=s.gb?"GB":n>=s.mb?"MB":n>=s.kb?"KB":"B");var p=(e/s[l.toLowerCase()]).toFixed(c);return u||(p=p.replace(o,"$1")),i&&(p=p.replace(r,i)),p+a+l}function c(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var t,n=i.exec(e),r="b";return n?(t=parseFloat(n[1]),r=n[4].toLowerCase()):(t=parseInt(e,10),r="b"),Math.floor(s[r]*t)}},function(e,t,n){"use strict";const r=n(233);e.exports=e=>{const t=r(0,e.length-1);return()=>e[t()]}},function(e,t,n){"use strict";var r=n(70),o=n(33),s=n(48),i=n(49),a=n(50),c=n(51),u=n(52),l=n(71),p=n(53),h=n(54),f=n(55),d=n(56),m=n(57),y=n(38),g=n(135),b=n(136),S=n(138),v=n(28),w=v.allocBuffer(17825792),_=function(){};_.prototype.serialize=function(e,t){var n="boolean"==typeof(t=t||{}).checkKeys&&t.checkKeys,r="boolean"==typeof t.serializeFunctions&&t.serializeFunctions,o="boolean"!=typeof t.ignoreUndefined||t.ignoreUndefined,s="number"==typeof t.minInternalBufferSize?t.minInternalBufferSize:17825792;w.lengthe.length)throw new Error("corrupt bson message");if(0!==e[r+o-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(e,r,t,n)},deserializeObject=function(e,t,n,r){var o=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,i=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!i)var a=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,u=null!=n.raw&&n.raw,l="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,p=null!=n.promoteBuffers&&n.promoteBuffers,h=null==n.promoteLongs||n.promoteLongs,f=null==n.promoteValues||n.promoteValues,d=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var m=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(m<5||m>e.length)throw new Error("corrupt bson message");for(var y=r?[]:{},g=0;;){var b=e[t++];if(0===b)break;for(var S=t;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var v=r?g++:e.toString("utf8",t,S);if(t=S+1,b===BSON.BSON_DATA_STRING){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(w<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=e.toString("utf8",t,t+w-1),t+=w}else if(b===BSON.BSON_DATA_OID){var _=utils.allocBuffer(12);e.copy(_,0,t,t+12),y[v]=new ObjectID(_),t+=12}else if(b===BSON.BSON_DATA_INT&&!1===f)y[v]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24);else if(b===BSON.BSON_DATA_INT)y[v]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;else if(b===BSON.BSON_DATA_NUMBER&&!1===f)y[v]=new Double(e.readDoubleLE(t)),t+=8;else if(b===BSON.BSON_DATA_NUMBER)y[v]=e.readDoubleLE(t),t+=8;else if(b===BSON.BSON_DATA_DATE){var O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;y[v]=new Date(new Long(O,T).toNumber())}else if(b===BSON.BSON_DATA_BOOLEAN){if(0!==e[t]&&1!==e[t])throw new Error("illegal boolean type value");y[v]=1===e[t++]}else if(b===BSON.BSON_DATA_OBJECT){var E=t,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(C<=0||C>e.length-t)throw new Error("bad embedded document length in bson");y[v]=u?e.slice(t,t+C):deserializeObject(e,E,n,!1),t+=C}else if(b===BSON.BSON_DATA_ARRAY){E=t;var x=n,A=t+(C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24);if(c&&c[v]){for(var N in x={},n)x[N]=n[N];x.raw=!0}if(y[v]=deserializeObject(e,E,x,!0),0!==e[(t+=C)-1])throw new Error("invalid array terminator byte");if(t!==A)throw new Error("corrupted array bson")}else if(b===BSON.BSON_DATA_UNDEFINED)y[v]=void 0;else if(b===BSON.BSON_DATA_NULL)y[v]=null;else if(b===BSON.BSON_DATA_LONG){O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var I=new Long(O,T);y[v]=h&&!0===f&&I.lessThanOrEqual(JS_INT_MAX_LONG)&&I.greaterThanOrEqual(JS_INT_MIN_LONG)?I.toNumber():I}else if(b===BSON.BSON_DATA_DECIMAL128){var k=utils.allocBuffer(16);e.copy(k,0,t,t+16),t+=16;var M=new Decimal128(k);y[v]=M.toObject?M.toObject():M}else if(b===BSON.BSON_DATA_BINARY){var R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,D=R,B=e[t++];if(R<0)throw new Error("Negative binary type element size found");if(R>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(B===Binary.SUBTYPE_BYTE_ARRAY){if((R=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(R>D-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(RD-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(R=e.length)throw new Error("Bad BSON Document: illegal CString");var L=e.toString("utf8",t,S);for(S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");var j=e.toString("utf8",t,S);t=S+1;var U=new Array(j.length);for(S=0;S=e.length)throw new Error("Bad BSON Document: illegal CString");for(L=e.toString("utf8",t,S),S=t=S+1;0!==e[S]&&S=e.length)throw new Error("Bad BSON Document: illegal CString");j=e.toString("utf8",t,S),t=S+1,y[v]=new BSONRegExp(L,j)}else if(b===BSON.BSON_DATA_SYMBOL){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");y[v]=new Symbol(e.toString("utf8",t,t+w-1)),t+=w}else if(b===BSON.BSON_DATA_TIMESTAMP)O=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,T=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24,y[v]=new Timestamp(O,T);else if(b===BSON.BSON_DATA_MIN_KEY)y[v]=new MinKey;else if(b===BSON.BSON_DATA_MAX_KEY)y[v]=new MaxKey;else if(b===BSON.BSON_DATA_CODE){if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var z=e.toString("utf8",t,t+w-1);if(o)if(s){var F=i?a(z):z;y[v]=isolateEvalWithHash(functionCache,F,z,y)}else y[v]=isolateEval(z);else y[v]=new Code(z);t+=w}else if(b===BSON.BSON_DATA_CODE_W_SCOPE){var W=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(W<13)throw new Error("code_w_scope total size shorter minimum expected length");if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");z=e.toString("utf8",t,t+w-1),E=t+=w,C=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,E,n,!1);if(t+=C,W<8+C+w)throw new Error("code_w_scope total size is to short, truncating scope");if(W>8+C+w)throw new Error("code_w_scope total size is to long, clips outer document");o?(s?(F=i?a(z):z,y[v]=isolateEvalWithHash(functionCache,F,z,y)):y[v]=isolateEval(z),y[v].scope=q):y[v]=new Code(z,q)}else{if(b!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+b.toString(16)+' for fieldname "'+v+'", are you using the latest BSON parser');if((w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)<=0||w>e.length-t||0!==e[t+w-1])throw new Error("bad string length in bson");var $=e.toString("utf8",t,t+w-1);t+=w;var H=utils.allocBuffer(12);e.copy(H,0,t,t+12),_=new ObjectID(H),t+=12;var V=$.split("."),Y=V.shift(),G=V.join(".");y[v]=new DBRef(G,_,Y)}}if(m!==t-d){if(r)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=y.$id&&(y=new DBRef(y.$ref,y.$id,y.$db)),y},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(e,t,n){"use strict";var r=n(137).writeIEEE754,o=n(33).Long,s=n(70),i=n(38).Binary,a=n(28).normalizedFunctionString,c=/\x00/,u=["$db","$ref","$id","$clusterTime"],l=function(e){return"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e)},p=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},h=function(e,t,n,r,o){e[r++]=R.BSON_DATA_STRING;var s=o?e.write(t,r,"ascii"):e.write(t,r,"utf8");e[(r=r+s+1)-1]=0;var i=e.write(n,r+4,"utf8");return e[r+3]=i+1>>24&255,e[r+2]=i+1>>16&255,e[r+1]=i+1>>8&255,e[r]=i+1&255,r=r+4+i,e[r++]=0,r},f=function(e,t,n,s,i){if(Math.floor(n)===n&&n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)if(n>=R.BSON_INT32_MIN&&n<=R.BSON_INT32_MAX){e[s++]=R.BSON_DATA_INT;var a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8");s+=a,e[s++]=0,e[s++]=255&n,e[s++]=n>>8&255,e[s++]=n>>16&255,e[s++]=n>>24&255}else if(n>=R.JS_INT_MIN&&n<=R.JS_INT_MAX)e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;else{e[s++]=R.BSON_DATA_LONG,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0;var c=o.fromNumber(n),u=c.getLowBits(),l=c.getHighBits();e[s++]=255&u,e[s++]=u>>8&255,e[s++]=u>>16&255,e[s++]=u>>24&255,e[s++]=255&l,e[s++]=l>>8&255,e[s++]=l>>16&255,e[s++]=l>>24&255}else e[s++]=R.BSON_DATA_NUMBER,s+=a=i?e.write(t,s,"ascii"):e.write(t,s,"utf8"),e[s++]=0,r(e,n,s,"little",52,8),s+=8;return s},d=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_NULL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},m=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_BOOLEAN,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=n?1:0,r},y=function(e,t,n,r,s){e[r++]=R.BSON_DATA_DATE,r+=s?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var i=o.fromNumber(n.getTime()),a=i.getLowBits(),c=i.getHighBits();return e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=255&c,e[r++]=c>>8&255,e[r++]=c>>16&255,e[r++]=c>>24&255,r},g=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,n.source&&null!=n.source.match(c))throw Error("value "+n.source+" must not contain null bytes");return r+=e.write(n.source,r,"utf8"),e[r++]=0,n.global&&(e[r++]=115),n.ignoreCase&&(e[r++]=105),n.multiline&&(e[r++]=109),e[r++]=0,r},b=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_REGEXP,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,null!=n.pattern.match(c))throw Error("pattern "+n.pattern+" must not contain null bytes");return r+=e.write(n.pattern,r,"utf8"),e[r++]=0,r+=e.write(n.options.split("").sort().join(""),r,"utf8"),e[r++]=0,r},S=function(e,t,n,r,o){return null===n?e[r++]=R.BSON_DATA_NULL:"MinKey"===n._bsontype?e[r++]=R.BSON_DATA_MIN_KEY:e[r++]=R.BSON_DATA_MAX_KEY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,r},v=function(e,t,n,r,o){if(e[r++]=R.BSON_DATA_OID,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,"string"==typeof n.id)e.write(n.id,r,"binary");else{if(!n.id||!n.id.copy)throw new Error("object ["+JSON.stringify(n)+"] is not a valid ObjectId");n.id.copy(e,r,0,12)}return r+12},w=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.length;return e[r++]=255&s,e[r++]=s>>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=R.BSON_BINARY_SUBTYPE_DEFAULT,n.copy(e,r,0,s),r+=s},_=function(e,t,n,r,o,s,i,a,c,u){for(var l=0;l>8&255,e[r++]=s>>16&255,e[r++]=s>>24&255,e[r++]=255&i,e[r++]=i>>8&255,e[r++]=i>>16&255,e[r++]=i>>24&255,r},E=function(e,t,n,r,o){return e[r++]=R.BSON_DATA_INT,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,e[r++]=255&n,e[r++]=n>>8&255,e[r++]=n>>16&255,e[r++]=n>>24&255,r},C=function(e,t,n,o,s){return e[o++]=R.BSON_DATA_NUMBER,o+=s?e.write(t,o,"ascii"):e.write(t,o,"utf8"),e[o++]=0,r(e,n,o,"little",52,8),o+=8},x=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_CODE,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var c=a(n),u=e.write(c,r+4,"utf8")+1;return e[r]=255&u,e[r+1]=u>>8&255,e[r+2]=u>>16&255,e[r+3]=u>>24&255,r=r+4+u-1,e[r++]=0,r},A=function(e,t,n,r,o,s,i,a,c){if(n.scope&&"object"==typeof n.scope){e[r++]=R.BSON_DATA_CODE_W_SCOPE;var u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8");r+=u,e[r++]=0;var l=r,p="string"==typeof n.code?n.code:n.code.toString();r+=4;var h=e.write(p,r+4,"utf8")+1;e[r]=255&h,e[r+1]=h>>8&255,e[r+2]=h>>16&255,e[r+3]=h>>24&255,e[r+4+h-1]=0,r=r+h+4;var f=M(e,n.scope,o,r,s+1,i,a);r=f-1;var d=f-l;e[l++]=255&d,e[l++]=d>>8&255,e[l++]=d>>16&255,e[l++]=d>>24&255,e[r++]=0}else{e[r++]=R.BSON_DATA_CODE,r+=u=c?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0,p=n.code.toString();var m=e.write(p,r+4,"utf8")+1;e[r]=255&m,e[r+1]=m>>8&255,e[r+2]=m>>16&255,e[r+3]=m>>24&255,r=r+4+m-1,e[r++]=0}return r},N=function(e,t,n,r,o){e[r++]=R.BSON_DATA_BINARY,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=n.value(!0),a=n.position;return n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a+=4),e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255,e[r++]=n.sub_type,n.sub_type===i.SUBTYPE_BYTE_ARRAY&&(a-=4,e[r++]=255&a,e[r++]=a>>8&255,e[r++]=a>>16&255,e[r++]=a>>24&255),s.copy(e,r,0,n.position),r+=n.position},I=function(e,t,n,r,o){e[r++]=R.BSON_DATA_SYMBOL,r+=o?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var s=e.write(n.value,r+4,"utf8")+1;return e[r]=255&s,e[r+1]=s>>8&255,e[r+2]=s>>16&255,e[r+3]=s>>24&255,r=r+4+s-1,e[r++]=0,r},k=function(e,t,n,r,o,s,i){e[r++]=R.BSON_DATA_OBJECT,r+=i?e.write(t,r,"ascii"):e.write(t,r,"utf8"),e[r++]=0;var a,c=r,u=(a=null!=n.db?M(e,{$ref:n.namespace,$id:n.oid,$db:n.db},!1,r,o+1,s):M(e,{$ref:n.namespace,$id:n.oid},!1,r,o+1,s))-c;return e[c++]=255&u,e[c++]=u>>8&255,e[c++]=u>>16&255,e[c++]=u>>24&255,a},M=function(e,t,n,r,o,i,a,M){r=r||0,(M=M||[]).push(t);var R=r+4;if(Array.isArray(t))for(var D=0;D>8&255,e[r++]=F>>16&255,e[r++]=F>>24&255,R},R={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};R.BSON_INT64_MAX=Math.pow(2,63)-1,R.BSON_INT64_MIN=-Math.pow(2,63),R.JS_INT_MAX=9007199254740992,R.JS_INT_MIN=-9007199254740992,e.exports=M},function(e,t){t.readIEEE754=function(e,t,n,r,o){var s,i,a="big"===n,c=8*o-r-1,u=(1<>1,p=-7,h=a?0:o-1,f=a?1:-1,d=e[t+h];for(h+=f,s=d&(1<<-p)-1,d>>=-p,p+=c;p>0;s=256*s+e[t+h],h+=f,p-=8);for(i=s&(1<<-p)-1,s>>=-p,p+=r;p>0;i=256*i+e[t+h],h+=f,p-=8);if(0===s)s=1-l;else{if(s===u)return i?NaN:1/0*(d?-1:1);i+=Math.pow(2,r),s-=l}return(d?-1:1)*i*Math.pow(2,s-r)},t.writeIEEE754=function(e,t,n,r,o,s){var i,a,c,u="big"===r,l=8*s-o-1,p=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,d=u?s-1:0,m=u?-1:1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=p):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=p?(a=0,i=p):i+h>=1?(a=(t*c-1)*Math.pow(2,o),i+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,o),i=0));o>=8;e[n+d]=255&a,d+=m,a/=256,o-=8);for(i=i<0;e[n+d]=255&i,d+=m,i/=256,l-=8);e[n+d-m]|=128*y}},function(e,t,n){"use strict";var r=n(33).Long,o=n(48).Double,s=n(49).Timestamp,i=n(50).ObjectID,a=n(52).Symbol,c=n(51).BSONRegExp,u=n(53).Code,l=n(54),p=n(55).MinKey,h=n(56).MaxKey,f=n(57).DBRef,d=n(38).Binary,m=n(28).normalizedFunctionString,y=function(e,t,n){var r=5;if(Array.isArray(e))for(var o=0;o=b.JS_INT_MIN&&t<=b.JS_INT_MAX&&t>=b.BSON_INT32_MIN&&t<=b.BSON_INT32_MAX?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+5:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;case"undefined":return g||!S?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1:0;case"boolean":return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+2;case"object":if(null==t||t instanceof p||t instanceof h||"MinKey"===t._bsontype||"MaxKey"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1;if(t instanceof i||"ObjectID"===t._bsontype||"ObjectId"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+13;if(t instanceof Date||"object"==typeof(w=t)&&"[object Date]"===Object.prototype.toString.call(w))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+6+t.length;if(t instanceof r||t instanceof o||t instanceof s||"Long"===t._bsontype||"Double"===t._bsontype||"Timestamp"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+9;if(t instanceof l||"Decimal128"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+17;if(t instanceof u||"Code"===t._bsontype)return null!=t.scope&&Object.keys(t.scope).length>0?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+y(t.scope,n,S):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1;if(t instanceof d||"Binary"===t._bsontype)return t.sub_type===d.SUBTYPE_BYTE_ARRAY?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4):(null!=e?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1);if(t instanceof a||"Symbol"===t._bsontype)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1;if(t instanceof f||"DBRef"===t._bsontype){var v={$ref:t.namespace,$id:t.oid};return null!=t.db&&(v.$db=t.db),(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+y(v,n,S)}return t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1:t instanceof c||"BSONRegExp"===t._bsontype?(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1:(null!=e?Buffer.byteLength(e,"utf8")+1:0)+y(t,n,S)+1;case"function":if(t instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(t)||"[object RegExp]"===String.call(t))return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.source,"utf8")+1+(t.global?1:0)+(t.ignoreCase?1:0)+(t.multiline?1:0)+1;if(n&&null!=t.scope&&Object.keys(t.scope).length>0)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(m(t),"utf8")+1+y(t.scope,n,S);if(n)return(null!=e?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(m(t),"utf8")+1}var w;return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};e.exports=y},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){"use strict";var r=n(39),o=n(141);e.exports=function(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("Expected `fromDir` and `moduleId` to be a string");e=r.resolve(e);var n=r.join(e,"noop.js");try{return o._resolveFilename(t,{id:n,filename:n,paths:o._nodeModulePaths(e)})}catch(e){return null}}},function(e,t){e.exports=require("module")},function(e,t){var n;t=e.exports=V,n="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var r=Number.MAX_SAFE_INTEGER||9007199254740991,o=t.re=[],s=t.src=[],i=0,a=i++;s[a]="0|[1-9]\\d*";var c=i++;s[c]="[0-9]+";var u=i++;s[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var l=i++;s[l]="("+s[a]+")\\.("+s[a]+")\\.("+s[a]+")";var p=i++;s[p]="("+s[c]+")\\.("+s[c]+")\\.("+s[c]+")";var h=i++;s[h]="(?:"+s[a]+"|"+s[u]+")";var f=i++;s[f]="(?:"+s[c]+"|"+s[u]+")";var d=i++;s[d]="(?:-("+s[h]+"(?:\\."+s[h]+")*))";var m=i++;s[m]="(?:-?("+s[f]+"(?:\\."+s[f]+")*))";var y=i++;s[y]="[0-9A-Za-z-]+";var g=i++;s[g]="(?:\\+("+s[y]+"(?:\\."+s[y]+")*))";var b=i++,S="v?"+s[l]+s[d]+"?"+s[g]+"?";s[b]="^"+S+"$";var v="[v=\\s]*"+s[p]+s[m]+"?"+s[g]+"?",w=i++;s[w]="^"+v+"$";var _=i++;s[_]="((?:<|>)?=?)";var O=i++;s[O]=s[c]+"|x|X|\\*";var T=i++;s[T]=s[a]+"|x|X|\\*";var E=i++;s[E]="[v=\\s]*("+s[T]+")(?:\\.("+s[T]+")(?:\\.("+s[T]+")(?:"+s[d]+")?"+s[g]+"?)?)?";var C=i++;s[C]="[v=\\s]*("+s[O]+")(?:\\.("+s[O]+")(?:\\.("+s[O]+")(?:"+s[m]+")?"+s[g]+"?)?)?";var x=i++;s[x]="^"+s[_]+"\\s*"+s[E]+"$";var A=i++;s[A]="^"+s[_]+"\\s*"+s[C]+"$";var N=i++;s[N]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var I=i++;s[I]="(?:~>?)";var k=i++;s[k]="(\\s*)"+s[I]+"\\s+",o[k]=new RegExp(s[k],"g");var M=i++;s[M]="^"+s[I]+s[E]+"$";var R=i++;s[R]="^"+s[I]+s[C]+"$";var D=i++;s[D]="(?:\\^)";var B=i++;s[B]="(\\s*)"+s[D]+"\\s+",o[B]=new RegExp(s[B],"g");var P=i++;s[P]="^"+s[D]+s[E]+"$";var L=i++;s[L]="^"+s[D]+s[C]+"$";var j=i++;s[j]="^"+s[_]+"\\s*("+v+")$|^$";var U=i++;s[U]="^"+s[_]+"\\s*("+S+")$|^$";var z=i++;s[z]="(\\s*)"+s[_]+"\\s*("+v+"|"+s[E]+")",o[z]=new RegExp(s[z],"g");var F=i++;s[F]="^\\s*("+s[E]+")\\s+-\\s+("+s[E]+")\\s*$";var W=i++;s[W]="^\\s*("+s[C]+")\\s+-\\s+("+s[C]+")\\s*$";var q=i++;s[q]="(<|>)?=?\\s*\\*";for(var $=0;$<35;$++)n($,s[$]),o[$]||(o[$]=new RegExp(s[$]));function H(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?o[w]:o[b]).test(e))return null;try{return new V(e,t)}catch(e){return null}}function V(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof V){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof V))return new V(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var s=e.trim().match(t.loose?o[w]:o[b]);if(!s)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);-1===n&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,n,r){"string"==typeof n&&(r=n,n=void 0);try{return new V(e,n).inc(t,r).version}catch(e){return null}},t.diff=function(e,t){if(Z(e,t))return null;var n=H(e),r=H(t),o="";if(n.prerelease.length||r.prerelease.length){o="pre";var s="prerelease"}for(var i in n)if(("major"===i||"minor"===i||"patch"===i)&&n[i]!==r[i])return o+i;return s},t.compareIdentifiers=G;var Y=/^[0-9]+$/;function G(e,t){var n=Y.test(e),r=Y.test(t);return n&&r&&(e=+e,t=+t),e===t?0:n&&!r?-1:r&&!n?1:e0}function J(e,t,n){return K(e,t,n)<0}function Z(e,t,n){return 0===K(e,t,n)}function Q(e,t,n){return 0!==K(e,t,n)}function ee(e,t,n){return K(e,t,n)>=0}function te(e,t,n){return K(e,t,n)<=0}function ne(e,t,n,r){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return Z(e,n,r);case"!=":return Q(e,n,r);case">":return X(e,n,r);case">=":return ee(e,n,r);case"<":return J(e,n,r);case"<=":return te(e,n,r);default:throw new TypeError("Invalid operator: "+t)}}function re(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof re){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof re))return new re(e,t);n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===oe?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}t.rcompareIdentifiers=function(e,t){return G(t,e)},t.major=function(e,t){return new V(e,t).major},t.minor=function(e,t){return new V(e,t).minor},t.patch=function(e,t){return new V(e,t).patch},t.compare=K,t.compareLoose=function(e,t){return K(e,t,!0)},t.rcompare=function(e,t,n){return K(t,e,n)},t.sort=function(e,n){return e.sort((function(e,r){return t.compare(e,r,n)}))},t.rsort=function(e,n){return e.sort((function(e,r){return t.rcompare(e,r,n)}))},t.gt=X,t.lt=J,t.eq=Z,t.neq=Q,t.gte=ee,t.lte=te,t.cmp=ne,t.Comparator=re;var oe={};function se(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof se)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new se(e.raw,t);if(e instanceof re)return new se(e.value,t);if(!(this instanceof se))return new se(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ie(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,n,r,o,s,i,a,c,u,l,p,h){return((t=ie(n)?"":ie(r)?">="+n+".0.0":ie(o)?">="+n+"."+r+".0":">="+t)+" "+(a=ie(c)?"":ie(u)?"<"+(+c+1)+".0.0":ie(l)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+l+"-"+p:"<="+a)).trim()}function ce(e,t,r){for(var o=0;o0){var s=e[o].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}function ue(e,t,n){try{t=new se(t,n)}catch(e){return!1}return t.test(e)}function le(e,t,n,r){var o,s,i,a,c;switch(e=new V(e,r),t=new se(t,r),n){case">":o=X,s=te,i=J,a=">",c=">=";break;case"<":o=J,s=ee,i=X,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,r))return!1;for(var u=0;u=0.0.0")),p=p||e,h=h||e,o(e.semver,p.semver,r)?p=e:i(e.semver,h.semver,r)&&(h=e)})),p.operator===a||p.operator===c)return!1;if((!h.operator||h.operator===a)&&s(e,h.semver))return!1;if(h.operator===c&&i(e,h.semver))return!1}return!0}re.prototype.parse=function(e){var t=this.options.loose?o[j]:o[U],n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1],"="===this.operator&&(this.operator=""),n[2]?this.semver=new V(n[2],this.options.loose):this.semver=oe},re.prototype.toString=function(){return this.value},re.prototype.test=function(e){return n("Comparator.test",e,this.options.loose),this.semver===oe||("string"==typeof e&&(e=new V(e,this.options)),ne(e,this.operator,this.semver,this.options))},re.prototype.intersects=function(e,t){if(!(e instanceof re))throw new TypeError("a Comparator is required");var n;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return n=new se(e.value,t),ue(this.value,n,t);if(""===e.operator)return n=new se(this.value,t),ue(e.semver,n,t);var r=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),o=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),s=this.semver.version===e.semver.version,i=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=ne(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=ne(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return r||o||s&&i||a||c},t.Range=se,se.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},se.prototype.toString=function(){return this.range},se.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var r=t?o[W]:o[F];e=e.replace(r,ae),n("hyphen replace",e),e=e.replace(o[z],"$1$2$3"),n("comparator trim",e,o[z]),e=(e=(e=e.replace(o[k],"$1~")).replace(o[B],"$1^")).split(/\s+/).join(" ");var s=t?o[j]:o[U],i=e.split(" ").map((function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){n("caret",e,t);var r=t.loose?o[L]:o[P];return e.replace(r,(function(t,r,o,s,i){var a;return n("caret",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a="0"===r?">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":">="+r+"."+o+".0 <"+(+r+1)+".0.0":i?(n("replaceCaret pr",i),a="0"===r?"0"===o?">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+"-"+i+" <"+(+r+1)+".0.0"):(n("no pr"),a="0"===r?"0"===o?">="+r+"."+o+"."+s+" <"+r+"."+o+"."+(+s+1):">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0":">="+r+"."+o+"."+s+" <"+(+r+1)+".0.0"),n("caret return",a),a}))}(e,t)})).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var r=t.loose?o[R]:o[M];return e.replace(r,(function(t,r,o,s,i){var a;return n("tilde",e,t,r,o,s,i),ie(r)?a="":ie(o)?a=">="+r+".0.0 <"+(+r+1)+".0.0":ie(s)?a=">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0":i?(n("replaceTilde pr",i),a=">="+r+"."+o+"."+s+"-"+i+" <"+r+"."+(+o+1)+".0"):a=">="+r+"."+o+"."+s+" <"+r+"."+(+o+1)+".0",n("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var r=t.loose?o[A]:o[x];return e.replace(r,(function(t,r,o,s,i,a){n("xRange",e,t,r,o,s,i,a);var c=ie(o),u=c||ie(s),l=u||ie(i);return"="===r&&l&&(r=""),c?t=">"===r||"<"===r?"<0.0.0":"*":r&&l?(u&&(s=0),i=0,">"===r?(r=">=",u?(o=+o+1,s=0,i=0):(s=+s+1,i=0)):"<="===r&&(r="<",u?o=+o+1:s=+s+1),t=r+o+"."+s+"."+i):u?t=">="+o+".0.0 <"+(+o+1)+".0.0":l&&(t=">="+o+"."+s+".0 <"+o+"."+(+s+1)+".0"),n("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(o[q],"")}(e,t),n("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(i=i.filter((function(e){return!!e.match(s)}))),i=i.map((function(e){return new re(e,this.options)}),this)},se.prototype.intersects=function(e,t){if(!(e instanceof se))throw new TypeError("a Range is required");return this.set.some((function(n){return n.every((function(n){return e.set.some((function(e){return e.every((function(e){return n.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new se(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},se.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new V(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!X(n,t)||(n=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(n&&e.test(n))return n;return null},t.validRange=function(e,t){try{return new se(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,n){return le(e,t,"<",n)},t.gtr=function(e,t,n){return le(e,t,">",n)},t.outside=le,t.prerelease=function(e,t){var n=H(e,t);return n&&n.prerelease.length?n.prerelease:null},t.intersects=function(e,t,n){return e=new se(e,n),t=new se(t,n),e.intersects(t)},t.coerce=function(e){if(e instanceof V)return e;if("string"!=typeof e)return null;var t=e.match(o[N]);if(null==t)return null;return H(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}},function(e,t){e.exports=require("os")},function(e){e.exports=JSON.parse('{"_from":"mongodb@^3.6.0","_id":"mongodb@3.6.0","_inBundle":false,"_integrity":"sha512-/XWWub1mHZVoqEsUppE0GV7u9kanLvHxho6EvBxQbShXTKYF9trhZC2NzbulRGeG7xMJHD8IOWRcdKx5LPjAjQ==","_location":"/mongodb","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"mongodb@^3.6.0","name":"mongodb","escapedName":"mongodb","rawSpec":"^3.6.0","saveSpec":null,"fetchSpec":"^3.6.0"},"_requiredBy":["#DEV:/","/mongodb-memory-server-core"],"_resolved":"https://registry.npmjs.org/mongodb/-/mongodb-3.6.0.tgz","_shasum":"babd7172ec717e2ed3f85e079b3f1aa29dce4724","_spec":"mongodb@^3.6.0","_where":"/repos/.nhscc/airports.api.hscc.bdpa.org","bugs":{"url":"https://github.com/mongodb/node-mongodb-native/issues"},"bundleDependencies":false,"dependencies":{"bl":"^2.2.0","bson":"^1.1.4","denque":"^1.4.1","require_optional":"^1.0.1","safe-buffer":"^5.1.2","saslprep":"^1.0.0"},"deprecated":false,"description":"The official MongoDB driver for Node.js","devDependencies":{"chai":"^4.1.1","chai-subset":"^1.6.0","chalk":"^2.4.2","co":"4.6.0","coveralls":"^2.11.6","eslint":"^4.5.0","eslint-plugin-prettier":"^2.2.0","istanbul":"^0.4.5","jsdoc":"3.5.5","lodash.camelcase":"^4.3.0","mocha":"5.2.0","mocha-sinon":"^2.1.0","mongodb-extjson":"^2.1.1","mongodb-mock-server":"^1.0.1","prettier":"^1.19.1","semver":"^5.5.0","sinon":"^4.3.0","sinon-chai":"^3.2.0","snappy":"^6.3.4","standard-version":"^4.4.0","util.promisify":"^1.0.1","worker-farm":"^1.5.0","wtfnode":"^0.8.0","yargs":"^14.2.0"},"engines":{"node":">=4"},"files":["index.js","lib"],"homepage":"https://github.com/mongodb/node-mongodb-native","keywords":["mongodb","driver","official"],"license":"Apache-2.0","main":"index.js","name":"mongodb","optionalDependencies":{"saslprep":"^1.0.0"},"peerOptionalDependencies":{"kerberos":"^1.1.0","mongodb-client-encryption":"^1.0.0","mongodb-extjson":"^2.1.2","snappy":"^6.3.4","bson-ext":"^2.0.0"},"repository":{"type":"git","url":"git+ssh://git@github.com/mongodb/node-mongodb-native.git"},"scripts":{"atlas":"mocha --opts \'{}\' ./test/manual/atlas_connectivity.test.js","bench":"node test/benchmarks/driverBench/","coverage":"istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional","format":"prettier --print-width 100 --tab-width 2 --single-quote --write \'test/**/*.js\' \'lib/**/*.js\'","generate-evergreen":"node .evergreen/generate_evergreen_tasks.js","lint":"eslint -v && eslint lib test","release":"standard-version -i HISTORY.md","test":"npm run lint && mocha --recursive test/functional test/unit test/core","test-nolint":"mocha --recursive test/functional test/unit test/core"},"version":"3.6.0"}')},function(e,t){e.exports=require("zlib")},function(e,t,n){"use strict";const r=n(5).inherits,o=n(10).EventEmitter,s=n(2).MongoError,i=n(2).MongoTimeoutError,a=n(2).MongoWriteConcernError,c=n(19),u=n(5).format,l=n(35).Msg,p=n(74),h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(94),S=n(16).Buffer,v=n(76),w=n(31).updateSessionFromResponse,_=n(4).eachAsync,O=n(4).makeStateMachine,T=n(0).now,E="destroying",C="destroyed",x=O({disconnected:["connecting","draining","disconnected"],connecting:["connecting","connected","draining","disconnected"],connected:["connected","disconnected","draining"],draining:["draining",E,C],[E]:[E,C],[C]:[C]}),A=new Set(["error","close","timeout","parseError","connect","message"]);var N=0,I=function(e,t){if(o.call(this),this.topology=e,this.s={state:"disconnected",cancellationToken:new o},this.s.cancellationToken.setMaxListeners(1/0),this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:36e4,keepAlive:!0,keepAliveInitialDelay:12e4,noDelay:!0,ssl:!1,checkServerIdentity:!0,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,reconnect:!0,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:!1,legacyCompatMode:!0},t),this.id=N++,this.retriesLeft=this.options.reconnectTries,this.reconnectId=null,this.reconnectError=null,!t.bson||t.bson&&("function"!=typeof t.bson.serialize||"function"!=typeof t.bson.deserialize))throw new Error("must pass in valid bson parser");this.logger=c("Pool",t),this.availableConnections=[],this.inUseConnections=[],this.connectingConnections=0,this.executing=!1,this.queue=[],this.numberOfConsecutiveTimeouts=0,this.connectionIndex=0;const n=this;this._messageHandler=function(e){return function(t,n){for(var r=null,o=0;oe.options.reconnectTries))return e.numberOfConsecutiveTimeouts=0,e.destroy(!0),e.emit("close",e);0===e.socketCount()&&(e.state!==C&&e.state!==E&&"draining"!==e.state&&e.options.reconnect&&x(e,"disconnected"),t="error"===t?"close":t,e.emit(t,n)),!e.reconnectId&&e.options.reconnect&&(e.reconnectError=n,e.reconnectId=setTimeout(R(e),e.options.reconnectInterval));B(e){null==n&&(e.reconnectId=null,e.retriesLeft=e.options.reconnectTries,e.emit("reconnect",e)),"function"==typeof t&&t(n,r)})}else"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}}function D(e,t,n){var r=t.indexOf(e);-1!==r&&(t.splice(r,1),n.push(e))}function B(e){return e.availableConnections.length+e.inUseConnections.length+e.connectingConnections}function P(e,t,n,r){x(e,E),e.s.cancellationToken.emit("cancel"),_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.on("error",()=>{}),e.destroy(n,t)},t=>{t?"function"==typeof r&&r(t,null):(k(e),e.queue=[],x(e,C),"function"==typeof r&&r(null,null))})}function L(e,t,n){const r=t.toBin();if(!!!e.options.agreedCompressor||!function(e){const t=e instanceof l?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(t))return n(null,r);const o=S.concat(r),s=o.slice(h),i=o.readInt32LE(12);m(e,s,(function(r,o){if(r)return n(r,null);const a=S.alloc(h);a.writeInt32LE(h+f+o.length,0),a.writeInt32LE(t.requestId,4),a.writeInt32LE(0,8),a.writeInt32LE(d.OP_COMPRESSED,12);const c=S.alloc(f);return c.writeInt32LE(i,0),c.writeInt32LE(s.length,4),c.writeUInt8(y[e.options.agreedCompressor],8),n(null,[a,c,o])}))}function j(e,t){for(var n=0;n(e.connectingConnections--,n?(e.logger.isDebug()&&e.logger.debug(`connection attempt failed with error [${JSON.stringify(n)}]`),!e.reconnectId&&e.options.reconnect?"connecting"===e.state&&e.options.legacyCompatMode?void t(n):(e.reconnectError=n,void(e.reconnectId=setTimeout(R(e,t),e.options.reconnectInterval))):void("function"==typeof t&&t(n))):e.state===C||e.state===E?("function"==typeof t&&t(new s("Pool was destroyed after connection creation")),void r.destroy()):(r.on("error",e._connectionErrorHandler),r.on("close",e._connectionCloseHandler),r.on("timeout",e._connectionTimeoutHandler),r.on("parseError",e._connectionParseErrorHandler),r.on("message",e._messageHandler),e.availableConnections.push(r),"function"==typeof t&&t(null,r),void W(e)())))):"function"==typeof t&&t(new s("Cannot create connection when pool is destroyed"))}function F(e){for(var t=0;t0)e.executing=!1;else{for(;;){const i=B(e);if(0===e.availableConnections.length){F(e.queue),i0&&z(e);break}if(0===e.queue.length)break;var t=null;const a=e.availableConnections.filter(e=>0===e.workItems.length);if(!(t=0===a.length?e.availableConnections[e.connectionIndex++%e.availableConnections.length]:a[e.connectionIndex++%a.length]).isConnected()){U(e,t),F(e.queue);break}var n=e.queue.shift();if(n.monitoring){var r=!1;for(let n=0;n0&&z(e),setTimeout(()=>W(e)(),10);break}}if(i0){e.queue.unshift(n),z(e);break}var o=n.buffer;n.monitoring&&D(t,e.availableConnections,e.inUseConnections),n.noResponse||t.workItems.push(n),n.immediateRelease||"number"!=typeof n.socketTimeout||t.setSocketTimeout(n.socketTimeout);var s=!0;if(Array.isArray(o))for(let e=0;e{if(t)return"function"==typeof e?(this.destroy(),void e(t)):("connecting"===this.state&&this.emit("error",t),void this.destroy());if(x(this,"connected"),this.minSize)for(let e=0;e0;){var o=n.queue.shift();"function"==typeof o.cb&&o.cb(new s("Pool was force destroyed"))}return P(n,r,{force:!0},t)}this.reconnectId&&clearTimeout(this.reconnectId),function e(){if(n.state!==C&&n.state!==E)if(F(n.queue),0===n.queue.length){for(var r=n.availableConnections.concat(n.inUseConnections),o=0;o0)return setTimeout(e,1);P(n,r,{force:!1},t)}else W(n)(),setTimeout(e,1);else"function"==typeof t&&t()}()}else"function"==typeof t&&t(null,null)},I.prototype.reset=function(e){if("connected"!==this.s.state)return void("function"==typeof e&&e(new s("pool is not connected, reset aborted")));this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);_(t,(e,t)=>{for(const t of A)e.removeAllListeners(t);e.destroy({force:!0},t)},t=>{t&&"function"==typeof e?e(t,null):(k(this),z(this,()=>{"function"==typeof e&&e(null,null)}))})},I.prototype.write=function(e,t,n){var r=this;if("function"==typeof t&&(n=t),t=t||{},"function"!=typeof n&&!t.noResponse)throw new s("write method must provide a callback");if(this.state!==C&&this.state!==E)if("draining"!==this.state){if(this.options.domainsEnabled&&process.domain&&"function"==typeof n){var o=n;n=process.domain.bind((function(){for(var e=new Array(arguments.length),t=0;t{t?r.emit("commandFailed",new b.CommandFailedEvent(this,e,t,i.started)):o&&o.result&&(0===o.result.ok||o.result.$err)?r.emit("commandFailed",new b.CommandFailedEvent(this,e,o.result,i.started)):r.emit("commandSucceeded",new b.CommandSucceededEvent(this,e,o,i.started)),"function"==typeof n&&n(t,o)}),L(r,e,(e,n)=>{if(e)throw e;i.buffer=n,t.monitoring?r.queue.unshift(i):r.queue.push(i),r.executing||process.nextTick((function(){W(r)()}))})}else n(new s("pool is draining, new operations prohibited"));else n(new s("pool destroyed"))},I._execute=W,e.exports=I},function(e,t){e.exports=require("net")},function(e,t,n){"use strict";const{unassigned_code_points:r,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:c}=n(149);e.exports=function(e,t={}){if("string"!=typeof e)throw new TypeError("Expected string.");if(0===e.length)return"";const n=h(e).map(e=>u.get(e)?32:e).filter(e=>!l.get(e)),o=String.fromCodePoint.apply(null,n).normalize("NFKC"),s=h(o);if(s.some(e=>i.get(e)))throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3");if(!0!==t.allowUnassigned){if(s.some(e=>r.get(e)))throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}const f=s.some(e=>a.get(e)),d=s.some(e=>c.get(e));if(f&&d)throw new Error("String must not contain RandALCat and LCat at the same time, see https://tools.ietf.org/html/rfc3454#section-6");const m=a.get(p((g=o,g[0]))),y=a.get(p((e=>e[e.length-1])(o)));var g;if(f&&(!m||!y))throw new Error("Bidirectional RandALCat character must be the first and the last character of the string, see https://tools.ietf.org/html/rfc3454#section-6");return o};const u=s,l=o,p=e=>e.codePointAt(0);function h(e){const t=[],n=e.length;for(let r=0;r=55296&&o<=56319&&n>r+1){const n=e.charCodeAt(r+1);if(n>=56320&&n<=57343){t.push(1024*(o-55296)+n-56320+65536),r+=1;continue}}t.push(o)}return t}},function(e,t,n){"use strict";(function(t){const r=n(40),o=n(39),s=n(150),i=r.readFileSync(o.resolve(t,"../code-points.mem"));let a=0;function c(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);return a+=e,s({buffer:t})}const u=c(),l=c(),p=c(),h=c(),f=c(),d=c();e.exports={unassigned_code_points:u,commonly_mapped_to_nothing:l,non_ASCII_space_characters:p,prohibited_characters:h,bidirectional_r_al:f,bidirectional_l:d}}).call(this,"/")},function(e,t,n){var r=n(151);function o(e){if(!(this instanceof o))return new o(e);if(e||(e={}),Buffer.isBuffer(e)&&(e={buffer:e}),this.pageOffset=e.pageOffset||0,this.pageSize=e.pageSize||1024,this.pages=e.pages||r(this.pageSize),this.byteLength=this.pages.length*this.pageSize,this.length=8*this.byteLength,(t=this.pageSize)&t-1)throw new Error("The page size should be a power of two");var t;if(this._trackUpdates=!!e.trackUpdates,this._pageMask=this.pageSize-1,e.buffer){for(var n=0;n>t)},o.prototype.getByte=function(e){var t=e&this._pageMask,n=(e-t)/this.pageSize,r=this.pages.get(n,!0);return r?r.buffer[t+this.pageOffset]:0},o.prototype.set=function(e,t){var n=7&e,r=(e-n)/8,o=this.getByte(r);return this.setByte(r,t?o|128>>n:o&(255^128>>n))},o.prototype.toBuffer=function(){for(var e=function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}(this.pages.length*this.pageSize),t=0;t=this.byteLength&&(this.byteLength=e+1,this.length=8*this.byteLength),this._trackUpdates&&this.pages.updated(o),!0)}},function(e,t){function n(e,t){if(!(this instanceof n))return new n(e,t);this.length=0,this.updates=[],this.path=new Uint16Array(4),this.pages=new Array(32768),this.maxPages=this.pages.length,this.level=0,this.pageSize=e||1024,this.deduplicate=t?t.deduplicate:null,this.zeros=this.deduplicate?r(this.deduplicate.length):null}function r(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t}function o(e,t){this.offset=e*t.length,this.buffer=t,this.updated=!1,this.deduplicate=0}e.exports=n,n.prototype.updated=function(e){for(;this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate];)if(e.deduplicate++,e.deduplicate===this.deduplicate.length){e.deduplicate=0,e.buffer.equals&&e.buffer.equals(this.deduplicate)&&(e.buffer=this.deduplicate);break}!e.updated&&this.updates&&(e.updated=!0,this.updates.push(e))},n.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();return e.updated=!1,e},n.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;!function(e,t){for(;e.maxPages0;s--){var i=this.path[s],a=o[i];if(!a){if(t)return;a=o[i]=new Array(32768)}o=a}return o},n.prototype.get=function(e,t){var n,s,i=this._array(e,t),a=this.path[0],c=i&&i[a];return c||t||(c=i[a]=new o(e,r(this.pageSize)),e>=this.length&&(this.length=e+1)),c&&c.buffer===this.deduplicate&&this.deduplicate&&!t&&(c.buffer=(n=c.buffer,s=Buffer.allocUnsafe?Buffer.allocUnsafe(n.length):new Buffer(n.length),n.copy(s),s),c.deduplicate=0),c},n.prototype.set=function(e,t){var n=this._array(e,!1),s=this.path[0];if(e>=this.length&&(this.length=e+1),!t||this.zeros&&t.equals&&t.equals(this.zeros))n[s]=void 0;else{this.deduplicate&&t.equals&&t.equals(this.deduplicate)&&(t=this.deduplicate);var i=n[s],a=function(e,t){if(e.length===t)return e;if(e.length>t)return e.slice(0,t);var n=r(t);return e.copy(n),n}(t,this.pageSize);i?i.buffer=a:n[s]=new o(e,a)}},n.prototype.toBuffer=function(){for(var e=new Array(this.length),t=r(this.pageSize),n=0;n{e.setEncoding("utf8");let r="";e.on("data",e=>r+=e),e.on("end",()=>{if(!1!==t.json)try{const e=JSON.parse(r);n(void 0,e)}catch(e){n(new s(`Invalid JSON response: "${r}"`))}else n(void 0,r)})});r.on("error",e=>n(e)),r.end()}e.exports=class extends r{auth(e,t){const n=e.connection,r=e.credentials;if(c(n)<9)return void t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));if(null==l)return void t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));if(null==r.username)return void function(e,t){function n(n){null!=n.AccessKeyId&&null!=n.SecretAccessKey&&null!=n.Token?t(void 0,new o({username:n.AccessKeyId,password:n.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:n.Token}})):t(new s("Could not obtain temporary MONGODB-AWS credentials"))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)return void d("http://169.254.170.2"+process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,(e,r)=>{if(e)return t(e);n(r)});d(p+"/latest/api/token",{method:"PUT",json:!1,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},(e,r)=>{if(e)return t(e);d(`${p}/${h}`,{json:!1,headers:{"X-aws-ec2-metadata-token":r}},(e,o)=>{if(e)return t(e);d(`${p}/${h}/${o}`,{headers:{"X-aws-ec2-metadata-token":r}},(e,r)=>{if(e)return t(e);n(r)})})})}(r,(n,r)=>{if(n)return t(n);e.credentials=r,this.auth(e,t)});const a=r.username,u=r.password,m=r.source,y=r.mechanismProperties.AWS_SESSION_TOKEN,g=this.bson;i.randomBytes(32,(e,r)=>{if(e)return void t(e);const o={saslStart:1,mechanism:"MONGODB-AWS",payload:g.serialize({r:r,p:110})};n.command(m+".$cmd",o,(e,o)=>{if(e)return t(e);const i=o.result,c=g.deserialize(i.payload.buffer),p=c.h,h=c.s.buffer;if(64!==h.length)return void t(new s(`Invalid server nonce length ${h.length}, expected 64`));if(0!==h.compare(r,0,r.length,0,r.length))return void t(new s("Server nonce does not begin with client nonce"));if(p.length<1||p.length>255||-1!==p.indexOf(".."))return void t(new s(`Server returned an invalid host: "${p}"`));const d="Action=GetCallerIdentity&Version=2011-06-15",b=l.sign({method:"POST",host:p,region:f(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":d.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:d},{accessKeyId:a,secretAccessKey:u,token:y}),S={a:b.headers.Authorization,d:b.headers["X-Amz-Date"]};y&&(S.t=y);const v={saslContinue:1,conversationId:1,payload:g.serialize(S)};n.command(m+".$cmd",v,e=>{if(e)return t(e);t()})})})}}},function(e,t){e.exports=require("http")},function(e,t,n){var r=t,o=n(59),s=n(102),i=n(21),a=n(155)(1e3);function c(e,t,n){return i.createHmac("sha256",e).update(t,"utf8").digest(n)}function u(e,t){return i.createHash("sha256").update(e,"utf8").digest(t)}function l(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function p(e){return l(encodeURIComponent(e))}function h(e,t){"string"==typeof e&&(e=o.parse(e));var n=e.headers=e.headers||{},r=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||n.Host||n.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||r[0]||"",this.region=e.region||r[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),n.Host||n.host||(n.Host=e.hostname||e.host||this.createHost(),e.port&&(n.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=n.Host||n.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}h.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var n=0;n<2;n++)if(/^s3-/.test(t[n])){t[1]=t[n].slice(3),t[0]="s3";break}return t},h.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},h.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},h.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,n=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||n["Content-Type"]||n["content-type"]||(n["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||n["Content-Length"]||n["content-length"]||(n["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||n["X-Amz-Security-Token"]||n["x-amz-security-token"]||(n["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||n["X-Amz-Content-Sha256"]||n["x-amz-content-sha256"]||(n["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),n["X-Amz-Date"]||n["x-amz-date"]?this.datetime=n["X-Amz-Date"]||n["x-amz-date"]:n["X-Amz-Date"]=this.getDateTime()),delete n.Authorization,delete n.authorization)},h.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},h.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},h.prototype.getDate=function(){return this.getDateTime().substr(0,8)},h.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},h.prototype.signature=function(){var e,t,n,r=this.getDate(),o=[this.credentials.secretAccessKey,r,this.region,this.service].join(),s=a.get(o);return s||(e=c("AWS4"+this.credentials.secretAccessKey,r),t=c(e,this.region),n=c(t,this.service),s=c(n,"aws4_request"),a.set(o,s)),c(s,this.stringToSign(),"hex")},h.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},h.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,n=this.parsedPath.query,r=this.request.headers,o="",s="s3"!==this.service,i="s3"===this.service||this.request.doNotEncodePath,a="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":r["X-Amz-Content-Sha256"]||r["x-amz-content-sha256"]||u(this.request.body||"","hex"),n){var l=Object.keys(n).reduce((function(e,t){return t?(e[p(t)]=Array.isArray(n[t])&&c?n[t][0]:n[t],e):e}),{}),h=[];Object.keys(l).sort().forEach((function(e){Array.isArray(l[e])?l[e].map(p).sort().forEach((function(t){h.push(e+"="+t)})):h.push(e+"="+p(l[e]))})),o=h.join("&")}return"/"!==t&&(s&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return s&&".."===t?e.pop():s&&"."===t||(i&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(p(t))),e}),[]).join("/"))[0]&&(t="/"+t),a&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,o,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},h.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).sort((function(e,t){return e.toLowerCase()=0&&(n=s.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:n}},h.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+l(s.stringify(t))):e},r.RequestSigner=h,r.sign=function(e,t){return new h(e,t).sign()}},function(e,t){function n(e){this.capacity=0|e,this.map=Object.create(null),this.list=new r}function r(){this.firstNode=null,this.lastNode=null}function o(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}e.exports=function(e){return new n(e)},n.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},n.prototype.set=function(e,t){var n=this.map[e];if(null!=n)n.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;n=new o(e,t),this.map[e]=n,this.capacity--}return this.used(n),!0},n.prototype.used=function(e){this.list.moveToFront(e)},n.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},r.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},r.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},r.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)}},function(e,t,n){"use strict";const r=n(2).MongoError,o=n(7).collectionNamespace,s=n(42);e.exports=function(e,t,n,i,a,c,u){if(0===a.length)throw new r(t+" must contain at least one document");"function"==typeof c&&(u=c,c={});const l="boolean"!=typeof(c=c||{}).ordered||c.ordered,p=c.writeConcern,h={};if(h[t]=o(i),h[n]=a,h.ordered=l,p&&Object.keys(p).length>0&&(h.writeConcern=p),c.collation)for(let e=0;e{};const l=n.cursorId;if(a(e)<4){const o=e.s.bson,s=e.s.pool,i=new r(o,t,[l]),a={immediateRelease:!0,noResponse:!0};if("object"==typeof n.session&&(a.session=n.session),s&&s.isConnected())try{s.write(i,a,u)}catch(e){"function"==typeof u?u(e,null):console.warn(e)}return}const p={killCursors:i(t),cursors:[l]},h={};"object"==typeof n.session&&(h.session=n.session),c(e,t,p,h,(e,t)=>{if(e)return u(e);const n=t.message;return n.cursorNotFound?u(new s("cursor killed or timed out"),null):Array.isArray(n.documents)&&0!==n.documents.length?void u(null,n.documents[0]):u(new o("invalid killCursors result returned for cursor id "+l))})}},function(e,t,n){"use strict";const r=n(22).GetMore,o=n(11).retrieveBSON,s=n(2).MongoError,i=n(2).MongoNetworkError,a=o().Long,c=n(7).collectionNamespace,u=n(4).maxWireVersion,l=n(7).applyCommonQueryOptions,p=n(42);e.exports=function(e,t,n,o,h,f){h=h||{};const d=u(e);function m(e,t){if(e)return f(e);const r=t.message;if(r.cursorNotFound)return f(new i("cursor killed or timed out"),null);if(d<4){const e="number"==typeof r.cursorId?a.fromNumber(r.cursorId):r.cursorId;return n.documents=r.documents,n.cursorId=e,void f(null,null,r.connection)}if(0===r.documents[0].ok)return f(new s(r.documents[0]));const o="number"==typeof r.documents[0].cursor.id?a.fromNumber(r.documents[0].cursor.id):r.documents[0].cursor.id;n.documents=r.documents[0].cursor.nextBatch,n.cursorId=o,f(null,r.documents[0],r.connection)}if(d<4){const s=e.s.bson,i=new r(s,t,n.cursorId,{numberToReturn:o}),a=l({},n);return void e.s.pool.write(i,a,m)}const y={getMore:n.cursorId instanceof a?n.cursorId:a.fromNumber(n.cursorId),collection:c(t),batchSize:Math.abs(o)};n.cmd.tailable&&"number"==typeof n.cmd.maxAwaitTimeMS&&(y.maxTimeMS=n.cmd.maxAwaitTimeMS);const g=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},h);n.session&&(g.session=n.session),p(e,t,y,g,m)}},function(e,t,n){"use strict";const r=n(22).Query,o=n(2).MongoError,s=n(7).getReadPreference,i=n(7).collectionNamespace,a=n(7).isSharded,c=n(4).maxWireVersion,u=n(7).applyCommonQueryOptions,l=n(42);e.exports=function(e,t,n,p,h,f){if(h=h||{},null!=p.cursorId)return f();if(null==n)return f(new o(`command ${JSON.stringify(n)} does not return a cursor`));if(c(e)<4){const i=function(e,t,n,i,c){c=c||{};const u=e.s.bson,l=s(n,c);i.batchSize=n.batchSize||i.batchSize;let p=0;p=i.limit<0||0!==i.limit&&i.limit0&&0===i.batchSize?i.limit:i.batchSize;const h=i.skip||0,f={};a(e)&&l&&(f.$readPreference=l.toJSON());n.sort&&(f.$orderby=n.sort);n.hint&&(f.$hint=n.hint);n.snapshot&&(f.$snapshot=n.snapshot);void 0!==n.returnKey&&(f.$returnKey=n.returnKey);n.maxScan&&(f.$maxScan=n.maxScan);n.min&&(f.$min=n.min);n.max&&(f.$max=n.max);void 0!==n.showDiskLoc&&(f.$showDiskLoc=n.showDiskLoc);n.comment&&(f.$comment=n.comment);n.maxTimeMS&&(f.$maxTimeMS=n.maxTimeMS);n.explain&&(p=-Math.abs(n.limit||0),f.$explain=!0);if(f.$query=n.query,n.readConcern&&"local"!==n.readConcern.level)throw new o("server find command does not support a readConcern level of "+n.readConcern.level);n.readConcern&&delete(n=Object.assign({},n)).readConcern;const d="boolean"==typeof c.serializeFunctions&&c.serializeFunctions,m="boolean"==typeof c.ignoreUndefined&&c.ignoreUndefined,y=new r(u,t,f,{numberToSkip:h,numberToReturn:p,pre32Limit:void 0!==n.limit?n.limit:void 0,checkKeys:!1,returnFieldSelector:n.fields,serializeFunctions:d,ignoreUndefined:m});"boolean"==typeof n.tailable&&(y.tailable=n.tailable);"boolean"==typeof n.oplogReplay&&(y.oplogReplay=n.oplogReplay);"boolean"==typeof n.noCursorTimeout&&(y.noCursorTimeout=n.noCursorTimeout);"boolean"==typeof n.awaitData&&(y.awaitData=n.awaitData);"boolean"==typeof n.partial&&(y.partial=n.partial);return y.slaveOk=l.slaveOk(),y}(e,t,n,p,h),c=u({},p);return"string"==typeof i.documentsReturnedIn&&(c.documentsReturnedIn=i.documentsReturnedIn),void e.s.pool.write(i,c,f)}const d=s(n,h),m=function(e,t,n,r){r.batchSize=n.batchSize||r.batchSize;let o={find:i(t)};n.query&&(n.query.$query?o.filter=n.query.$query:o.filter=n.query);let s=n.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];"asc"===t?t=1:"desc"===t&&(t=-1),e[s[0]]=t}else for(let t=0;te.name===t);if(n>=0){return e.s.connectingServers[n].destroy({force:!0}),e.s.connectingServers.splice(n,1),s()}var r=new p(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:!1,monitoring:!1,parent:e}));r.once("connect",i(e,"connect")),r.once("close",i(e,"close")),r.once("timeout",i(e,"timeout")),r.once("error",i(e,"error")),r.once("parseError",i(e,"parseError")),r.on("serverOpening",t=>e.emit("serverOpening",t)),r.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),r.on("serverClosed",t=>e.emit("serverClosed",t)),g(r,e,["commandStarted","commandSucceeded","commandFailed"]),e.s.connectingServers.push(r),r.connect(e.s.connectOptions)}),n)}for(var c=0;c0&&e.emit(t,n)}A.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},E(this,"connecting");var n=this.s.seedlist.map((function(n){return new p(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}))}));if(this.s.options.socketTimeout>0&&this.s.options.socketTimeout<=this.s.options.haInterval)return t.emit("error",new l(o("haInterval [%s] MS must be set to less than socketTimeout [%s] MS",this.s.options.haInterval,this.s.options.socketTimeout)));P(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.s.connectingServers=e.s.connectingServers.concat(t);var n=0;function r(t,n){setTimeout((function(){e.s.replicaSetState.update(t)&&t.lastIsMaster()&&t.lastIsMaster().ismaster&&(e.ismaster=t.lastIsMaster()),t.once("close",B(e,"close")),t.once("timeout",B(e,"timeout")),t.once("parseError",B(e,"parseError")),t.once("error",B(e,"error")),t.once("connect",B(e,"connect")),t.on("serverOpening",t=>e.emit("serverOpening",t)),t.on("serverDescriptionChanged",t=>e.emit("serverDescriptionChanged",t)),t.on("serverClosed",t=>e.emit("serverClosed",t)),g(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}for(;t.length>0;)r(t.shift(),n++)}(t,n)},A.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},A.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};let n=this.s.connectingServers.length+1;const r=()=>{n--,n>0||(P(this,"topologyClosed",{topologyId:this.id}),E(this,T),"function"==typeof t&&t(null,null))};this.haTimeoutId&&clearTimeout(this.haTimeoutId);for(var o=0;o{if(!o)return n(null,s);if(!w(o,r))return o=S(o),n(o);if(c){return L(Object.assign({},e,{retrying:!0}),t,n)}return r.s.replicaSetState.primary&&(r.s.replicaSetState.primary.destroy(),r.s.replicaSetState.remove(r.s.replicaSetState.primary,{force:!0})),n(o)};n.operationId&&(u.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),r.s.replicaSetState.primary[s](i,a,t,u)}A.prototype.selectServer=function(e,t,n){let r,o;"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e),t=t||{},r=e instanceof i?e:t.readPreference||i.primary;const s=_(),a=()=>{if(O(s)>=1e4)return void(null!=o?n(o,null):n(new l("Server selection timed out")));const e=this.s.replicaSetState.pickServer(r);if(null!=e){if(!(e instanceof p))return o=e,void setTimeout(a,1e3);this.s.debug&&this.emit("pickedServer",t.readPreference,e),n(null,e)}else setTimeout(a,1e3)};a()},A.prototype.getServers=function(){return this.s.replicaSetState.allServers()},A.prototype.insert=function(e,t,n,r){L({self:this,op:"insert",ns:e,ops:t},n,r)},A.prototype.update=function(e,t,n,r){L({self:this,op:"update",ns:e,ops:t},n,r)},A.prototype.remove=function(e,t,n,r){L({self:this,op:"remove",ns:e,ops:t},n,r)};const j=["findAndModify","insert","update","delete"];A.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===T)return r(new l(o("topology was destroyed")));var s=this,a=n.readPreference?n.readPreference:i.primary;if("primary"===a.preference&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("secondary"===a.preference&&!this.s.replicaSetState.hasSecondary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if("primary"!==a.preference&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);var c=this.s.replicaSetState.pickServer(a);if(!(c instanceof p))return r(c);if(s.s.debug&&s.emit("pickedServer",i.primary,c),null==c)return r(new l(o("no server found that matches the provided readPreference %s",a)));const u=!n.retrying&&!!n.retryWrites&&n.session&&y(s)&&!n.session.inTransaction()&&(h=t,j.some(e=>h[e]));var h;u&&(n.session.incrementTransactionNumber(),n.willRetryWrite=u),c.command(e,t,n,(o,i)=>{if(!o)return r(null,i);if(!w(o,s))return r(o);if(u){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return this.s.replicaSetState.primary&&(this.s.replicaSetState.primary.destroy(),this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:!0})),r(o)})},A.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},e.exports=A},function(e,t,n){"use strict";var r=n(5).inherits,o=n(5).format,s=n(9).diff,i=n(10).EventEmitter,a=n(19),c=n(13),u=n(2).MongoError,l=n(16).Buffer,p="ReplicaSetNoPrimary",h="ReplicaSetWithPrimary",f="Unknown",d="PossiblePrimary",m="RSPrimary",y="RSSecondary",g="RSArbiter",b="RSOther",S="RSGhost",v="Unknown",w=function(e){e=e||{},i.call(this),this.topologyType=p,this.setName=e.setName,this.set={},this.id=e.id,this.setName=e.setName,this.logger=e.logger||a("ReplSet",e),this.index=0,this.acceptableLatency=e.acceptableLatency||15,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.primary=null,this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.maxElectionId=null,this.maxSetVersion=0,this.replicasetDescription={topologyType:"Unknown",servers:[]},this.logicalSessionTimeoutMinutes=void 0};r(w,i),w.prototype.hasPrimaryAndSecondary=function(){return null!=this.primary&&this.secondaries.length>0},w.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()},w.prototype.hasPrimary=function(){return null!=this.primary},w.prototype.hasSecondary=function(){return this.secondaries.length>0},w.prototype.get=function(e){for(var t=this.allServers(),n=0;n{r--,r>0||(this.secondaries=[],this.arbiters=[],this.passives=[],this.ghosts=[],this.unknownServers=[],this.set={},this.primary=null,I(this),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>t.destroy(e,o)):o()},w.prototype.remove=function(e,t){t=t||{};var n=e.name.toLowerCase(),r=this.primary?[this.primary]:[];r=(r=(r=r.concat(this.secondaries)).concat(this.arbiters)).concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;w.prototype.update=function(e){var t=e.lastIsMaster(),n=e.name.toLowerCase();if(t){var r=Array.isArray(t.hosts)?t.hosts:[];r=(r=(r=r.concat(Array.isArray(t.arbiters)?t.arbiters:[])).concat(Array.isArray(t.passives)?t.passives:[])).map((function(e){return e.toLowerCase()}));for(var s=0;sc)return!1}else if(!l&&i&&c&&c=5&&e.ismaster.secondary&&this.hasPrimary()?e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t:e.ismaster.maxWireVersion>=5&&e.ismaster.secondary&&(e.staleness=n-e.lastWriteDate+t)},w.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&null==e.maxStalenessSeconds){var o=E(this,e);if(o)return o}else if(r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)))return o;return e.equals(c.secondaryPreferred)?this.primary:null}if(e.equals(c.primaryPreferred)){if(o=null,this.primary)return this.primary;if(r.length>0&&null==e.maxStalenessSeconds?o=E(this,e):r.length>0&&null!=e.maxStalenessSeconds&&(o=T(this,e)),o)return o}return this.primary};var O=function(e,t){if(null==e.tags)return t;for(var n=[],r=Array.isArray(e.tags)?e.tags:[e.tags],o=0;o0?n[0].lastIsMasterMS:0;if(0===(n=n.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}))).length)return null;e.index=e.index%n.length;var s=n[e.index];return e.index=e.index+1,s}function C(e,t,n){for(var r=0;r0){var t="Unknown",n=e.setName;e.hasPrimaryAndSecondary()?t="ReplicaSetWithPrimary":!e.hasPrimary()&&e.hasSecondary()&&(t="ReplicaSetNoPrimary");var r={topologyType:t,setName:n,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary",r.servers.push(o)}r.servers=r.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t}))),r.servers=r.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();return t.type="RSArbiter",t}))),r.servers=r.servers.concat(e.passives.map((function(e){var t=e.getDescription();return t.type="RSSecondary",t})));var i=s(e.replicasetDescription,r),a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:r,diff:i};e.emit("topologyDescriptionChanged",a),e.replicasetDescription=r}}e.exports=w},function(e,t,n){"use strict";const r=n(5).inherits,o=n(5).format,s=n(10).EventEmitter,i=n(20).CoreCursor,a=n(19),c=n(11).retrieveBSON,u=n(2).MongoError,l=n(75),p=n(9).diff,h=n(9).cloneOptions,f=n(9).SessionMixins,d=n(9).isRetryableWritesSupported,m=n(4).relayEvents,y=c(),g=n(9).getMMAPError,b=n(4).makeClientMetadata,S=n(9).legacyIsRetryableWriteError;var v="destroying",w="destroyed";function _(e,t){var n={disconnected:["connecting",v,w,"disconnected"],connecting:["connecting",v,w,"connected","disconnected"],connected:["connected","disconnected",v,w,"unreferenced"],unreferenced:["unreferenced",v,w],destroyed:[w]}[e.state];n&&-1!==n.indexOf(t)?e.state=t:e.s.logger.error(o("Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}var O=1,T=["connect","close","error","timeout","parseError"],E=function(e,t){t=t||{},this.id=O++,Array.isArray(e)&&(e=e.reduce((e,t)=>(e.find(e=>e.host===t.host&&e.port===t.port)||e.push(t),e),[])),this.s={options:Object.assign({metadata:b(t)},t),bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:"boolean"==typeof t.debug&&t.debug,localThresholdMS:t.localThresholdMS||15},this.s.logger.isWarn()&&0!==this.s.options.socketTimeout&&this.s.options.socketTimeout0&&e.emit(t,n)}r(E,s),Object.assign(E.prototype,f),Object.defineProperty(E.prototype,"type",{enumerable:!0,get:function(){return"mongos"}}),Object.defineProperty(E.prototype,"parserType",{enumerable:!0,get:function(){return y.native?"c++":"js"}}),Object.defineProperty(E.prototype,"logicalSessionTimeoutMinutes",{enumerable:!0,get:function(){return this.ismaster&&this.ismaster.logicalSessionTimeoutMinutes||null}});const x=["serverDescriptionChanged","error","close","timeout","parseError"];function A(e,t,n){t=t||{},x.forEach(t=>e.removeAllListeners(t)),e.destroy(t,n)}function N(e){return function(){e.state!==w&&e.state!==v&&(M(e.connectedProxies,e.disconnectedProxies,this),L(e),e.emit("left","mongos",this),e.emit("serverClosed",{topologyId:e.id,address:this.name}))}}function I(e,t){return function(){if(e.state===w)return L(e),M(e.connectingProxies,e.disconnectedProxies,this),this.destroy();if("connect"===t)if(e.ismaster=this.lastIsMaster(),"isdbgrid"===e.ismaster.msg){for(let t=0;t0&&"connecting"===e.state)_(e,"connected"),e.emit("connect",e),e.emit("fullsetup",e),e.emit("all",e);else if(0===e.disconnectedProxies.length)return e.s.logger.isWarn()&&e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset")),e.emit("error",new u("no mongos proxies found in seed list"));!function e(t,n){if(n=n||{},t.state===w||t.state===v||"unreferenced"===t.state)return;t.haTimeoutId=setTimeout((function(){if(t.state!==w&&t.state!==v&&"unreferenced"!==t.state){t.isConnected()&&t.s.disconnectHandler&&t.s.disconnectHandler.execute();var r=t.connectedProxies.slice(0),o=r.length;if(0===r.length)return t.listeners("close").length>0&&"connecting"===t.state?t.emit("error",new u("no mongos proxy available")):t.emit("close",t),D(t,t.disconnectedProxies,(function(){t.state!==w&&t.state!==v&&"unreferenced"!==t.state&&("connecting"===t.state&&n.firstConnect?(t.emit("connect",t),t.emit("fullsetup",t),t.emit("all",t)):t.isConnected()?t.emit("reconnect",t):!t.isConnected()&&t.listeners("close").length>0&&t.emit("close",t),e(t))}));for(var s=0;s{if(!o)return n(null,s);if(!S(o,r)||!c)return o=g(o),n(o);if(a=k(r,t.session),!a)return n(o);return B(Object.assign({},e,{retrying:!0}),t,n)};n.operationId&&(l.operationId=n.operationId),c&&(t.session.incrementTransactionNumber(),t.willRetryWrite=c),a[o](s,i,t,l)}E.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{},_(this,"connecting");var n=this.s.seedlist.map((function(n){const r=new l(Object.assign({},t.s.options,n,e,{reconnect:!1,monitoring:!1,parent:t}));return m(r,t,["serverDescriptionChanged"]),r}));C(this,"topologyOpening",{topologyId:this.id}),function(e,t){e.connectingProxies=e.connectingProxies.concat(t);var n=0;t.forEach(t=>function(t,n){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name}),L(e),t.once("close",I(e,"close")),t.once("timeout",I(e,"timeout")),t.once("parseError",I(e,"parseError")),t.once("error",I(e,"error")),t.once("connect",I(e,"connect")),m(t,e,["commandStarted","commandSucceeded","commandFailed"]),t.connect(e.s.connectOptions)}),n)}(t,n++))}(t,n)},E.prototype.auth=function(e,t){"function"==typeof t&&t(null,null)},E.prototype.lastIsMaster=function(){return this.ismaster},E.prototype.unref=function(){_(this,"unreferenced"),this.connectedProxies.concat(this.connectingProxies).forEach((function(e){e.unref()})),clearTimeout(this.haTimeoutId)},E.prototype.destroy=function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{},_(this,v),this.haTimeoutId&&clearTimeout(this.haTimeoutId);const n=this.connectedProxies.concat(this.connectingProxies);let r=n.length;const o=()=>{r--,r>0||(L(this),C(this,"topologyClosed",{topologyId:this.id}),_(this,w),"function"==typeof t&&t(null,null))};0!==r?n.forEach(t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name}),A(t,e,o),M(this.connectedProxies,this.disconnectedProxies,t)}):o()},E.prototype.isConnected=function(){return this.connectedProxies.length>0},E.prototype.isDestroyed=function(){return this.state===w},E.prototype.insert=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"insert",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("insert",e,t,n,r)},E.prototype.update=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"update",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("update",e,t,n,r)},E.prototype.remove=function(e,t,n,r){return"function"==typeof n&&(r=n,n=(n={})||{}),this.state===w?r(new u(o("topology was destroyed"))):this.isConnected()||null==this.s.disconnectHandler?this.isConnected()?void B({self:this,op:"remove",ns:e,ops:t},n,r):r(new u("no mongos proxy available")):this.s.disconnectHandler.add("remove",e,t,n,r)};const P=["findAndModify","insert","update","delete"];function L(e){if(e.listeners("topologyDescriptionChanged").length>0){var t="Unknown";e.connectedProxies.length>0&&(t="Sharded");var n={topologyType:t,servers:[]},r=e.disconnectedProxies.concat(e.connectingProxies);n.servers=n.servers.concat(r.map((function(e){var t=e.getDescription();return t.type="Unknown",t}))),n.servers=n.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();return t.type="Mongos",t})));var o=p(e.topologyDescription,n),s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:n,diff:o};o.servers.length>0&&e.emit("topologyDescriptionChanged",s),e.topologyDescription=n}}E.prototype.command=function(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.state===w)return r(new u(o("topology was destroyed")));var s=this,i=k(s,n.session);if((null==i||!i.isConnected())&&null!=this.s.disconnectHandler)return this.s.disconnectHandler.add("command",e,t,n,r);if(null==i)return r(new u("no mongos proxy available"));var a=h(n);a.topology=s;const c=!n.retrying&&n.retryWrites&&n.session&&d(s)&&!n.session.inTransaction()&&(l=t,P.some(e=>l[e]));var l;c&&(a.session.incrementTransactionNumber(),a.willRetryWrite=c),i.command(e,t,a,(n,o)=>{if(!n)return r(null,o);if(!S(n,s))return r(n);if(c){const n=Object.assign({},a,{retrying:!0});return this.command(e,t,n,r)}return r(n)})},E.prototype.cursor=function(e,t,n){const r=(n=n||{}).topology||this;return new(n.cursorFactory||this.s.Cursor)(r,e,t,n)},E.prototype.selectServer=function(e,t,n){"function"==typeof e&&void 0===n&&(n=e,e=void 0,t={}),"function"==typeof t&&(n=t,t=e,e=void 0);const r=k(this,(t=t||{}).session);null!=r?(this.s.debug&&this.emit("pickedServer",null,r),n(null,r)):n(new u("server selection failed"))},E.prototype.connections=function(){for(var e=[],t=0;t({host:e.split(":")[0],port:e.split(":")[1]||27017}))}(e)),t=Object.assign({},k.TOPOLOGY_DEFAULTS,t),t=Object.freeze(Object.assign(t,{metadata:A(t),compression:{compressors:g(t)}})),H.forEach(e=>{t[e]&&C(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")});const n=function(e,t){if(t.directConnection)return c.Single;if(null==(t.replicaSet||t.setName||t.rs_name))return c.Unknown;return c.ReplicaSetNoPrimary}(0,t),o=L++,i=e.reduce((e,t)=>{t.domain_socket&&(t.host=t.domain_socket);const n=t.port?`${t.host}:${t.port}`:t.host+":27017";return e.set(n,new s(n)),e},new Map);this[Y]=new r,this.s={id:o,options:t,seedlist:e,state:F,description:new a(n,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new y([y.Binary,y.Code,y.DBRef,y.Decimal128,y.Double,y.Int32,y.Long,y.Map,y.MaxKey,y.MinKey,y.ObjectId,y.BSONRegExp,y.Symbol,y.Timestamp]),servers:new Map,sessionPool:new x(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set},t.srvHost&&(this.s.srvPoller=t.srvPoller||new _({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel}),this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type,n=e.newDescription.type;var r;t!==c.Sharded&&n===c.Sharded&&(this.s.handleSrvPolling=(r=this,function(e){const t=r.s.description;r.s.description=r.s.description.updateFromSrvPollingEvent(e),r.s.description!==t&&(Z(r),r.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(r.s.id,t,r.s.description)))}),this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling),this.s.srvPoller.start())},this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)),this.setMaxListeners(1/0)}get description(){return this.s.description}get parserType(){return y.native?"c++":"js"}connect(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},this.s.state===q)return void("function"==typeof t&&t());var n,r;$(this,W),this.emit("topologyOpening",new u.TopologyOpeningEvent(this.s.id)),this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,new a(c.Unknown),this.s.description)),n=this,r=Array.from(this.s.description.servers.values()),n.s.servers=r.reduce((e,t)=>{const r=J(n,t);return e.set(t.address,r),e},new Map),h.translate(e);const o=e.readPreference||h.primary,s=e=>{if(e)return this.close(),void("function"==typeof t?t(e):this.emit("error",e));$(this,q),this.emit("open",e,this),this.emit("connect",this),"function"==typeof t&&t(e,this)};this.s.credentials?this.command("admin.$cmd",{ping:1},{readPreference:o},s):this.selectServer(B(o),e,s)}close(e,t){"function"==typeof e&&(t=e,e={}),"boolean"==typeof e&&(e={force:e}),e=e||{},this.s.state!==F&&this.s.state!==z?($(this,z),te(this[Y],new S("Topology closed")),M(this.s.connectionTimers),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.handleSrvPolling&&(this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling),delete this.s.handleSrvPolling)),this.s.detectTopologyDescriptionChange&&(this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange),delete this.s.detectTopologyDescriptionChange),this.s.sessions.forEach(e=>e.endSession()),this.s.sessionPool.endAllPooledSessions(()=>{E(Array.from(this.s.servers.values()),(t,n)=>X(t,this,e,n),e=>{this.s.servers.clear(),this.emit("topologyClosed",new u.TopologyClosedEvent(this.s.id)),$(this,F),this.emit("close"),"function"==typeof t&&t(e)})})):"function"==typeof t&&t()}selectServer(e,t,n){if("function"==typeof t)if(n=t,"function"!=typeof e){let n;t=e,e instanceof h?n=e:"string"==typeof e?n=new h(e):(h.translate(t),n=t.readPreference||h.primary),e=B(n)}else t={};t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const r=this.description.type===c.Sharded,o=t.session,s=o&&o.transaction;if(r&&s&&s.server)return void n(void 0,s.server);let i=e;if("object"==typeof e){const t=e.readPreference?e.readPreference:h.primary;i=B(t)}const a={serverSelector:i,transaction:s,callback:n},u=t.serverSelectionTimeoutMS;u&&(a.timer=setTimeout(()=>{a[V]=!0,a.timer=void 0;const e=new v(`Server selection timed out after ${u} ms`,this.description);a.callback(e)},u)),this[Y].push(a),ne(this)}shouldCheckForSessionSupport(){return this.description.type===c.Single?!this.description.hasKnownServers:!this.description.hasDataBearingServers}hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}startSession(e,t){const n=new b(this,this.s.sessionPool,e,t);return n.once("ended",()=>{this.s.sessions.delete(n)}),this.s.sessions.add(n),n}endSessions(e,t){Array.isArray(e)||(e=[e]),this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:!0},()=>{"function"==typeof t&&t()})}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const n=e.servers.get(t.address).topologyVersion;return I(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,n=this.s.description.servers.get(e.address),r=e.$clusterTime;r&&w(this,r);const o=n&&n.equals(e);this.s.description=this.s.description.update(e),this.s.description.compatibilityError?this.emit("error",new S(this.s.description.compatibilityError)):(o||this.emit("serverDescriptionChanged",new u.ServerDescriptionChangedEvent(this.s.id,e.address,n,this.s.description.servers.get(e.address))),Z(this,e),this[Y].length>0&&ne(this),o||this.emit("topologyDescriptionChanged",new u.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}auth(e,t){"function"==typeof e&&(t=e,e=null),"function"==typeof t&&t(null,!0)}logout(e){"function"==typeof e&&e(null,!0)}insert(e,t,n,r){Q({topology:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){Q({topology:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){Q({topology:this,op:"remove",ns:e,ops:t},n,r)}command(e,t,n,r){"function"==typeof n&&(r=n,n=(n={})||{}),h.translate(n);const o=n.readPreference||h.primary;this.selectServer(B(o),n,(o,s)=>{if(o)return void r(o);const i=!n.retrying&&!!n.retryWrites&&n.session&&f(this)&&!n.session.inTransaction()&&(a=t,K.some(e=>a[e]));var a;i&&(n.session.incrementTransactionNumber(),n.willRetryWrite=i),s.command(e,t,n,(o,s)=>{if(!o)return r(null,s);if(!ee(o))return r(o);if(i){const o=Object.assign({},n,{retrying:!0});return this.command(e,t,o,r)}return r(o)})})}cursor(e,t,n){const r=(n=n||{}).topology||this,o=n.cursorFactory||this.s.Cursor;return h.translate(n),new o(r,e,t,n)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===q}isDestroyed(){return this.s.state===F}unref(){console.log("not implemented: `unref`")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(0===e.length)return{};return e.filter(e=>e.type!==i.Unknown)[0]||{maxWireVersion:this.description.commonWireVersion}}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(G.prototype,"clusterTime",{enumerable:!0,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}}),G.prototype.destroy=m(G.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function X(e,t,n,r){n=n||{},U.forEach(t=>e.removeAllListeners(t)),e.destroy(n,()=>{t.emit("serverClosed",new u.ServerClosedEvent(t.s.id,e.description.address)),j.forEach(t=>e.removeAllListeners(t)),"function"==typeof r&&r()})}function J(e,t,n){e.emit("serverOpening",new u.ServerOpeningEvent(e.s.id,t.address));const r=new l(t,e.s.options,e);if(p(r,e,j),r.on("descriptionReceived",e.serverUpdateHandler.bind(e)),n){const t=setTimeout(()=>{R(t,e.s.connectionTimers),r.connect()},n);return e.s.connectionTimers.add(t),r}return r.connect(),r}function Z(e,t){if(t&&e.s.servers.has(t.address)){e.s.servers.get(t.address).s.description=t}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const n=J(e,t);e.s.servers.set(t.address,n)}for(const t of e.s.servers){const n=t[0];if(e.description.hasServer(n))continue;const r=e.s.servers.get(n);e.s.servers.delete(n),X(r,e)}}function Q(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.topology,o=e.op,s=e.ns,i=e.ops,a=!e.retrying&&!!t.retryWrites&&t.session&&f(r)&&!t.session.inTransaction();r.selectServer(P(),t,(r,c)=>{if(r)return void n(r,null);const u=(r,o)=>{if(!r)return n(null,o);if(!ee(r))return r=O(r),n(r);if(a){return Q(Object.assign({},e,{retrying:!0}),t,n)}return n(r)};n.operationId&&(u.operationId=n.operationId),a&&(t.session.incrementTransactionNumber(),t.willRetryWrite=a),c[o](s,i,t,u)})}function ee(e){return e instanceof S&&e.hasErrorLabel("RetryableWriteError")}function te(e,t){for(;e.length;){const n=e.shift();clearTimeout(n.timer),n[V]||n.callback(t)}}function ne(e){if(e.s.state===F)return void te(e[Y],new S("Topology is closed, please connect"));const t=Array.from(e.description.servers.values()),n=e[Y].length;for(let o=0;o0&&e.s.servers.forEach(e=>process.nextTick(()=>e.requestCheck()))}e.exports={Topology:G}},function(e,t,n){"use strict";const r=n(10),o=n(165).ConnectionPool,s=n(61).CMAP_EVENT_NAMES,i=n(2).MongoError,a=n(4).relayEvents,c=n(11).retrieveBSON(),u=n(19),l=n(34).ServerDescription,p=n(34).compareTopologyVersion,h=n(13),f=n(176).Monitor,d=n(2).MongoNetworkError,m=n(2).MongoNetworkTimeoutError,y=n(4).collationNotSupported,g=n(11).debugOptions,b=n(2).isSDAMUnrecoverableError,S=n(2).isRetryableWriteError,v=n(2).isNodeShuttingDownError,w=n(2).isNetworkErrorBeforeHandshake,_=n(4).maxWireVersion,O=n(4).makeStateMachine,T=n(15),E=T.ServerType,C=n(41).isTransactionCommand,x=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","servername"],A=T.STATE_CLOSING,N=T.STATE_CLOSED,I=T.STATE_CONNECTING,k=T.STATE_CONNECTED,M=O({[N]:[N,I],[I]:[I,A,k,N],[k]:[k,A,N],[A]:[A,N]}),R=Symbol("monitor");class D extends r{constructor(e,t,n){super(),this.s={description:e,options:t,logger:u("Server",t),bson:t.bson||new c([c.Binary,c.Code,c.DBRef,c.Decimal128,c.Double,c.Int32,c.Long,c.Map,c.MaxKey,c.MinKey,c.ObjectId,c.BSONRegExp,c.Symbol,c.Timestamp]),state:N,credentials:t.credentials,topology:n};const r=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(r),a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s)),this.s.pool.on("clusterTimeReceived",e=>{this.clusterTime=e}),this[R]=new f(this,this.s.options),a(this[R],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]),this[R].on("resetConnectionPool",()=>{this.s.pool.clear()}),this[R].on("resetServer",e=>L(this,e)),this[R].on("serverHeartbeatSucceeded",e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:B(this.description.roundTripTime,e.duration)})),this.s.state===I&&(M(this,k),this.emit("connect",this))})}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){return this.s.options&&this.s.options.autoEncrypter?this.s.options.autoEncrypter:null}connect(){this.s.state===N&&(M(this,I),this[R].connect())}destroy(e,t){"function"==typeof e&&(t=e,e={}),e=Object.assign({},{force:!1},e),this.s.state!==N?(M(this,A),this[R].close(),this.s.pool.close(e,e=>{M(this,N),this.emit("closed"),"function"==typeof t&&t(e)})):"function"==typeof t&&t()}requestCheck(){this[R].requestCheck()}command(e,t,n,r){if("function"==typeof n&&(r=n,n=(n={})||{}),this.s.state===A||this.s.state===N)return void r(new i("server is closed"));const o=function(e,t){if(t.readPreference&&!(t.readPreference instanceof h))return new i("readPreference must be an instance of ReadPreference")}(0,n);if(o)return r(o);n=Object.assign({},n,{wireProtocolCommand:!1}),this.s.logger.isDebug()&&this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:t,options:g(x,n)})}] against ${this.name}`),y(this,t)?r(new i(`server ${this.name} does not support collation`)):this.s.pool.withConnection((r,o,s)=>{if(r)return L(this,r),s(r);o.command(e,t,n,U(this,o,t,n,s))},r)}query(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.query(e,t,n,r,U(this,s,t,r,i))},o):o(new i("server is closed"))}getMore(e,t,n,r,o){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((o,s,i)=>{if(o)return L(this,o),i(o);s.getMore(e,t,n,r,U(this,s,null,r,i))},o):o(new i("server is closed"))}killCursors(e,t,n){this.s.state!==A&&this.s.state!==N?this.s.pool.withConnection((n,r,o)=>{if(n)return L(this,n),o(n);r.killCursors(e,t,U(this,r,null,void 0,o))},n):"function"==typeof n&&n(new i("server is closed"))}insert(e,t,n,r){P({server:this,op:"insert",ns:e,ops:t},n,r)}update(e,t,n,r){P({server:this,op:"update",ns:e,ops:t},n,r)}remove(e,t,n,r){P({server:this,op:"remove",ns:e,ops:t},n,r)}}function B(e,t){if(-1===e)return t;return.2*t+.8*e}function P(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};const r=e.server,o=e.op,s=e.ns,a=Array.isArray(e.ops)?e.ops:[e.ops];if(r.s.state===A||r.s.state===N)return void n(new i("server is closed"));if(y(r,t))return void n(new i(`server ${r.name} does not support collation`));!(t.writeConcern&&0===t.writeConcern.w||_(r)<5)||"update"!==o&&"remove"!==o||!a.find(e=>e.hint)?r.s.pool.withConnection((e,n,i)=>{if(e)return L(r,e),i(e);n[o](s,a,t,U(r,n,a,t,i))},n):n(new i("servers < 3.4 do not support hint on "+o))}function L(e,t){t instanceof d&&!(t instanceof m)&&e[R].reset(),e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function j(e,t){return e&&e.inTransaction()&&!C(t)}function U(e,t,n,r,o){const s=r&&r.session;return function(r,i){r&&!function(e,t){return t.generation!==e.generation}(e.s.pool,t)&&(r instanceof d?(s&&!s.hasEnded&&(s.serverSession.isDirty=!0),function(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==E.Standalone}(e)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),r instanceof m&&!w(r)||(L(e,r),e.s.pool.clear())):(_(e)<9&&S(r)&&!j(s,n)&&r.addErrorLabel("RetryableWriteError"),b(r)&&function(e,t){const n=t.topologyVersion,r=e.description.topologyVersion;return p(r,n)<0}(e,r)&&((_(e)<=7||v(r))&&e.s.pool.clear(),L(e,r),process.nextTick(()=>e.requestCheck())))),o(r,i)}}Object.defineProperty(D.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}}),e.exports={Server:D}},function(e,t,n){"use strict";const r=n(77),o=n(10).EventEmitter,s=n(19),i=n(0).makeCounter,a=n(2).MongoError,c=n(105).Connection,u=n(4).eachAsync,l=n(76),p=n(4).relayEvents,h=n(175),f=h.PoolClosedError,d=h.WaitQueueTimeoutError,m=n(61),y=m.ConnectionPoolCreatedEvent,g=m.ConnectionPoolClosedEvent,b=m.ConnectionCreatedEvent,S=m.ConnectionReadyEvent,v=m.ConnectionClosedEvent,w=m.ConnectionCheckOutStartedEvent,_=m.ConnectionCheckOutFailedEvent,O=m.ConnectionCheckedOutEvent,T=m.ConnectionCheckedInEvent,E=m.ConnectionPoolClearedEvent,C=Symbol("logger"),x=Symbol("connections"),A=Symbol("permits"),N=Symbol("minPoolSizeTimer"),I=Symbol("generation"),k=Symbol("connectionCounter"),M=Symbol("cancellationToken"),R=Symbol("waitQueue"),D=Symbol("cancelled"),B=new Set(["ssl","bson","connectionType","monitorCommands","socketTimeout","credentials","compression","host","port","localAddress","localPort","family","hints","lookup","path","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext","allowHalfOpen","rejectUnauthorized","pskCallback","ALPNProtocols","servername","checkServerIdentity","session","minDHSize","secureContext","maxPoolSize","minPoolSize","maxIdleTimeMS","waitQueueTimeoutMS"]);function P(e,t){return t.generation!==e[I]}function L(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function j(e,t){const n=Object.assign({id:e[k].next().value,generation:e[I]},e.options);e[A]--,l(n,e[M],(n,r)=>{if(n)return e[A]++,e[C].debug(`connection attempt failed with error [${JSON.stringify(n)}]`),void("function"==typeof t&&t(n));e.closed?r.destroy({force:!0}):(p(r,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]),e.emit("connectionCreated",new b(e,r)),r.markAvailable(),e.emit("connectionReady",new S(e,r)),"function"!=typeof t?(e[x].push(r),z(e)):t(void 0,r))})}function U(e,t,n){e.emit("connectionClosed",new v(e,t,n)),e[A]++,process.nextTick(()=>t.destroy())}function z(e){if(e.closed)return;for(;e.waitQueueSize;){const t=e[R].peekFront();if(t[D]){e[R].shift();continue}if(!e.availableConnectionCount)break;const n=e[x].shift(),r=P(e,n),o=L(e,n);if(!r&&!o&&!n.closed)return e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(t.timer),e[R].shift(),void t.callback(void 0,n);const s=n.closed?"error":r?"stale":"idle";U(e,n,s)}const t=e.options.maxPoolSize;e.waitQueueSize&&(t<=0||e.totalConnectionCount{const r=e[R].shift();null!=r?r[D]||(t?e.emit("connectionCheckOutFailed",new _(e,t)):e.emit("connectionCheckedOut",new O(e,n)),clearTimeout(r.timer),r.callback(t,n)):null==t&&e[x].push(n)})}e.exports={ConnectionPool:class extends o{constructor(e){if(super(),e=e||{},this.closed=!1,this.options=function(e,t){const n=Array.from(B).reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{});return Object.freeze(Object.assign({},t,n))}(e,{connectionType:c,maxPoolSize:"number"==typeof e.maxPoolSize?e.maxPoolSize:100,minPoolSize:"number"==typeof e.minPoolSize?e.minPoolSize:0,maxIdleTimeMS:"number"==typeof e.maxIdleTimeMS?e.maxIdleTimeMS:0,waitQueueTimeoutMS:"number"==typeof e.waitQueueTimeoutMS?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata}),e.minSize>e.maxSize)throw new TypeError("Connection pool minimum size must not be greater than maxiumum pool size");this[C]=s("ConnectionPool",e),this[x]=new r,this[A]=this.options.maxPoolSize,this[N]=void 0,this[I]=0,this[k]=i(1),this[M]=new o,this[M].setMaxListeners(1/0),this[R]=new r,process.nextTick(()=>{this.emit("connectionPoolCreated",new y(this)),function e(t){if(t.closed||0===t.options.minPoolSize)return;const n=t.options.minPoolSize;for(let e=t.totalConnectionCount;ee(t),10)}(this)})}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[I]}get totalConnectionCount(){return this[x].length+(this.options.maxPoolSize-this[A])}get availableConnectionCount(){return this[x].length}get waitQueueSize(){return this[R].length}checkOut(e){if(this.emit("connectionCheckOutStarted",new w(this)),this.closed)return this.emit("connectionCheckOutFailed",new _(this,"poolClosed")),void e(new f(this));const t={callback:e},n=this,r=this.options.waitQueueTimeoutMS;r&&(t.timer=setTimeout(()=>{t[D]=!0,t.timer=void 0,n.emit("connectionCheckOutFailed",new _(n,"timeout")),t.callback(new d(n))},r)),this[R].push(t),z(this)}checkIn(e){const t=this.closed,n=P(this,e),r=!!(t||n||e.closed);if(r||(e.markAvailable(),this[x].push(e)),this.emit("connectionCheckedIn",new T(this,e)),r){U(this,e,e.closed?"error":t?"poolClosed":"stale")}z(this)}clear(){this[I]+=1,this.emit("connectionPoolCleared",new E(this))}close(e,t){if("function"==typeof e&&(t=e),e=Object.assign({force:!1},e),this.closed)return t();for(this[M].emit("cancel");this.waitQueueSize;){const e=this[R].pop();clearTimeout(e.timer),e[D]||e.callback(new a("connection pool closed"))}this[N]&&clearTimeout(this[N]),"function"==typeof this[k].return&&this[k].return(),this.closed=!0,u(this[x].toArray(),(t,n)=>{this.emit("connectionClosed",new v(this,t,"poolClosed")),t.destroy(e,n)},e=>{this[x].clear(),this.emit("connectionPoolClosed",new g(this)),t(e)})}withConnection(e,t){this.checkOut((n,r)=>{e(n,r,(e,n)=>{"function"==typeof t&&(e?t(e):t(void 0,n)),r&&this.checkIn(r)})})}}}},function(e,t,n){"use strict";const r=n(24).Duplex,o=n(167),s=n(2).MongoParseError,i=n(27).decompress,a=n(22).Response,c=n(35).BinMsg,u=n(2).MongoError,l=n(7).opcodes.OP_COMPRESSED,p=n(7).opcodes.OP_MSG,h=n(7).MESSAGE_HEADER_SIZE,f=n(7).COMPRESSION_DETAILS_SIZE,d=n(7).opcodes,m=n(27).compress,y=n(27).compressorIDs,g=n(27).uncompressibleCommands,b=n(35).Msg,S=Symbol("buffer");e.exports=class extends r{constructor(e){super(e=e||{}),this.bson=e.bson,this.maxBsonMessageSize=e.maxBsonMessageSize||67108864,this[S]=new o}_write(e,t,n){this[S].append(e),function e(t,n){const r=t[S];if(r.length<4)return void n();const o=r.readInt32LE(0);if(o<0)return void n(new s("Invalid message size: "+o));if(o>t.maxBsonMessageSize)return void n(new s(`Invalid message size: ${o}, max allowed: ${t.maxBsonMessageSize}`));if(o>r.length)return void n();const f=r.slice(0,o);r.consume(o);const d={length:f.readInt32LE(0),requestId:f.readInt32LE(4),responseTo:f.readInt32LE(8),opCode:f.readInt32LE(12)};let m=d.opCode===p?c:a;const y=t.responseOptions;if(d.opCode!==l){const o=f.slice(h);return t.emit("message",new m(t.bson,f,d,o,y)),void(r.length>=4?e(t,n):n())}d.fromCompressed=!0,d.opCode=f.readInt32LE(h),d.length=f.readInt32LE(h+4);const g=f[h+8],b=f.slice(h+9);m=d.opCode===p?c:a,i(g,b,(o,s)=>{o?n(o):s.length===d.length?(t.emit("message",new m(t.bson,f,d,s,y)),r.length>=4?e(t,n):n()):n(new u("Decompressing a compressed message from the server failed. The message is corrupt."))})}(this,n)}_read(){}writeCommand(e,t){if(!(t&&!!t.agreedCompressor)||!function(e){const t=e instanceof b?e.command:e.query,n=Object.keys(t)[0];return!g.has(n)}(e)){const t=e.toBin();return void this.push(Array.isArray(t)?Buffer.concat(t):t)}const n=Buffer.concat(e.toBin()),r=n.slice(h),o=n.readInt32LE(12);m({options:t},r,(n,s)=>{if(n)return void t.cb(n,null);const i=Buffer.alloc(h);i.writeInt32LE(h+f+s.length,0),i.writeInt32LE(e.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(d.OP_COMPRESSED,12);const a=Buffer.alloc(f);a.writeInt32LE(o,0),a.writeInt32LE(r.length,4),a.writeUInt8(y[t.agreedCompressor],8),this.push(Buffer.concat([i,a,s]))})}}},function(e,t,n){"use strict";var r=n(168).Duplex,o=n(5),s=n(16).Buffer;function i(e){if(!(this instanceof i))return new i(e);if(this._bufs=[],this.length=0,"function"==typeof e){this._callback=e;var t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)}))}else this.append(e);r.call(this)}o.inherits(i,r),i.prototype._offset=function(e){var t,n=0,r=0;if(0===e)return[0,0];for(;rthis.length||e<0)){var t=this._offset(e);return this._bufs[t[0]][t[1]]}},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||s.alloc(0);if(r<=0)return e||s.alloc(0);var o,i,a=!!e,c=this._offset(n),u=r-n,l=u,p=a&&t||0,h=c[1];if(0===n&&r==this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:s.concat(this._bufs,this.length);for(i=0;i(o=this._bufs[i].length-h))){this._bufs[i].copy(e,p,h,h+l),p+=o;break}this._bufs[i].copy(e,p,h),p+=o,l-=o,h&&(h=0)}return e.length>p?e.slice(0,p):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return new i;var n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0==r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!=n[1]&&(o[0]=o[0].slice(n[1])),new i(o)},i.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){for(var e=0,t=new i;ethis.length?this.length:t;for(var r=this._offset(t),o=r[0],a=r[1];o=e.length){var u=c.indexOf(e,a);if(-1!==u)return this._reverseOffset([o,u]);a=c.length-e.length+1}else{var l=this._reverseOffset([o,a]);if(this._match(l,e))return l;a++}}a=0}return-1},i.prototype._match=function(e,t){if(this.length-e0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return r.alloc(0);if(1===this.length)return this.head.data;for(var t,n,o,s=r.allocUnsafe(e>>>0),i=this.head,a=0;i;)t=i.data,n=s,o=a,t.copy(n,o),a+=i.data.length,i=i.next;return s},e}(),o&&o.inspect&&o.inspect.custom&&(e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t,n){e.exports=n(5).deprecate},function(e,t,n){"use strict";e.exports=s;var r=n(111),o=Object.create(n(44));function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}o.inherits=n(45),o.inherits(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},function(e,t,n){"use strict";const r=n(34).parseServerType,o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];e.exports={StreamDescription:class{constructor(e,t){this.address=e,this.type=r(null),this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.compressors=t&&t.compression&&Array.isArray(t.compression.compressors)?t.compression.compressors:[]}receiveResponse(e){this.type=r(e),o.forEach(t=>{void 0!==e[t]&&(this[t]=e[t])}),e.compression&&(this.compressor=this.compressors.filter(t=>-1!==e.compression.indexOf(t))[0])}}}},function(e,t,n){"use strict";const r=n(2).MongoError;e.exports={PoolClosedError:class extends r{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.name="MongoPoolClosedError",this.address=e.address}},WaitQueueTimeoutError:class extends r{constructor(e){super("Timed out while checking out a connection from connection pool"),this.name="MongoWaitQueueTimeoutError",this.address=e.address}}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(10),s=n(76),i=n(105).Connection,a=n(15),c=n(4).makeStateMachine,u=n(2).MongoNetworkError,l=n(11).retrieveBSON(),p=n(0).makeInterruptableAsyncInterval,h=n(0).calculateDurationInMs,f=n(0).now,d=n(104),m=d.ServerHeartbeatStartedEvent,y=d.ServerHeartbeatSucceededEvent,g=d.ServerHeartbeatFailedEvent,b=Symbol("server"),S=Symbol("monitorId"),v=Symbol("connection"),w=Symbol("cancellationToken"),_=Symbol("rttPinger"),O=Symbol("roundTripTime"),T=a.STATE_CLOSED,E=a.STATE_CLOSING,C=c({[E]:[E,"idle",T],[T]:[T,"monitoring"],idle:["idle","monitoring",E],monitoring:["monitoring","idle",E]}),x=new Set([E,T,"monitoring"]);function A(e){return e.s.state===T||e.s.state===E}function N(e){C(e,E),e[S]&&(e[S].stop(),e[S]=null),e[_]&&(e[_].close(),e[_]=void 0),e[w].emit("cancel"),e[S]&&(clearTimeout(e[S]),e[S]=void 0),e[v]&&e[v].destroy({force:!0})}function I(e){return t=>{function n(){A(e)||C(e,"idle"),t()}C(e,"monitoring"),process.nextTick(()=>e.emit("monitoring",e[b])),function(e,t){let n=f();function r(r){e[v]&&(e[v].destroy({force:!0}),e[v]=void 0),e.emit("serverHeartbeatFailed",new g(h(n),r,e.address)),e.emit("resetServer",r),e.emit("resetConnectionPool"),t(r)}if(e.emit("serverHeartbeatStarted",new m(e.address)),null!=e[v]&&!e[v].closed){const s=e.options.connectTimeoutMS,i=e.options.heartbeatFrequencyMS,a=e[b].description.topologyVersion,c=null!=a,u=c?{ismaster:!0,maxAwaitTimeMS:i,topologyVersion:(o=a,{processId:o.processId,counter:l.Long.fromNumber(o.counter)})}:{ismaster:!0},p=c?{socketTimeout:s+i,exhaustAllowed:!0}:{socketTimeout:s};return c&&null==e[_]&&(e[_]=new k(e[w],e.connectOptions)),void e[v].command("admin.$cmd",u,p,(o,s)=>{if(o)return void r(o);const i=s.result,a=c?e[_].roundTripTime:h(n);e.emit("serverHeartbeatSucceeded",new y(a,i,e.address)),c&&i.topologyVersion?(e.emit("serverHeartbeatStarted",new m(e.address)),n=f()):(e[_]&&(e[_].close(),e[_]=void 0),t(void 0,i))})}var o;s(e.connectOptions,e[w],(o,s)=>{if(s&&A(e))s.destroy({force:!0});else{if(o)return e[v]=void 0,o instanceof u||e.emit("resetConnectionPool"),void r(o);e[v]=s,e.emit("serverHeartbeatSucceeded",new y(h(n),s.ismaster,e.address)),t(void 0,s.ismaster)}})}(e,(t,o)=>{if(t&&e[b].description.type===r.Unknown)return e.emit("resetServer",t),n();o&&o.topologyVersion&&setTimeout(()=>{A(e)||e[S].wake()}),n()})}}class k{constructor(e,t){this[v]=null,this[w]=e,this[O]=0,this.closed=!1;const n=t.heartbeatFrequencyMS;this[S]=setTimeout(()=>function e(t,n){const r=f(),o=t[w],i=n.heartbeatFrequencyMS;if(t.closed)return;function a(o){t.closed?o.destroy({force:!0}):(null==t[v]&&(t[v]=o),t[O]=h(r),t[S]=setTimeout(()=>e(t,n),i))}if(null==t[v])return void s(n,o,(e,n)=>{if(e)return t[v]=void 0,void(t[O]=0);a(n)});t[v].command("admin.$cmd",{ismaster:1},e=>{if(e)return t[v]=void 0,void(t[O]=0);a()})}(this,t),n)}get roundTripTime(){return this[O]}close(){this.closed=!0,clearTimeout(this[S]),this[S]=void 0,this[v]&&this[v].destroy({force:!0})}}e.exports={Monitor:class extends o{constructor(e,t){super(t),this[b]=e,this[v]=void 0,this[w]=new o,this[w].setMaxListeners(1/0),this[S]=null,this.s={state:T},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:"number"==typeof t.connectionTimeout?t.connectionTimeout:"number"==typeof t.connectTimeoutMS?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:"number"==typeof t.heartbeatFrequencyMS?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:"number"==typeof t.minHeartbeatFrequencyMS?t.minHeartbeatFrequencyMS:500});const n=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0});delete n.credentials,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==T)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t,immediate:!0})}requestCheck(){x.has(this.s.state)||this[S].wake()}reset(){if(A(this))return;C(this,E),N(this),C(this,"idle");const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this[S]=p(I(this),{interval:e,minInterval:t})}close(){A(this)||(C(this,E),N(this),this.emit("close"),C(this,T))}}}},function(e,t,n){"use strict";const r=n(19),o=n(10).EventEmitter,s=n(78);class i{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map(e=>`${e.name}:${e.port}`))}}e.exports.SrvPollingEvent=i,e.exports.SrvPoller=class extends o{constructor(e){if(super(),!e||!e.srvHost)throw new TypeError("options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS||1e4,this.logger=r("srvPoller",e),this.haMode=!1,this.generation=0,this._timeout=null}get srvAddress(){return"_mongodb._tcp."+this.srvHost}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&(clearTimeout(this._timeout),this.generation+=1,this._timeout=null)}schedule(){clearTimeout(this._timeout),this._timeout=setTimeout(()=>this._poll(),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit("srvRecordDiscovery",new i(e))}failure(e,t){this.logger.warn(e,t),this.haMode=!0,this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;s.resolveSrv(this.srvAddress,(t,n)=>{if(e!==this.generation)return;if(t)return void this.failure("DNS error",t);const r=[];n.forEach(e=>{!function(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}(e.name,this.srvHost)?this.parentDomainMismatch(e):r.push(e)}),r.length?this.success(r):this.failure("No valid addresses found at host")})}}},function(e,t,n){"use strict";const r=n(15).ServerType,o=n(15).TopologyType,s=n(13),i=n(2).MongoError;function a(e,t){const n=Object.keys(e),r=Object.keys(t);for(let o=0;o-1===e?t.roundTripTime:Math.min(t.roundTripTime,e),-1),r=n+e.localThresholdMS;return t.reduce((e,t)=>(t.roundTripTime<=r&&t.roundTripTime>=n&&e.push(t),e),[])}function u(e){return e.type===r.RSPrimary}function l(e){return e.type===r.RSSecondary}function p(e){return e.type===r.RSSecondary||e.type===r.RSPrimary}function h(e){return e.type!==r.Unknown}e.exports={writableServerSelector:function(){return function(e,t){return c(e,t.filter(e=>e.isWritable))}},readPreferenceServerSelector:function(e){if(!e.isValid())throw new TypeError("Invalid read preference specified");return function(t,n){const r=t.commonWireVersion;if(r&&e.minWireVersion&&e.minWireVersion>r)throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${r}'`);if(t.type===o.Unknown)return[];if(t.type===o.Single||t.type===o.Sharded)return c(t,n.filter(h));const f=e.mode;if(f===s.PRIMARY)return n.filter(u);if(f===s.PRIMARY_PREFERRED){const e=n.filter(u);if(e.length)return e}const d=f===s.NEAREST?p:l,m=c(t,function(e,t){if(null==e.tags||Array.isArray(e.tags)&&0===e.tags.length)return t;for(let n=0;n(a(r,t.tags)&&e.push(t),e),[]);if(o.length)return o}return[]}(e,function(e,t,n){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return n;const r=e.maxStalenessSeconds,s=(t.heartbeatFrequencyMS+1e4)/1e3;if(r((o.lastUpdateTime-o.lastWriteDate-(r.lastUpdateTime-r.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}if(t.type===o.ReplicaSetNoPrimary){if(0===n.length)return n;const r=n.reduce((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e);return n.reduce((n,o)=>((r.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=e.maxStalenessSeconds&&n.push(o),n),[])}return n}(e,t,n.filter(d))));return f===s.SECONDARY_PREFERRED&&0===m.length?n.filter(u):m}}}},function(e,t,n){"use strict";const r=n(59),o=n(102),s=n(78),i=n(2).MongoParseError,a=n(13),c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;function u(e,t){const n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return r.endsWith(o)}function l(e,t){if(Array.isArray(t))1===(t=t.filter((e,n)=>t.indexOf(e)===n)).length&&(t=t[0]);else if(t.indexOf(":")>0)t=t.split(",").reduce((t,n)=>{const r=n.split(":");return t[r[0]]=l(e,r[1]),t},{});else if(t.indexOf(",")>0)t=t.split(",").map(t=>l(e,t));else if("true"===t.toLowerCase()||"false"===t.toLowerCase())t="true"===t.toLowerCase();else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);Number.isNaN(e)||(t=parseFloat(t))}return t}const p=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]),h=new Set(["authsource","replicaset"]),f=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]),d={replicaset:"replicaSet",connecttimeoutms:"connectTimeoutMS",sockettimeoutms:"socketTimeoutMS",maxpoolsize:"maxPoolSize",minpoolsize:"minPoolSize",maxidletimems:"maxIdleTimeMS",waitqueuemultiple:"waitQueueMultiple",waitqueuetimeoutms:"waitQueueTimeoutMS",wtimeoutms:"wtimeoutMS",readconcern:"readConcern",readconcernlevel:"readConcernLevel",readpreference:"readPreference",maxstalenessseconds:"maxStalenessSeconds",readpreferencetags:"readPreferenceTags",authsource:"authSource",authmechanism:"authMechanism",authmechanismproperties:"authMechanismProperties",gssapiservicename:"gssapiServiceName",localthresholdms:"localThresholdMS",serverselectiontimeoutms:"serverSelectionTimeoutMS",serverselectiontryonce:"serverSelectionTryOnce",heartbeatfrequencyms:"heartbeatFrequencyMS",retrywrites:"retryWrites",uuidrepresentation:"uuidRepresentation",zlibcompressionlevel:"zlibCompressionLevel",tlsallowinvalidcertificates:"tlsAllowInvalidCertificates",tlsallowinvalidhostnames:"tlsAllowInvalidHostnames",tlsinsecure:"tlsInsecure",tlscafile:"tlsCAFile",tlscertificatekeyfile:"tlsCertificateKeyFile",tlscertificatekeyfilepassword:"tlsCertificateKeyFilePassword",wtimeout:"wTimeoutMS",j:"journal",directconnection:"directConnection"};function m(e,t,n,r){if("journal"===t?t="j":"wtimeoutms"===t&&(t="wtimeout"),p.has(t)?n="true"===n||!0===n:"appname"===t?n=decodeURIComponent(n):"readconcernlevel"===t&&(e.readConcernLevel=n,t="readconcern",n={level:n}),"compressors"===t&&!(n=Array.isArray(n)?n:[n]).every(e=>"snappy"===e||"zlib"===e))throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`");if("authmechanism"===t&&!f.has(n))throw new i(`Value for authMechanism must be one of: ${Array.from(f).join(", ")}, found: ${n}`);if("readpreference"===t&&!a.isValid(n))throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`");if("zlibcompressionlevel"===t&&(n<-1||n>9))throw new i("zlibCompressionLevel must be an integer between -1 and 9");"compressors"!==t&&"zlibcompressionlevel"!==t||(e.compression=e.compression||{},e=e.compression),"authmechanismproperties"===t&&("string"==typeof n.SERVICE_NAME&&(e.gssapiServiceName=n.SERVICE_NAME),"string"==typeof n.SERVICE_REALM&&(e.gssapiServiceRealm=n.SERVICE_REALM),void 0!==n.CANONICALIZE_HOST_NAME&&(e.gssapiCanonicalizeHostName=n.CANONICALIZE_HOST_NAME)),"readpreferencetags"===t&&(n=Array.isArray(n)?function(e){const t=[];for(let n=0;n{const r=e.split(":");t[n][r[0]]=r[1]});return t}(n):[n]),r.caseTranslate&&d[t]?e[d[t]]=n:e[t]=n}const y=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function g(e,t){const n={};let r=o.parse(e);!function(e){const t=Object.keys(e);if(-1!==t.indexOf("tlsInsecure")&&(-1!==t.indexOf("tlsAllowInvalidCertificates")||-1!==t.indexOf("tlsAllowInvalidHostnames")))throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.");const n=b("tls",e,t),r=b("ssl",e,t);if(null!=n&&null!=r&&n!==r)throw new i("All values of `tls` and `ssl` must be the same.")}(r);for(const e in r){const o=r[e];if(""===o||null==o)throw new i("Incomplete key value pair for option");const s=e.toLowerCase();m(n,s,l(s,o),t)}return n.wtimeout&&n.wtimeoutms&&(delete n.wtimeout,console.warn("Unsupported option `wtimeout` specified")),Object.keys(n).length?n:null}function b(e,t,n){const r=-1!==n.indexOf(e);let o;if(o=Array.isArray(t[e])?t[e][0]:t[e],r&&Array.isArray(t[e])){const n=t[e][0];t[e].forEach(t=>{if(t!==n)throw new i(`All values of ${e} must be the same.`)})}return o}const S="mongodb+srv",v=["mongodb",S];function w(e,t,n){"function"==typeof t&&(n=t,t={}),t=Object.assign({},{caseTranslate:!0},t);try{r.parse(e)}catch(e){return n(new i("URI malformed, cannot be parsed"))}const a=e.match(c);if(!a)return n(new i("Invalid connection string"));const l=a[1];if(-1===v.indexOf(l))return n(new i("Invalid protocol provided"));const p=a[4].split("?"),h=p.length>0?p[0]:null,f=p.length>1?p[1]:null;let d;try{d=g(f,t)}catch(e){return n(e)}if(d=Object.assign({},d,t),l===S)return function(e,t,n){const a=r.parse(e,!0);if(t.directConnection||t.directconnection)return n(new i("directConnection not supported with SRV URI"));if(a.hostname.split(".").length<3)return n(new i("URI does not have hostname, domain name and tld"));if(a.domainLength=a.hostname.split(".").length,a.pathname&&a.pathname.match(","))return n(new i("Invalid URI, cannot contain multiple hostnames"));if(a.port)return n(new i(`Ports not accepted with '${S}' URIs`));const c=a.host;s.resolveSrv("_mongodb._tcp."+c,(e,l)=>{if(e)return n(e);if(0===l.length)return n(new i("No addresses found at host"));for(let e=0;e`${e.name}:${e.port}`).join(","),"ssl"in t||a.search&&"ssl"in a.query&&null!==a.query.ssl||(a.query.ssl=!0),s.resolveTxt(c,(e,s)=>{if(e){if("ENODATA"!==e.code)return n(e);s=null}if(s){if(s.length>1)return n(new i("Multiple text records not allowed"));if(s=o.parse(s[0].join("")),Object.keys(s).some(e=>"authSource"!==e&&"replicaSet"!==e))return n(new i("Text record must only set `authSource` or `replicaSet`"));a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);w(r.format(a),t,(e,t)=>{e?n(e):n(null,Object.assign({},t,{srvHost:c}))})})})}(e,d,n);const m={username:null,password:null,db:h&&""!==h?o.unescape(h):null};if(d.auth?(d.auth.username&&(m.username=d.auth.username),d.auth.user&&(m.username=d.auth.user),d.auth.password&&(m.password=d.auth.password)):(d.username&&(m.username=d.username),d.user&&(m.username=d.user),d.password&&(m.password=d.password)),-1!==a[4].split("?")[0].indexOf("@"))return n(new i("Unescaped slash in userinfo section"));const b=a[3].split("@");if(b.length>2)return n(new i("Unescaped at-sign in authority section"));if(null==b[0]||""===b[0])return n(new i("No username provided in authority section"));if(b.length>1){const e=b.shift().split(":");if(e.length>2)return n(new i("Unescaped colon in authority section"));if(""===e[0])return n(new i("Invalid empty username provided"));m.username||(m.username=o.unescape(e[0])),m.password||(m.password=e[1]?o.unescape(e[1]):null)}let _=null;const O=b.shift().split(",").map(e=>{let t=r.parse("mongodb://"+e);if("/:"===t.path)return _=new i("Double colon in host identifier"),null;if(e.match(/\.sock/)&&(t.hostname=o.unescape(e),t.port=null),Number.isNaN(t.port))return void(_=new i("Invalid port (non-numeric string)"));const n={host:t.hostname,port:t.port?parseInt(t.port):27017};if(0!==n.port)if(n.port>65535)_=new i("Invalid port (larger than 65535) with hostname");else{if(!(n.port<0))return n;_=new i("Invalid port (negative number)")}else _=new i("Invalid port (zero) with hostname")}).filter(e=>!!e);if(_)return n(_);if(0===O.length||""===O[0].host||null===O[0].host)return n(new i("No hostname or hostnames provided in connection string"));if(!!d.directConnection&&1!==O.length)return n(new i("directConnection option requires exactly one host"));null==d.directConnection&&1===O.length&&null==d.replicaSet&&(d.directConnection=!0);const T={hosts:O,auth:m.db||m.username?m:null,options:Object.keys(d).length?d:null};var E;T.auth&&T.auth.db?T.defaultDatabase=T.auth.db:T.defaultDatabase="test",T.options=((E=T.options).tls&&(E.ssl=E.tls),E.tlsInsecure?(E.checkServerIdentity=!1,E.sslValidate=!1):Object.assign(E,{checkServerIdentity:!E.tlsAllowInvalidHostnames,sslValidate:!E.tlsAllowInvalidCertificates}),E.tlsCAFile&&(E.ssl=!0,E.sslCA=E.tlsCAFile),E.tlsCertificateKeyFile&&(E.ssl=!0,E.tlsCertificateFile?(E.sslCert=E.tlsCertificateFile,E.sslKey=E.tlsCertificateKeyFile):(E.sslKey=E.tlsCertificateKeyFile,E.sslCert=E.tlsCertificateKeyFile)),E.tlsCertificateKeyFilePassword&&(E.ssl=!0,E.sslPass=E.tlsCertificateKeyFilePassword),E);try{!function(e){if(null==e.options)return;const t=e.options,n=t.authsource||t.authSource;null!=n&&(e.auth=Object.assign({},e.auth,{db:n}));const r=t.authmechanism||t.authMechanism;if(null!=r){if(y.has(r)&&(!e.auth||null==e.auth.username))throw new i(`Username required for mechanism \`${r}\``);if("GSSAPI"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-AWS"===r){if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}if("MONGODB-X509"===r){if(e.auth&&null!=e.auth.password)throw new i(`Password not allowed for mechanism \`${r}\``);if(null!=n&&"$external"!==n)throw new i(`Invalid source \`${n}\` for mechanism \`${r}\` specified.`);e.auth=Object.assign({},e.auth,{db:"$external"})}"PLAIN"===r&&e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"$external"}))}e.auth&&null==e.auth.db&&(e.auth=Object.assign({},e.auth,{db:"admin"}))}(T)}catch(e){return n(e)}n(null,T)}e.exports=w},function(e,t,n){"use strict";const r=n(10).EventEmitter;e.exports=class extends r{constructor(){super()}instrument(e,t){this.$MongoClient=e;const n=this.$prototypeConnect=e.prototype.connect,r=this;e.prototype.connect=function(e){return this.s.options.monitorCommands=!0,this.on("commandStarted",e=>r.emit("started",e)),this.on("commandSucceeded",e=>r.emit("succeeded",e)),this.on("commandFailed",e=>r.emit("failed",e)),n.call(this,e)},"function"==typeof t&&t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}},function(e,t,n){"use strict";const r=n(46).buildCountCommand,o=n(0).handleCallback,s=n(1).MongoError,i=Array.prototype.push,a=n(20).CursorState;function c(e,t){if(0!==e.bufferedCount())return e._next(t),c}e.exports={count:function(e,t,n,o){t&&("number"==typeof e.cursorSkip()&&(n.skip=e.cursorSkip()),"number"==typeof e.cursorLimit()&&(n.limit=e.cursorLimit())),n.readPreference&&e.setReadPreference(n.readPreference),"number"!=typeof n.maxTimeMS&&e.cmd&&"number"==typeof e.cmd.maxTimeMS&&(n.maxTimeMS=e.cmd.maxTimeMS);let s,i={};i.skip=n.skip,i.limit=n.limit,i.hint=n.hint,i.maxTimeMS=n.maxTimeMS,i.collectionName=e.namespace.collection;try{s=r(e,e.cmd.query,i)}catch(e){return o(e)}e.server=e.topology.s.coreTopology,e.topology.command(e.namespace.withCollection("$cmd"),s,e.options,(e,t)=>{o(e,t?t.result.n:null)})},each:function e(t,n){if(!n)throw s.create({message:"callback is mandatory",driver:!0});if(t.isNotified())return;if(t.s.state===a.CLOSED||t.isDead())return o(n,s.create({message:"Cursor is closed",driver:!0}));t.s.state===a.INIT&&(t.s.state=a.OPEN);let r=null;if(t.bufferedCount()>0){for(;r=c(t,n);)r(t,n);e(t,n)}else t.next((r,s)=>r?o(n,r):null==s?t.close({skipKillCursors:!0},()=>o(n,null,null)):void(!1!==o(n,null,s)&&e(t,n)))},toArray:function(e,t){const n=[];e.rewind(),e.s.state=a.INIT;const r=()=>{e._next((s,a)=>{if(s)return o(t,s);if(null==a)return e.close({skipKillCursors:!0},()=>o(t,null,n));if(n.push(a),e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());e.s.transforms&&"function"==typeof e.s.transforms.doc&&(t=t.map(e.s.transforms.doc)),i.apply(n,t)}r()})};r()}}},function(e,t,n){"use strict";const r=n(12).buildCountCommand,o=n(3).OperationBase;e.exports=class extends o{constructor(e,t,n){super(n),this.cursor=e,this.applySkipLimit=t}execute(e){const t=this.cursor,n=this.applySkipLimit,o=this.options;n&&("number"==typeof t.cursorSkip()&&(o.skip=t.cursorSkip()),"number"==typeof t.cursorLimit()&&(o.limit=t.cursorLimit())),o.readPreference&&t.setReadPreference(o.readPreference),"number"!=typeof o.maxTimeMS&&t.cmd&&"number"==typeof t.cmd.maxTimeMS&&(o.maxTimeMS=t.cmd.maxTimeMS);let s,i={};i.skip=o.skip,i.limit=o.limit,i.hint=o.hint,i.maxTimeMS=o.maxTimeMS,i.collectionName=t.namespace.collection;try{s=r(t,t.cmd.query,i)}catch(t){return e(t)}t.server=t.topology.s.coreTopology,t.topology.command(t.namespace.withCollection("$cmd"),s,t.options,(t,n)=>{e(t,n?n.result.n:null)})}}},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null,t===r.INSERT?e.s.currentBatch=e.s.currentInsertBatch:t===r.UPDATE?e.s.currentBatch=e.s.currentUpdateBatch:t===r.REMOVE&&(e.s.currentBatch=e.s.currentRemoveBatch);const c=e.s.maxKeySize;if(null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex)),(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex)),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.operations.push(n),e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentIndex=e.s.currentIndex+1,t===r.INSERT?(e.s.currentInsertBatch=e.s.currentBatch,e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:n._id})):t===r.UPDATE?e.s.currentUpdateBatch=e.s.currentBatch:t===r.REMOVE&&(e.s.currentRemoveBatch=e.s.currentBatch),e.s.currentBatch.size+=1,e.s.currentBatch.sizeBytes+=c+o,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!1)}handleWriteError(e,t){return!this.s.batches.length&&super.handleWriteError(e,t)}}function l(e,t,n){return new u(e,t,n)}l.UnorderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(81),o=r.BulkOperationBase,s=r.Batch,i=r.bson,a=n(0).toError;function c(e,t,n){const o=i.calculateObjectSize(n,{checkKeys:!1,ignoreUndefined:!1});if(o>=e.s.maxBsonObjectSize)throw a("document is larger than the maximum size "+e.s.maxBsonObjectSize);null==e.s.currentBatch&&(e.s.currentBatch=new s(t,e.s.currentIndex));const c=e.s.maxKeySize;if((e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+c+o>=e.s.maxBatchSizeBytes||e.s.currentBatch.batchType!==t)&&(e.s.batches.push(e.s.currentBatch),e.s.currentBatch=new s(t,e.s.currentIndex),e.s.currentBatchSize=0,e.s.currentBatchSizeBytes=0),t===r.INSERT&&e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:n._id}),Array.isArray(n))throw a("operation passed in cannot be an Array");return e.s.currentBatch.originalIndexes.push(e.s.currentIndex),e.s.currentBatch.operations.push(n),e.s.currentBatchSize+=1,e.s.currentBatchSizeBytes+=c+o,e.s.currentIndex+=1,e}class u extends o{constructor(e,t,n){n=n||{},super(e,t,n=Object.assign(n,{addToOperationsList:c}),!0)}}function l(e,t,n){return new u(e,t,n)}l.OrderedBulkOperation=u,e.exports=l,e.exports.Bulk=u},function(e,t,n){"use strict";const r=n(63);e.exports=class extends r{constructor(e,t,n){const r=[{$match:t}];"number"==typeof n.skip&&r.push({$skip:n.skip}),"number"==typeof n.limit&&r.push({$limit:n.limit}),r.push({$group:{_id:1,n:{$sum:1}}}),super(e,r,n)}execute(e,t){super.execute(e,(e,n)=>{if(e)return void t(e,null);const r=n.result;if(null==r.cursor||null==r.cursor.firstBatch)return void t(null,0);const o=r.cursor.firstBatch;t(null,o.length?o[0].n:0)})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!1,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).deleteCallback,s=n(12).removeDocuments;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.filter=t}execute(e){const t=this.collection,n=this.filter,r=this.options;r.single=!0,s(t,n,r,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(0).decorateWithCollation,a=n(0).decorateWithReadConcern;class c extends s{constructor(e,t,n,r){super(e,r),this.collection=e,this.key=t,this.query=n}execute(e,t){const n=this.collection,r=this.key,o=this.query,s=this.options,c={distinct:n.collectionName,key:r,query:o};"number"==typeof s.maxTimeMS&&(c.maxTimeMS=s.maxTimeMS),a(c,n,s);try{i(c,n,s)}catch(e){return t(e,null)}super.executeCommand(e,c,(e,n)=>{e?t(e):t(null,this.options.full?n:n.values)})}}o(c,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(115),i=n(0).handleCallback;class a extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute(t=>{if(t)return i(e,t,!1);i(e,null,!0)})}}o(a,r.WRITE_OPERATION),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26);class i extends s{constructor(e,t,n){void 0===n&&(n=t,t=void 0),super(e,n),this.collectionName=e.s.namespace.collection,t&&(this.query=t)}execute(e,t){const n=this.options,r={count:this.collectionName};this.query&&(r.query=this.query),"number"==typeof n.skip&&(r.skip=n.skip),"number"==typeof n.limit&&(r.limit=n.limit),n.hint&&(r.hint=n.hint),super.executeCommand(e,r,(e,n)=>{e?t(e):t(null,n.n)})}}o(i,[r.READ_OPERATION,r.RETRYABLE,r.EXECUTE_WITH_SELECTION]),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(3).Aspect,s=n(3).defineAspects,i=n(1).ReadPreference,a=n(4).maxWireVersion,c=n(2).MongoError;class u extends r{constructor(e,t,n,r){super(r),this.ns=t,this.cmd=n,this.readPreference=i.resolve(e,this.options)}execute(e,t){if(this.server=e,void 0!==this.cmd.allowDiskUse&&a(e)<4)return void t(new c("The `allowDiskUse` option is not supported on MongoDB < 3.2"));const n=this.cursorState||{};e.query(this.ns.toString(),this.cmd,n,this.options,t)}}s(u,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(0).handleCallback,o=n(3).OperationBase,s=n(0).toError;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.query=t}execute(e){const t=this.collection,n=this.query,o=this.options;try{t.find(n,o).limit(-1).batchSize(1).next((t,n)=>{if(null!=t)return r(e,s(t),null);r(e,null,n)})}catch(t){e(t)}}}},function(e,t,n){"use strict";const r=n(64);e.exports=class extends r{constructor(e,t,n){const r=Object.assign({},n);if(r.fields=n.projection,r.remove=!0,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");super(e,t,r.sort,null,r)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new=void 0!==r.returnOriginal&&!r.returnOriginal,s.upsert=void 0!==r.upsert&&!!r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Replacement parameter must be an object");if(o(n))throw new TypeError("Replacement document must not contain atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(64),o=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){const s=Object.assign({},r);if(s.fields=r.projection,s.update=!0,s.new="boolean"==typeof r.returnOriginal&&!r.returnOriginal,s.upsert="boolean"==typeof r.upsert&&r.upsert,null==t||"object"!=typeof t)throw new TypeError("Filter parameter must be an object");if(null==n||"object"!=typeof n)throw new TypeError("Update parameter must be an object");if(!o(n))throw new TypeError("Update document requires atomic operators");super(e,t,s.sort,n,s)}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(3).OperationBase,i=n(0).decorateCommand,a=n(0).decorateWithReadConcern,c=n(14).executeCommand,u=n(0).handleCallback,l=n(1).ReadPreference,p=n(0).toError;class h extends s{constructor(e,t,n,r){super(r),this.collection=e,this.x=t,this.y=n}execute(e){const t=this.collection,n=this.x,r=this.y;let o=this.options,s={geoSearch:t.collectionName,near:[n,r]};s=i(s,o,["readPreference","session"]),o=Object.assign({},o),o.readPreference=l.resolve(t,o),a(s,t,o),c(t.s.db,s,o,(t,n)=>{if(t)return u(e,t);(n.err||n.errmsg)&&u(e,p(n)),u(e,null,n)})}}o(h,r.READ_OPERATION),e.exports=h},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).indexInformation;e.exports=class extends r{constructor(e,t){super(t),this.collection=e}execute(e){const t=this.collection;let n=this.options;n=Object.assign({},{full:!0},n),o(t.s.db,t.collectionName,n,e)}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback,s=n(14).indexInformation;e.exports=class extends r{constructor(e,t,n){super(n),this.collection=e,this.indexes=t}execute(e){const t=this.collection,n=this.indexes,r=this.options;s(t.s.db,t.collectionName,r,(t,r)=>{if(null!=t)return o(e,t,null);if(!Array.isArray(n))return o(e,null,null!=r[n]);for(let t=0;t{if(t)return e(t,null);e(null,function(e,t){const n={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};t.getLastOp()&&(n.result.opTime=t.getLastOp());return n}(n,r))})}}},function(e,t,n){"use strict";const r=n(1).MongoError,o=n(3).OperationBase,s=n(12).insertDocuments;e.exports=class extends o{constructor(e,t,n){super(n),this.collection=e,this.doc=t}execute(e){const t=this.collection,n=this.doc,o=this.options;if(Array.isArray(n))return e(r.create({message:"doc parameter must be an object",driver:!0}));s(t,[n],o,(t,r)=>{if(null!=e){if(t&&e)return e(t);if(null==r)return e(null,{result:{ok:1}});r.insertedCount=r.result.n,r.insertedId=n._id,e&&e(null,r)}})}}},function(e,t,n){"use strict";const r=n(117),o=n(0).handleCallback;e.exports=class extends r{constructor(e,t){super(e,t)}execute(e){super.execute((t,n)=>{if(t)return o(e,t);o(e,null,!(!n||!n.capped))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion;class a extends r{constructor(e,t){super(e,t,{fullResponse:!0}),this.collectionNamespace=e.s.namespace}execute(e,t){if(i(e)<3){const n=this.collectionNamespace.withCollection("system.indexes").toString(),r=this.collectionNamespace.toString();return void e.query(n,{query:{ns:r}},{},this.options,t)}const n=this.options.batchSize?{batchSize:this.options.batchSize}:{};super.executeCommand(e,{listIndexes:this.collectionNamespace.collection,cursor:n},t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(0).applyWriteConcern,o=n(1).BSON.Code,s=n(0).decorateWithCollation,i=n(0).decorateWithReadConcern,a=n(14).executeCommand,c=n(0).handleCallback,u=n(0).isObject,l=n(85).loadDb,p=n(3).OperationBase,h=n(1).ReadPreference,f=n(0).toError,d=["readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];function m(e){if(!u(e)||"ObjectID"===e._bsontype)return e;const t=Object.keys(e);let n;const r={};for(let s=t.length-1;s>=0;s--)n=t[s],"function"==typeof e[n]?r[n]=new o(String(e[n])):r[n]=m(e[n]);return r}e.exports=class extends p{constructor(e,t,n,r){super(r),this.collection=e,this.map=t,this.reduce=n}execute(e){const t=this.collection,n=this.map,o=this.reduce;let u=this.options;const p={mapReduce:t.collectionName,map:n,reduce:o};for(let e in u)"scope"===e?p[e]=m(u[e]):-1===d.indexOf(e)&&(p[e]=u[e]);u=Object.assign({},u),u.readPreference=h.resolve(t,u),!1!==u.readPreference&&"primary"!==u.readPreference&&u.out&&1!==u.out.inline&&"inline"!==u.out?(u.readPreference="primary",r(p,{db:t.s.db,collection:t},u)):i(p,t,u),!0===u.bypassDocumentValidation&&(p.bypassDocumentValidation=u.bypassDocumentValidation);try{s(p,t,u)}catch(t){return e(t,null)}a(t.s.db,p,u,(n,r)=>{if(n)return c(e,n);if(1!==r.ok||r.err||r.errmsg)return c(e,f(r));const o={};if(r.timeMillis&&(o.processtime=r.timeMillis),r.counts&&(o.counts=r.counts),r.timing&&(o.timing=r.timing),r.results)return null!=u.verbose&&u.verbose?c(e,null,{results:r.results,stats:o}):c(e,null,r.results);let s=null;if(null!=r.result&&"object"==typeof r.result){const e=r.result;s=new(l())(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else s=t.s.db.collection(r.result);if(null==u.verbose||!u.verbose)return c(e,n,s);c(e,n,{collection:s,stats:o})})}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(0).handleCallback;let s;e.exports=class extends r{constructor(e,t){super(t),this.db=e}execute(e){const t=this.db;let r=this.options,i=(s||(s=n(47)),s);r=Object.assign({},r,{nameOnly:!0}),t.listCollections({},r).toArray((n,r)=>{if(null!=n)return o(e,n,null);r=r.filter(e=>-1===e.name.indexOf("$")),o(e,null,r.map(e=>new i(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options)))})}}},function(e,t,n){"use strict";const r=n(26),o=n(3).defineAspects,s=n(3).Aspect;class i extends r{constructor(e,t,n){super(e,n),this.command=t}execute(e,t){const n=this.command;this.executeCommand(e,n,t)}}o(i,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]),e.exports=i},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(23),i=n(0).applyWriteConcern,a=n(85).loadCollection,c=n(1).MongoError,u=n(1).ReadPreference,l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class p extends s{constructor(e,t,n){super(e,n),this.name=t}_buildCommand(){const e=this.name,t=this.options,n={create:e};for(let e in t)null==t[e]||"function"==typeof t[e]||l.has(e)||(n[e]=t[e]);return n}execute(e){const t=this.db,n=this.name,r=this.options,o=a();let s=Object.assign({nameOnly:!0,strict:!1},r);function l(s){if(s)return e(s);try{e(null,new o(t,t.s.topology,t.databaseName,n,t.s.pkFactory,r))}catch(s){e(s)}}s=i(s,{db:t},s);s.strict?t.listCollections({name:n},s).setReadPreference(u.PRIMARY).toArray((t,r)=>t?e(t):r.length>0?e(new c(`Collection ${n} already exists. Currently in strict mode.`)):void super.execute(l)):super.execute(l)}}o(p,r.WRITE_OPERATION),e.exports=p},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(4).maxWireVersion,a=n(80);class c extends r{constructor(e,t,n){super(e,n,{fullResponse:!0}),this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize)}execute(e,t){if(i(e)<3){let n=this.filter;const r=this.db.s.namespace.db;"string"!=typeof n.name||new RegExp("^"+r+"\\.").test(n.name)||(n=Object.assign({},n),n.name=this.db.s.namespace.withCollection(n.name).toString()),null==n&&(n.name=`/${r}/`),n=n.name?{$and:[{name:n.name},{name:/^((?!\$).)*$/}]}:{name:/^((?!\$).)*$/};const o=function(e){const t=e+".";return{doc:e=>{const n=e.name.indexOf(t);return e.name&&0===n&&(e.name=e.name.substr(n+t.length)),e}}}(r);return void e.query(`${r}.${a.SYSTEM_NAMESPACE_COLLECTION}`,{query:n},{batchSize:this.batchSize||1e3},{},(e,n)=>{n&&n.message&&n.message.documents&&Array.isArray(n.message.documents)&&(n.message.documents=n.message.documents.map(o.doc)),t(e,n)})}const n={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,n,t)}}s(c,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=c},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){super(e,n)}_buildCommand(){return{profile:-1}}execute(e){super.execute((t,n)=>{if(null==t&&1===n.ok){const t=n.was;return 0===t?e(null,"off"):1===t?e(null,"slow_only"):2===t?e(null,"all"):e(new Error("Error: illegal profiling level value "+t),null)}e(null!=t?t:new Error("Error with profile command"),null)})}}},function(e,t,n){"use strict";const r=n(23),o=new Set(["off","slow_only","all"]);e.exports=class extends r{constructor(e,t,n){let r=0;"off"===t?r=0:"slow_only"===t?r=1:"all"===t&&(r=2),super(e,n),this.level=t,this.profile=r}_buildCommand(){return{profile:this.profile}}execute(e){const t=this.level;if(!o.has(t))return e(new Error("Error: illegal profiling level value "+t));super.execute((n,r)=>null==n&&1===r.ok?e(null,t):e(null!=n?n:new Error("Error with profile command"),null))}}},function(e,t,n){"use strict";const r=n(23);e.exports=class extends r{constructor(e,t,n){let r={validate:t};const o=Object.keys(n);for(let e=0;enull!=n?e(n,null):0===r.ok?e(new Error("Error with validate command"),null):null!=r.result&&r.result.constructor!==String?e(new Error("Error with validation data"),null):null!=r.result&&null!=r.result.match(/exception|corrupt/)?e(new Error("Error: invalid collection "+t),null):null==r.valid||r.valid?e(null,r):e(new Error("Error: invalid collection "+t),null))}}},function(e,t,n){"use strict";const r=n(26),o=n(3).Aspect,s=n(3).defineAspects,i=n(0).MongoDBNamespace;class a extends r{constructor(e,t){super(e,t),this.ns=new i("admin","$cmd")}execute(e,t){const n={listDatabases:1};this.options.nameOnly&&(n.nameOnly=Number(n.nameOnly)),this.options.filter&&(n.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(n.authorizedDatabases=this.options.authorizedDatabases),super.executeCommand(e,n,t)}}s(a,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]),e.exports=a},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(3).defineAspects,s=n(26),i=n(15).serverType,a=n(15).ServerType,c=n(1).MongoError;class u extends s{constructor(e,t){super(e,t),this.collectionName=e.collectionName}execute(e,t){i(e)===a.Standalone?super.executeCommand(e,{reIndex:this.collectionName},(e,n)=>{e?t(e):t(null,!!n.ok)}):t(new c("reIndex can only be executed on standalone servers."))}}o(u,[r.EXECUTE_WITH_SELECTION]),e.exports=u},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),s(n))throw new TypeError("Replacement document must not contain atomic operators");this.collection=e,this.filter=t,this.replacement=n}execute(e){const t=this.collection,n=this.filter,r=this.replacement,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n,r){if(null==r)return;if(e&&r)return r(e);if(null==t)return r(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,t.ops=[n],r&&r(null,t)}(t,n,r,e))}}},function(e,t,n){"use strict";const r=n(3).Aspect,o=n(23),s=n(3).defineAspects;class i extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection,t=this.options,n={collStats:e.collectionName};return null!=t.scale&&(n.scale=t.scale),n}}s(i,r.READ_OPERATION),e.exports=i},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateCallback,s=n(12).updateDocuments,i=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!i(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,i=this.options;i.multi=!0,s(t,n,r,i,(t,n)=>o(t,n,e))}}},function(e,t,n){"use strict";const r=n(3).OperationBase,o=n(12).updateDocuments,s=n(0).hasAtomicOperators;e.exports=class extends r{constructor(e,t,n,r){if(super(r),!s(n))throw new TypeError("Update document requires atomic operators");this.collection=e,this.filter=t,this.update=n}execute(e){const t=this.collection,n=this.filter,r=this.update,s=this.options;s.multi=!1,o(t,n,r,s,(t,n)=>function(e,t,n){if(null==n)return;if(e)return n(e);if(null==t)return n(null,{result:{ok:1}});t.modifiedCount=null!=t.result.nModified?t.result.nModified:t.result.n,t.upsertedId=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?t.result.upserted[0]:null,t.upsertedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length?t.result.upserted.length:0,t.matchedCount=Array.isArray(t.result.upserted)&&t.result.upserted.length>0?0:t.result.n,n(null,t)}(t,n,e))}}},function(e,t,n){"use strict";const r=n(1).ReadPreference,o=n(59),s=n(5).format,i=n(1).Logger,a=n(78),c=n(36);function u(e,t){let n=/^.*?\./,r="."+e.replace(n,""),o="."+t.replace(n,"");return!!r.endsWith(o)}function l(e,t,n){let a,u;try{a=function(e,t){let n="",a="",u="",l="admin",p=o.parse(e,!0);if((null==p.hostname||""===p.hostname)&&-1===e.indexOf(".sock"))throw new Error("No hostname or hostnames provided in connection string");if("0"===p.port)throw new Error("Invalid port (zero) with hostname");if(!isNaN(parseInt(p.port,10))&&parseInt(p.port,10)>65535)throw new Error("Invalid port (larger than 65535) with hostname");if(p.path&&p.path.length>0&&"/"!==p.path[0]&&-1===e.indexOf(".sock"))throw new Error("Missing delimiting slash between hosts and options");if(p.query)for(let e in p.query){if(-1!==e.indexOf("::"))throw new Error("Double colon in host identifier");if(""===p.query[e])throw new Error("Query parameter "+e+" is an incomplete value pair")}if(p.auth){let t=p.auth.split(":");if(-1!==e.indexOf(p.auth)&&t.length>2)throw new Error("Username with password containing an unescaped colon");if(-1!==e.indexOf(p.auth)&&-1!==p.auth.indexOf("@"))throw new Error("Username containing an unescaped at-sign")}let h=e.split("?").shift().split(","),f=[];for(let e=0;e1&&-1===t.path.indexOf("::")?new Error("Slash in host identifier"):new Error("Double colon in host identifier")}-1!==e.indexOf("?")?(u=e.substr(e.indexOf("?")+1),n=e.substring("mongodb://".length,e.indexOf("?"))):n=e.substring("mongodb://".length);-1!==n.indexOf("@")&&(a=n.split("@")[0],n=n.split("@")[1]);if(n.split("/").length>2)throw new Error("Unsupported host '"+n.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash");if(-1!==n.indexOf(".sock")){if(-1!==n.indexOf(".sock/")){if(l=n.split(".sock/")[1],-1!==l.indexOf("/")){if(2===l.split("/").length&&0===l.split("/")[1].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}n=n.split("/",n.indexOf(".sock")+".sock".length)}}else if(-1!==n.indexOf("/")){if(n.split("/").length>2){if(0===n.split("/")[2].length)throw new Error("Illegal trailing backslash after database name");throw new Error("More than 1 database name in URL")}l=n.split("/")[1],n=n.split("/")[0]}n=decodeURIComponent(n);let d,m,y,g,b={},S=a||"",v=S.split(":",2),w=decodeURIComponent(v[0]);if(v[0]!==encodeURIComponent(w))throw new Error("Username contains an illegal unescaped character");if(v[0]=w,v[1]){let e=decodeURIComponent(v[1]);if(v[1]!==encodeURIComponent(e))throw new Error("Password contains an illegal unescaped character");v[1]=e}2===v.length&&(b.auth={user:v[0],password:v[1]});t&&null!=t.auth&&(b.auth=t.auth);let _={socketOptions:{}},O={read_preference_tags:[]},T={socketOptions:{}},E={socketOptions:{}};if(b.server_options=_,b.db_options=O,b.rs_options=T,b.mongos_options=E,e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);-1!==t.indexOf("@")&&(t=t.split("@")[1]),t=decodeURIComponent(t),y=[{domain_socket:t}]}else{d=n;let e={};y=d.split(",").map((function(t){let n,r,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t))n=o[1],r=parseInt(o[2],10)||27017;else{let e=t.split(":",2);n=e[0]||"localhost",r=null!=e[1]?parseInt(e[1],10):27017,-1!==n.indexOf("?")&&(n=n.split(/\?/)[0])}return e[n+"_"+r]?null:(e[n+"_"+r]=1,{host:n,port:r})})).filter((function(e){return null!=e}))}b.dbName=l||"admin",m=(u||"").split(/[&;]/),m.forEach((function(e){if(e){var t=e.split("="),n=t[0],o=t[1];switch(n){case"slaveOk":case"slave_ok":_.slave_ok="true"===o,O.slaveOk="true"===o;break;case"maxPoolSize":case"poolSize":_.poolSize=parseInt(o,10),T.poolSize=parseInt(o,10);break;case"appname":b.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":_.auto_reconnect="true"===o;break;case"ssl":if("prefer"===o){_.ssl=o,T.ssl=o,E.ssl=o;break}_.ssl="true"===o,T.ssl="true"===o,E.ssl="true"===o;break;case"sslValidate":_.sslValidate="true"===o,T.sslValidate="true"===o,E.sslValidate="true"===o;break;case"replicaSet":case"rs_name":T.rs_name=o;break;case"reconnectWait":T.reconnectWait=parseInt(o,10);break;case"retries":T.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":T.read_secondary="true"===o;break;case"fsync":O.fsync="true"===o;break;case"journal":O.j="true"===o;break;case"safe":O.safe="true"===o;break;case"nativeParser":case"native_parser":O.native_parser="true"===o;break;case"readConcernLevel":O.readConcern=new c(o);break;case"connectTimeoutMS":_.socketOptions.connectTimeoutMS=parseInt(o,10),T.socketOptions.connectTimeoutMS=parseInt(o,10),E.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":_.socketOptions.socketTimeoutMS=parseInt(o,10),T.socketOptions.socketTimeoutMS=parseInt(o,10),E.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":O.w=parseInt(o,10),isNaN(O.w)&&(O.w=o);break;case"authSource":O.authSource=o;break;case"gssapiServiceName":O.gssapiServiceName=o;break;case"authMechanism":if("GSSAPI"===o)if(null==b.auth){let e=decodeURIComponent(S);if(-1===e.indexOf("@"))throw new Error("GSSAPI requires a provided principal");b.auth={user:e,password:null}}else b.auth.user=decodeURIComponent(b.auth.user);else"MONGODB-X509"===o&&(b.auth={user:decodeURIComponent(S)});if("GSSAPI"!==o&&"MONGODB-X509"!==o&&"MONGODB-CR"!==o&&"DEFAULT"!==o&&"SCRAM-SHA-1"!==o&&"SCRAM-SHA-256"!==o&&"PLAIN"!==o)throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");O.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(","),t={};e.forEach((function(e){let n=e.split(":");t[n[0]]=n[1]})),O.authMechanismProperties=t,"string"==typeof t.SERVICE_NAME&&(O.gssapiServiceName=t.SERVICE_NAME),"string"==typeof t.SERVICE_REALM&&(O.gssapiServiceRealm=t.SERVICE_REALM),"string"==typeof t.CANONICALIZE_HOST_NAME&&(O.gssapiCanonicalizeHostName="true"===t.CANONICALIZE_HOST_NAME)}break;case"wtimeoutMS":O.wtimeout=parseInt(o,10);break;case"readPreference":if(!r.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");O.readPreference=o;break;case"maxStalenessSeconds":O.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{let e={};if(null==(o=decodeURIComponent(o))||""===o){O.read_preference_tags.push(e);break}let t=o.split(/,/);for(let n=0;n9)throw new Error("zlibCompressionLevel must be an integer between -1 and 9");g.zlibCompressionLevel=e,_.compression=g}break;case"retryWrites":O.retryWrites="true"===o;break;case"minSize":O.minSize=parseInt(o,10);break;default:i("URL Parser").warn(n+" is not supported as a connection string option")}}})),0===O.read_preference_tags.length&&(O.read_preference_tags=null);if(!(-1!==O.w&&0!==O.w||!0!==O.journal&&!0!==O.fsync&&!0!==O.safe))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");O.readPreference||(O.readPreference="primary");return O=Object.assign(O,t),b.servers=y,b}(e,t)}catch(e){u=e}return u?n(u,null):n(null,a)}e.exports=function(e,t,n){let r;"function"==typeof t&&(n=t,t={}),t=t||{};try{r=o.parse(e,!0)}catch(e){return n(new Error("URL malformed, cannot be parsed"))}if("mongodb:"!==r.protocol&&"mongodb+srv:"!==r.protocol)return n(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"));if("mongodb:"===r.protocol)return l(e,t,n);if(r.hostname.split(".").length<3)return n(new Error("URI does not have hostname, domain name and tld"));if(r.domainLength=r.hostname.split(".").length,r.pathname&&r.pathname.match(","))return n(new Error("Invalid URI, cannot contain multiple hostnames"));if(r.port)return n(new Error("Ports not accepted with `mongodb+srv` URIs"));let s="_mongodb._tcp."+r.host;a.resolveSrv(s,(function(e,o){if(e)return n(e);if(0===o.length)return n(new Error("No addresses found at host"));for(let e=0;e1)return n(new Error("Multiple text records not allowed"));if(!(r=(r=r[0]).length>1?r.join(""):r[0]).includes("authSource")&&!r.includes("replicaSet"))return n(new Error("Text record must only set `authSource` or `replicaSet`"));c.push(r)}c.length&&(i+="?"+c.join("&")),l(i,t,n)}))}))}},function(e,t,n){"use strict";e.exports=function(e){const t=n(95),r=e.mongodb.MongoTimeoutError,o=n(67),s=o.debug,i=o.databaseNamespace,a=o.collectionNamespace,c=o.MongoCryptError,u=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]);return{StateMachine:class{constructor(e){this.options=e||{},this.bson=e.bson}execute(e,t,n){const o=this.bson,i=e._client,a=e._keyVaultNamespace,l=e._keyVaultClient,p=e._mongocryptdClient,h=e._mongocryptdManager;switch(s(`[context#${t.id}] ${u.get(t.state)||t.state}`),t.state){case 1:{const r=o.deserialize(t.nextMongoOperation());return void this.fetchCollectionInfo(i,t.ns,r,(r,o)=>{if(r)return n(r,null);o&&t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}case 2:{const o=t.nextMongoOperation();return void this.markCommand(p,t.ns,o,(s,i)=>{if(s)return s instanceof r&&h&&!h.bypassSpawn?void h.spawn(()=>{this.markCommand(p,t.ns,o,(r,o)=>{if(r)return n(r,null);t.addMongoOperationResponse(o),t.finishMongoOperation(),this.execute(e,t,n)})}):n(s,null);t.addMongoOperationResponse(i),t.finishMongoOperation(),this.execute(e,t,n)})}case 3:{const r=t.nextMongoOperation();return void this.fetchKeys(l,a,r,(r,s)=>{if(r)return n(r,null);s.forEach(e=>{t.addMongoOperationResponse(o.serialize(e))}),t.finishMongoOperation(),this.execute(e,t,n)})}case 4:{const r=[];let o;for(;o=t.nextKMSRequest();)r.push(this.kmsRequest(o));return void Promise.all(r).then(()=>{t.finishKMSRequests(),this.execute(e,t,n)}).catch(e=>{n(e,null)})}case 5:{const e=t.finalize();if(0===t.state){const e=t.status.message||"Finalization error";return void n(new c(e))}return void n(null,o.deserialize(e,this.options))}case 0:{const e=t.status.message;return void n(new c(e))}case 6:return;default:return void n(new c("Unknown state: "+t.state))}}kmsRequest(e){const n=e.endpoint.split(":"),r=null!=n[1]?Number.parseInt(n[1],10):443,o={host:n[0],port:r},s=e.message;return new Promise((n,r)=>{const i=t.connect(o,()=>{i.write(s)});i.once("timeout",()=>{i.removeAllListeners(),i.destroy(),r(new c("KMS request timed out"))}),i.once("error",e=>{i.removeAllListeners(),i.destroy();const t=new c("KMS request failed");t.originalError=e,r(t)}),i.on("data",t=>{e.addResponse(t),e.bytesNeeded<=0&&i.end(n)})})}fetchCollectionInfo(e,t,n,r){const o=this.bson,s=i(t);e.db(s).listCollections(n).toArray((e,t)=>{if(e)return void r(e,null);const n=t.length>0?o.serialize(t[0]):null;r(null,n)})}markCommand(e,t,n,r){const o=this.bson,s=i(t),a=o.deserialize(n,{promoteLongs:!1,promoteValues:!1});e.db(s).command(a,(e,t)=>{r(e,e?null:o.serialize(t,this.options))})}fetchKeys(e,t,n,r){const o=this.bson,s=i(t),c=a(t);n=o.deserialize(n),e.db(s).collection(c,{readConcern:{level:"majority"}}).find(n).toArray((e,t)=>{e?r(e,null):r(null,t)})}}}}},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67).databaseNamespace,o=e.stateMachine.StateMachine,s=n(221).MongocryptdManager,i=e.mongodb.MongoClient,a=e.mongodb.MongoError,c=n(129);return{AutoEncrypter:class{constructor(e,n){this._client=e,this._bson=n.bson||e.topology.bson,this._mongocryptdManager=new s(n.extraOptions),this._mongocryptdClient=new i(this._mongocryptdManager.uri,{useNewUrlParser:!0,useUnifiedTopology:!0,serverSelectionTimeoutMS:1e3}),this._keyVaultNamespace=n.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=n.keyVaultClient||e,this._bypassEncryption="boolean"==typeof n.bypassAutoEncryption&&n.bypassAutoEncryption;const r={};n.schemaMap&&(r.schemaMap=Buffer.isBuffer(n.schemaMap)?n.schemaMap:this._bson.serialize(n.schemaMap)),n.kmsProviders&&(r.kmsProviders=n.kmsProviders),n.logger&&(r.logger=n.logger),Object.assign(r,{cryptoCallbacks:c}),this._mongocrypt=new t.MongoCrypt(r),this._contextCounter=0}init(e){const t=(t,n)=>{t&&t.message&&t.message.match(/timed out after/)?e(new a("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn")):e(t,n)};if(this._mongocryptdManager.bypassSpawn)return this._mongocryptdClient.connect(t);this._mongocryptdManager.spawn(()=>this._mongocryptdClient.connect(t))}teardown(e,t){this._mongocryptdClient.close(e,t)}encrypt(e,t,n,s){if("string"!=typeof e)throw new TypeError("Parameter `ns` must be a string");if("object"!=typeof t)throw new TypeError("Parameter `cmd` must be an object");if("function"==typeof n&&null==s&&(s=n,n={}),this._bypassEncryption)return void s(void 0,t);const i=this._bson,a=Buffer.isBuffer(t)?t:i.serialize(t,n);let c;try{c=this._mongocrypt.makeEncryptionContext(r(e),a)}catch(e){return void s(e,null)}c.id=this._contextCounter++,c.ns=e,c.document=t;new o(Object.assign({bson:i},n)).execute(this,c,s)}decrypt(e,t,n){"function"==typeof t&&null==n&&(n=t,t={});const r=this._bson,s=Buffer.isBuffer(e)?e:r.serialize(e,t);let i;try{i=this._mongocrypt.makeDecryptionContext(s)}catch(e){return void n(e,null)}i.id=this._contextCounter++;new o(Object.assign({bson:r},t)).execute(this,i,n)}}}}},function(e,t,n){var r=n(39).sep||"/";e.exports=function(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7))throw new TypeError("must pass in a file:// URI to convert to a file path");var t=decodeURI(e.substring(7)),n=t.indexOf("/"),o=t.substring(0,n),s=t.substring(n+1);"localhost"==o&&(o="");o&&(o=r+r+o);s=s.replace(/^(.+)\|/,"$1:"),"\\"==r&&(s=s.replace(/\//g,"\\"));/^.+\:/.test(s)||(s=r+s);return o+s}},function(e,t,n){"use strict";const r=n(222).spawn;e.exports={MongocryptdManager:class{constructor(e){(e=e||{}).mongocryptdURI?this.uri=e.mongocryptdURI:this.uri="mongodb://localhost:27020/?serverSelectionTimeoutMS=1000",this.bypassSpawn=!!e.mongocryptdBypassSpawn,this.spawnPath=e.mongocryptdSpawnPath||"",this.spawnArgs=[],Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter(e=>"string"==typeof e).every(e=>e.indexOf("--idleShutdownTimeoutSecs")<0)&&this.spawnArgs.push("--idleShutdownTimeoutSecs",60)}spawn(e){const t=this.spawnPath||"mongocryptd";this._child=r(t,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",()=>{}),this._child.unref(),process.nextTick(e)}}}},function(e,t){e.exports=require("child_process")},function(e,t,n){"use strict";e.exports=function(e){const t=n(128)("mongocrypt"),r=n(67),o=r.databaseNamespace,s=r.collectionNamespace,i=r.promiseOrCallback,a=e.stateMachine.StateMachine,c=n(129);return{ClientEncryption:class{constructor(e,n){if(this._client=e,this._bson=n.bson||e.topology.bson,null==n.keyVaultNamespace)throw new TypeError("Missing required option `keyVaultNamespace`");Object.assign(n,{cryptoCallbacks:c}),this._keyVaultNamespace=n.keyVaultNamespace,this._keyVaultClient=n.keyVaultClient||e,this._mongoCrypt=new t.MongoCrypt(n)}createDataKey(e,t,n){"function"==typeof t&&(n=t,t={});const r=this._bson;t=function(e,t){if((t=Object.assign({},t)).keyAltNames){if(!Array.isArray(t.keyAltNames))throw new TypeError(`Option "keyAltNames" must be an array of string, but was of type ${typeof t.keyAltNames}.`);const n=[];for(let r=0;r{u.execute(this,c,(t,n)=>{if(t)return void e(t,null);const r=o(this._keyVaultNamespace),i=s(this._keyVaultNamespace);this._keyVaultClient.db(r).collection(i).insertOne(n,{w:"majority"},(t,n)=>{t?e(t,null):e(null,n.insertedId)})})})}encrypt(e,t,n){const r=this._bson,o=r.serialize({v:e}),s=Object.assign({},t);if(t.keyId&&(s.keyId=t.keyId.buffer),t.keyAltName){const e=t.keyAltName;if(t.keyId)throw new TypeError('"options" cannot contain both "keyId" and "keyAltName"');const n=typeof e;if("string"!==n)throw new TypeError('"options.keyAltName" must be of type string, but was of type '+n);s.keyAltName=r.serialize({keyAltName:e})}const c=new a({bson:r}),u=this._mongoCrypt.makeExplicitEncryptionContext(o,s);return i(n,e=>{c.execute(this,u,(t,n)=>{t?e(t,null):e(null,n.v)})})}decrypt(e,t){const n=this._bson,r=n.serialize({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(r),s=new a({bson:n});return i(t,e=>{s.execute(this,o,(t,n)=>{t?e(t,null):e(null,n.v)})})}}}}},function(e,t,n){"use strict";const r=n(130),o=n(1).BSON.ObjectID,s=n(1).ReadPreference,i=n(16).Buffer,a=n(40),c=n(5).format,u=n(5),l=n(1).MongoError,p=u.inherits,h=n(24).Duplex,f=n(0).shallowClone,d=n(0).executeLegacyOperation,m=n(5).deprecate;const y=m(()=>{},"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var g=function e(t,n,i,a,c){if(y(),!(this instanceof e))return new e(t,n,i,a,c);this.db=t,void 0===c&&(c={}),void 0===a?(a=i,i=void 0):"object"==typeof a&&(c=a,a=i,i=void 0),n&&"ObjectID"===n._bsontype?(this.referenceBy=1,this.fileId=n,this.filename=i):void 0===i?(this.referenceBy=0,this.filename=n,null!=a.indexOf("w")&&(this.fileId=new o)):(this.referenceBy=1,this.fileId=n,this.filename=i),this.mode=null==a?"r":a,this.options=c||{},this.isOpen=!1,this.root=null==this.options.root?e.DEFAULT_ROOT_COLLECTION:this.options.root,this.position=0,this.readPreference=this.options.readPreference||t.options.readPreference||s.primary,this.writeConcern=z(t,this.options),this.internalChunkSize=null==this.options.chunkSize?r.DEFAULT_CHUNK_SIZE:this.options.chunkSize;var u=this.options.promiseLibrary||Promise;this.promiseLibrary=u,Object.defineProperty(this,"chunkSize",{enumerable:!0,get:function(){return this.internalChunkSize},set:function(e){"w"!==this.mode[0]||0!==this.position||null!=this.uploadDate?this.internalChunkSize=this.internalChunkSize:this.internalChunkSize=e}}),Object.defineProperty(this,"md5",{enumerable:!0,get:function(){return this.internalMd5}}),Object.defineProperty(this,"chunkNumber",{enumerable:!0,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};g.prototype.open=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"w"!==this.mode&&"w+"!==this.mode&&"r"!==this.mode)throw l.create({message:"Illegal mode "+this.mode,driver:!0});return d(this.db.s.topology,b,[this,e,t],{skipSessions:!0})};var b=function(e,t,n){var r=z(e.db,e.options);"w"===e.mode||"w+"===e.mode?e.collection().ensureIndex([["filename",1]],r,(function(){var t=e.chunkCollection(),o=f(r);o.unique=!0,t.ensureIndex([["files_id",1],["n",1]],o,(function(){x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))}))})):x(e,r,(function(t,r){if(t)return n(t);e.isOpen=!0,n(t,r)}))};g.prototype.eof=function(){return this.position===this.length},g.prototype.getc=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,S,[this,e,t],{skipSessions:!0})};var S=function(e,t,n){e.eof()?n(null,null):e.currentChunk.eof()?I(e,e.currentChunk.chunkNumber+1,(function(t,r){e.currentChunk=r,e.position=e.position+1,n(t,e.currentChunk.getc())})):(e.position=e.position+1,n(null,e.currentChunk.getc()))};g.prototype.puts=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t||{};var r=null==e.match(/\n$/)?e+"\n":e;return d(this.db.s.topology,this.write.bind(this),[r,t,n],{skipSessions:!0})},g.prototype.stream=function(){return new F(this)},g.prototype.write=function(e,t,n,r){return"function"==typeof n&&(r=n,n={}),n=n||{},d(this.db.s.topology,j,[this,e,t,n,r],{skipSessions:!0})},g.prototype.destroy=function(){this.writable&&(this.readable=!1,this.writable&&(this.writable=!1,this._q.length=0,this.emit("close")))},g.prototype.writeFile=function(e,t,n){return"function"==typeof t&&(n=t,t={}),t=t||{},d(this.db.s.topology,v,[this,e,t,n],{skipSessions:!0})};var v=function(e,t,n,o){"string"!=typeof t?e.open((function(e,n){if(e)return o(e,n);a.fstat(t,(function(e,s){if(e)return o(e,n);var c=0,u=0,l=function(){var e=i.alloc(n.chunkSize);a.read(t,e,0,e.length,c,(function(e,i,p){if(e)return o(e,n);c+=i,new r(n,{n:u++},n.writeConcern).write(p.slice(0,i),(function(e,r){if(e)return o(e,n);r.save({},(function(e){return e?o(e,n):(n.position=n.position+i,n.currentChunk=r,c>=s.size?void a.close(t,(function(e){if(e)return o(e);n.close((function(e){return o(e||null,n)}))})):process.nextTick(l))}))}))}))};process.nextTick(l)}))})):a.open(t,"r",(function(t,n){if(t)return o(t);e.writeFile(n,o)}))};g.prototype.close=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,w,[this,e,t],{skipSessions:!0})};var w=function(e,t,n){"w"===e.mode[0]?(t=Object.assign({},e.writeConcern,t),null!=e.currentChunk&&e.currentChunk.position>0?e.currentChunk.save({},(function(r){if(r&&"function"==typeof n)return n(r);e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);null!=e.uploadDate||(e.uploadDate=new Date),N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))})):e.collection((function(r,o){if(r&&"function"==typeof n)return n(r);e.uploadDate=new Date,N(e,(function(e,r){if(e){if("function"==typeof n)return n(e);throw e}o.save(r,t,(function(e){"function"==typeof n&&n(e,r)}))}))}))):"r"===e.mode[0]?"function"==typeof n&&n(null,null):"function"==typeof n&&n(l.create({message:c("Illegal mode %s",e.mode),driver:!0}))};g.prototype.chunkCollection=function(e){return"function"==typeof e?this.db.collection(this.root+".chunks",e):this.db.collection(this.root+".chunks")},g.prototype.unlink=function(e,t){return"function"==typeof e&&(t=e,e={}),e=e||{},d(this.db.s.topology,_,[this,e,t],{skipSessions:!0})};var _=function(e,t,n){M(e,(function(t){if(null!==t)return t.message="at deleteChunks: "+t.message,n(t);e.collection((function(t,r){if(null!==t)return t.message="at collection: "+t.message,n(t);r.remove({_id:e.fileId},e.writeConcern,(function(t){n(t,e)}))}))}))};g.prototype.collection=function(e){return"function"==typeof e&&this.db.collection(this.root+".files",e),this.db.collection(this.root+".files")},g.prototype.readlines=function(e,t,n){var r=Array.prototype.slice.call(arguments,0);return n="function"==typeof r[r.length-1]?r.pop():void 0,e=(e=r.length?r.shift():"\n")||"\n",t=r.length?r.shift():{},d(this.db.s.topology,O,[this,e,t,n],{skipSessions:!0})};var O=function(e,t,n,r){e.read((function(e,n){if(e)return r(e);var o=n.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var c=e.currentChunk.readSlice(s-a._index);return c.copy(a,a._index),e.position=e.position+a.length,0===s&&0===a.length?o(l.create({message:"File does not exist",driver:!0}),null):o(null,a)}(c=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position)).copy(a,a._index),a._index+=c.length,I(e,e.currentChunk.chunkNumber+1,(function(n,r){if(n)return o(n);r.length()>0?(e.currentChunk=r,e.read(t,a,o)):a._index>0?o(null,a):o(l.create({message:"no chunks found for file, possibly corrupt",driver:!0}),null)}))};g.prototype.tell=function(e){var t=this;return"function"==typeof e?e(null,this.position):new t.promiseLibrary((function(e){e(t.position)}))},g.prototype.seek=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,1);return r="function"==typeof o[o.length-1]?o.pop():void 0,t=o.length?o.shift():null,n=o.length?o.shift():{},d(this.db.s.topology,C,[this,e,t,n,r],{skipSessions:!0})};var C=function(e,t,n,r,o){if("r"!==e.mode)return o(l.create({message:"seek is only supported for mode r",driver:!0}));var s=null==n?g.IO_SEEK_SET:n,i=t,a=0;a=s===g.IO_SEEK_CUR?e.position+i:s===g.IO_SEEK_END?e.length+i:i;var c=Math.floor(a/e.chunkSize);I(e,c,(function(t,n){return t?o(t,null):null==n?o(new Error("no chunk found")):(e.currentChunk=n,e.position=a,e.currentChunk.position=e.position%e.chunkSize,void o(t,e))}))},x=function(e,t,n){var s=e.collection(),i=1===e.referenceBy?{_id:e.fileId}:{filename:e.filename};function a(e){a.err||n(a.err=e)}i=null==e.fileId&&null==e.filename?null:i,t.readPreference=e.readPreference,null!=i?s.findOne(i,t,(function(s,i){if(s)return a(s);if(null!=i)e.fileId=i._id,e.filename="r"===e.mode||void 0===e.filename?i.filename:e.filename,e.contentType=i.contentType,e.internalChunkSize=i.chunkSize,e.uploadDate=i.uploadDate,e.aliases=i.aliases,e.length=i.length,e.metadata=i.metadata,e.internalMd5=i.md5;else{if("r"===e.mode){e.length=0;var u="ObjectID"===e.fileId._bsontype?e.fileId.toHexString():e.fileId;return a(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?u:e.filename),driver:!0}))}e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0}"r"===e.mode?I(e,0,t,(function(t,r){if(t)return a(t);e.currentChunk=r,e.position=0,n(null,e)})):"w"===e.mode&&i?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w"===e.mode?(e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)}))})):(e.fileId=null==e.fileId?new o:e.fileId,e.contentType=g.DEFAULT_CONTENT_TYPE,e.internalChunkSize=null==e.internalChunkSize?r.DEFAULT_CHUNK_SIZE:e.internalChunkSize,e.length=0,"w"===e.mode?M(e,t,(function(t){if(t)return a(t);e.currentChunk=new r(e,{n:0},e.writeConcern),e.contentType=null==e.options.content_type?e.contentType:e.options.content_type,e.internalChunkSize=null==e.options.chunk_size?e.internalChunkSize:e.options.chunk_size,e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=0,n(null,e)})):"w+"===e.mode&&I(e,k(e),t,(function(t,o){if(t)return a(t);e.currentChunk=null==o?new r(e,{n:0},e.writeConcern):o,e.currentChunk.position=e.currentChunk.data.length(),e.metadata=null==e.options.metadata?e.metadata:e.options.metadata,e.aliases=null==e.options.aliases?e.aliases:e.options.aliases,e.position=e.length,n(null,e)})))},A=function(e,t,n,o){"function"==typeof n&&(o=n,n=null);var s="boolean"==typeof n&&n;if("w"!==e.mode)o(l.create({message:c("file with id %s not opened for writing",1===e.referenceBy?e.referenceBy:e.filename),driver:!0}),null);else{if(!(e.currentChunk.position+t.length>=e.chunkSize))return e.position=e.position+t.length,e.currentChunk.write(t),s?e.close((function(t){o(t,e)})):o(null,e);for(var i=e.currentChunk.chunkNumber,a=e.chunkSize-e.currentChunk.position,u=t.slice(0,a),p=t.slice(a),h=[e.currentChunk.write(u)];p.length>=e.chunkSize;){var f=new r(e,{n:i+1},e.writeConcern);u=p.slice(0,e.chunkSize),p=p.slice(e.chunkSize),i+=1,f.write(u),h.push(f)}e.currentChunk=new r(e,{n:i+1},e.writeConcern),p.length>0&&e.currentChunk.write(p),e.position=e.position+t.length;for(var d=h.length,m=0;m=t.length?s("offset larger than size of file",null):n&&n>t.length?s("length is larger than the size of the file",null):r&&n&&r+n>t.length?s("offset and length is larger than the size of the file",null):void(null!=r?t.seek(r,(function(e,t){if(e)return s(e);t.read(n,s)})):t.read(n,s))}))};g.readlines=function(e,t,n,r,o){var s=Array.prototype.slice.call(arguments,2);return o="function"==typeof s[s.length-1]?s.pop():void 0,n=s.length?s.shift():null,r=(r=s.length?s.shift():null)||{},d(e.s.topology,P,[e,t,n,r,o],{skipSessions:!0})};var P=function(e,t,n,r,o){var s=null==n?"\n":n;new g(e,t,"r",r).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};g.unlink=function(e,t,n,r){var o=Array.prototype.slice.call(arguments,2);return r="function"==typeof o[o.length-1]?o.pop():void 0,n=(n=o.length?o.shift():{})||{},d(e.s.topology,L,[this,e,t,n,r],{skipSessions:!0})};var L=function(e,t,n,r,o){var s=z(t,r);if(n.constructor===Array)for(var i=0,a=0;ae.totalBytesToRead&&(e.totalBytesToRead=e.totalBytesToRead-n._index,e.push(n.slice(0,n._index))),void(e.totalBytesToRead<=0&&(e.endCalled=!0)))}))},n=e.gs.length=0?(n={uploadDate:1},r=t.revision):r=-t.revision-1);var s={filename:e};return t={sort:n,skip:r,start:t&&t.start,end:t&&t.end},new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)},p.prototype.rename=function(e,t,n){return u(this.s.db.s.topology,f,[this,e,t,n],{skipSessions:!0})},p.prototype.drop=function(e){return u(this.s.db.s.topology,d,[this,e],{skipSessions:!0})},p.prototype.getLogger=function(){return this.s.db.s.logger}},function(e,t,n){"use strict";var r=n(24),o=n(5);function s(e,t,n,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:!1,expectedEnd:0,file:null,options:s,readPreference:n},r.Readable.call(this)}function i(e){if(e.s.init)throw new Error("You cannot change options after the stream has enteredflowing mode!")}function a(e,t){e.emit("error",t)}e.exports=s,o.inherits(s,r.Readable),s.prototype._read=function(){var e=this;this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(!function(e){var t={};e.s.readPreference&&(t.readPreference=e.s.readPreference);e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort);e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);e.s.files.findOne(e.s.filter,t,(function(t,n){if(t)return a(e,t);if(!n){var r=e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename,o=new Error("FileNotFound: file "+r+" was not found");return o.code="ENOENT",a(e,o)}if(n.length<=0)e.push(null);else if(e.destroyed)e.emit("close");else{try{e.s.bytesToSkip=function(e,t,n){if(n&&null!=n.start){if(n.start>t.length)throw new Error("Stream start ("+n.start+") must not be more than the length of the file ("+t.length+")");if(n.start<0)throw new Error("Stream start ("+n.start+") must not be negative");if(null!=n.end&&n.end0&&(s.n={$gte:i})}e.s.cursor=e.s.chunks.find(s).sort({n:1}),e.s.readPreference&&e.s.cursor.setReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(n.length/n.chunkSize),e.s.file=n;try{e.s.bytesToTrim=function(e,t,n,r){if(r&&null!=r.end){if(r.end>t.length)throw new Error("Stream end ("+r.end+") must not be more than the length of the file ("+t.length+")");if(r.start<0)throw new Error("Stream end ("+r.end+") must not be negative");var o=null!=r.start?Math.floor(r.start/t.chunkSize):0;return n.limit(Math.ceil(r.end/t.chunkSize)-o),e.s.expectedEnd=Math.ceil(r.end/t.chunkSize),Math.ceil(r.end/t.chunkSize)*t.chunkSize-r.end}}(e,n,e.s.cursor,e.s.options)}catch(t){return a(e,t)}e.emit("file",n)}}))}(e),e.s.init=!0);e.once("file",(function(){t()}))}(e,(function(){!function(e){if(e.destroyed)return;e.s.cursor.next((function(t,n){if(e.destroyed)return;if(t)return a(e,t);if(!n)return e.push(null),void process.nextTick(()=>{e.s.cursor.close((function(t){t?a(e,t):e.emit("close")}))});var r=e.s.file.length-e.s.bytesRead,o=e.s.expected++,s=Math.min(e.s.file.chunkSize,r);if(n.n>o){var i="ChunkIsMissing: Got unexpected n: "+n.n+", expected: "+o;return a(e,new Error(i))}if(n.n0;){var d=o.length-s;if(o.copy(e.bufToStore,e.pos,d,d+c),e.pos+=c,0===(i-=c)){e.md5&&e.md5.update(e.bufToStore);var m=l(e.id,e.n,a.from(e.bufToStore));if(++e.state.outstandingRequests,++p,y(e,r))return!1;e.chunks.insertOne(m,f(e),(function(t){if(t)return u(e,t);--e.state.outstandingRequests,--p||(e.emit("drain",m),r&&r(),h(e))})),i=e.chunkSizeBytes,e.pos=0,++e.n}s-=c,c=Math.min(i,s)}return!1}(r,e,t,n)}))},c.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");return"function"==typeof e?e(t):this.state.promiseLibrary.reject(t)}if(this.state.aborted)return t=new Error("Cannot call abort() on a stream twice"),"function"==typeof e?e(t):this.state.promiseLibrary.reject(t);this.state.aborted=!0,this.chunks.deleteMany({files_id:this.id},(function(t){"function"==typeof e&&e(t)}))},c.prototype.end=function(e,t,n){var r=this;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),y(this,n)||(this.state.streamEnd=!0,n&&this.once("finish",(function(e){n(null,e)})),e?this.write(e,t,(function(){m(r)})):d(this,(function(){m(r)})))}},function(e,t,n){var r,o; +/*! + * is.js 0.8.0 + * Author: Aras Atasaygin + */o=this,void 0===(r=function(){return o.is=function(){var e={VERSION:"0.8.0",not:{},all:{},any:{}},t=Object.prototype.toString,n=Array.prototype.slice,r=Object.prototype.hasOwnProperty;function o(e){return function(){return!e.apply(null,n.call(arguments))}}function s(e){return function(){for(var t=u(arguments),n=t.length,r=0;r":function(e,t){return e>t},">=":function(e,t){return e>=t}};function c(e,t){var n=t+"",r=+(n.match(/\d+/)||NaN),o=n.match(/^[<>]=?|/)[0];return a[o]?a[o](e,r):e==r||r!=r}function u(t){var r=n.call(t);return 1===r.length&&e.array(r[0])&&(r=r[0]),r}e.arguments=function(e){return"[object Arguments]"===t.call(e)||null!=e&&"object"==typeof e&&"callee"in e},e.array=Array.isArray||function(e){return"[object Array]"===t.call(e)},e.boolean=function(e){return!0===e||!1===e||"[object Boolean]"===t.call(e)},e.char=function(t){return e.string(t)&&1===t.length},e.date=function(e){return"[object Date]"===t.call(e)},e.domNode=function(t){return e.object(t)&&t.nodeType>0},e.error=function(e){return"[object Error]"===t.call(e)},e.function=function(e){return"[object Function]"===t.call(e)||"function"==typeof e},e.json=function(e){return"[object Object]"===t.call(e)},e.nan=function(e){return e!=e},e.null=function(e){return null===e},e.number=function(n){return e.not.nan(n)&&"[object Number]"===t.call(n)},e.object=function(e){return Object(e)===e},e.regexp=function(e){return"[object RegExp]"===t.call(e)},e.sameType=function(n,r){var o=t.call(n);return o===t.call(r)&&("[object Number]"!==o||!e.any.nan(n,r)||e.all.nan(n,r))},e.sameType.api=["not"],e.string=function(e){return"[object String]"===t.call(e)},e.undefined=function(e){return void 0===e},e.windowObject=function(e){return null!=e&&"object"==typeof e&&"setInterval"in e},e.empty=function(t){if(e.object(t)){var n=Object.getOwnPropertyNames(t).length;return!!(0===n||1===n&&e.array(t)||2===n&&e.arguments(t))}return""===t},e.existy=function(e){return null!=e},e.falsy=function(e){return!e},e.truthy=o(e.falsy),e.above=function(t,n){return e.all.number(t,n)&&t>n},e.above.api=["not"],e.decimal=function(t){return e.number(t)&&t%1!=0},e.equal=function(t,n){return e.all.number(t,n)?t===n&&1/t==1/n:e.all.string(t,n)||e.all.regexp(t,n)?""+t==""+n:!!e.all.boolean(t,n)&&t===n},e.equal.api=["not"],e.even=function(t){return e.number(t)&&t%2==0},e.finite=isFinite||function(t){return e.not.infinite(t)&&e.not.nan(t)},e.infinite=function(e){return e===1/0||e===-1/0},e.integer=function(t){return e.number(t)&&t%1==0},e.negative=function(t){return e.number(t)&&t<0},e.odd=function(t){return e.number(t)&&t%2==1},e.positive=function(t){return e.number(t)&&t>0},e.under=function(t,n){return e.all.number(t,n)&&tn&&t=0&&t.indexOf(n,r)===r},e.endWith.api=["not"],e.include=function(e,t){return e.indexOf(t)>-1},e.include.api=["not"],e.lowerCase=function(t){return e.string(t)&&t===t.toLowerCase()},e.palindrome=function(t){if(e.not.string(t))return!1;for(var n=(t=t.replace(/[^a-zA-Z0-9]+/g,"").toLowerCase()).length-1,r=0,o=Math.floor(n/2);r<=o;r++)if(t.charAt(r)!==t.charAt(n-r))return!1;return!0},e.space=function(t){if(e.not.char(t))return!1;var n=t.charCodeAt(0);return n>8&&n<14||32===n},e.startWith=function(t,n){return e.string(t)&&0===t.indexOf(n)},e.startWith.api=["not"],e.upperCase=function(t){return e.string(t)&&t===t.toUpperCase()};var f=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["january","february","march","april","may","june","july","august","september","october","november","december"];e.day=function(t,n){return e.date(t)&&n.toLowerCase()===f[t.getDay()]},e.day.api=["not"],e.dayLightSavingTime=function(e){var t=new Date(e.getFullYear(),0,1),n=new Date(e.getFullYear(),6,1),r=Math.max(t.getTimezoneOffset(),n.getTimezoneOffset());return e.getTimezoneOffset()n.getTime()},e.inDateRange=function(t,n,r){if(e.not.date(t)||e.not.date(n)||e.not.date(r))return!1;var o=t.getTime();return o>n.getTime()&&on)return!1;return o===n},e.propertyCount.api=["not"],e.propertyDefined=function(t,n){return e.object(t)&&e.string(n)&&n in t},e.propertyDefined.api=["not"],e.inArray=function(t,n){if(e.not.array(n))return!1;for(var r=0;r="],o=1;o>>0]},i=1;i<624;i++)s.x[i]=(t=1812433253,n=s.x[i-1]^s.x[i-1]>>>30,r=void 0,o=void 0,(((t>>>16)*(o=65535&n)+(r=65535&t)*(n>>>16)<<16)+r*o>>>0)+i);return s},t.randNext=function(e){var t=(e.i+1)%624,n=e.x[e.i]&o|e.x[t]&s,i={i:t,x:r(e.x,[e.x[(e.i+397)%624]^n>>>1^(0==(1&n)?0:2567483615)])},a=i.x[i.i];return a^=a>>>11,a^=a<<7&2636928640,a^=a<<15&4022730752,[(a^=a>>>18)>>>0,i]},t.randRange=function(e,n,r){var o=n-e;if(!(04294967296-(c-(c%=o));){var l=t.randNext(u);c=l[0],u=l[1]}return[c+e,u]}},function(e,t,n){"use strict"; +/*! + * shallow-clone + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */const r=Symbol.prototype.valueOf,o=n(131);e.exports=function(e,t){switch(o(e)){case"array":return e.slice();case"object":return Object.assign({},e);case"date":return new e.constructor(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return function(e){const t=e.length,n=Buffer.allocUnsafe?Buffer.allocUnsafe(t):Buffer.from(t);return e.copy(n),n}(e);case"symbol":return function(e){return r?Object(r.call(e)):{}}(e);case"arraybuffer":return function(e){const t=new e.constructor(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t}(e);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return function(e,t){return new e.constructor(e.buffer,e.byteOffset,e.length)}(e);case"regexp":return function(e){const t=void 0!==e.flags?e.flags:/\w+$/.exec(e)||void 0,n=new e.constructor(e.source,t);return n.lastIndex=e.lastIndex,n}(e);case"error":return Object.create(e);default:return e}}},function(e,t,n){"use strict"; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */var r=n(232);function o(e){return!0===r(e)&&"[object Object]"===Object.prototype.toString.call(e)}e.exports=function(e){var t,n;return!1!==o(e)&&("function"==typeof(t=e.constructor)&&(!1!==o(n=t.prototype)&&!1!==n.hasOwnProperty("isPrototypeOf")))}},function(e,t,n){"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},function(e,t,n){"use strict";e.exports=(e,t)=>{let n;return function r(){const o=Math.floor(Math.random()*(t-e+1)+e);return n=o===n&&e!==t?r():o,n}}},,function(e,t,n){"use strict";n.r(t);var r=n(18);console.log(Object(r.a)())}]); \ No newline at end of file diff --git a/external-scripts/generate-flights.ts b/external-scripts/generate-flights.ts index 910227a..c3a2284 100644 --- a/external-scripts/generate-flights.ts +++ b/external-scripts/generate-flights.ts @@ -1,4 +1,5 @@ +import { getEnv } from 'universe/backend/env' import { generateFlights } from 'universe/backend' -// eslint-disable-next-line no-console console.log(generateFlights); +console.log(getEnv); diff --git a/external-scripts/prune-logs.ts b/external-scripts/prune-logs.ts index 9b50a1e..3314f0c 100644 --- a/external-scripts/prune-logs.ts +++ b/external-scripts/prune-logs.ts @@ -1,5 +1,3 @@ -import { generateFlights } from 'universe/backend' import { getEnv } from 'universe/backend/env' -// eslint-disable-next-line no-console -console.log(getEnv); +console.log(getEnv()); diff --git a/markov-arrivals.png b/markov-arrivals.png new file mode 100644 index 0000000000000000000000000000000000000000..9b2c7ef538f88c7393697d9d6e6719b9893f1cd7 GIT binary patch literal 36992 zcmaI7by$_n7dE;{k?t?RDKQ}s2#)+K*gFUW*$Vu2!9WL}tj;XXfImgP(X($9j50QsSsk)`^Eqt`I+V-Zsgnu4JTG&FT6bcbZl5r6H_KFAl!x*7_ zEXOAz>oPXW>KX;czD6~d`YD~lcmeP7rpByarEz;_3i@AJUl+zv5VLd0+r!>bI|QdX zagO%Z``b7v!T$+;l%W2>Dean#9DGXPEQrnzg+jA%d)i)trxPpWGyi>!8ifk+r4SRtr{M99 z-T(iWpVc-Z!C+~{nqMS|OCYEi0T_CmQuvUF59JGrPqV~3z`LDf3%*G)HHO1hbp*xl ziI^3L!wG}vL(8=T%e4c@Y3~Uxy*S%8v_G?X{#`JI?$`$yk-u!Dl7dYxi;?Dmd5d>j)ZUCO@{Zmfzjv#l%a2O zIe~z{ehi6#z^U19W_!RD*AjAcy(E z@^BIJs%grPlz>358!X*hQBApm@_r*&%$DzV;O#ff&U85#DpxsyN`{Ewtr&4cELEAK zAd^vT^pcw%e`E04nuHZ>JT$Z)tSsO5xdO4ATt?aM-@J@_KGC!FvI*yXmGy|XuM2K? zBSW_c4?4jNug5WaP1ScA)Du!i=_j16UtF(wiRmv9*2Q4yS#IBk~XiiyPAELMf( zKOm-F>No39^sIR&YV-I1`-sdX`Fzjpe33xq!3eRd4ZAl2`?Itc?-f1y3C`#^gz3R& z4#U&lCCq;f$vqaPb&CBPdBZ~Up#TLtI{JrI&IUKvR1#Qv8oMov0!LB*-$RQ+N;&b? z2x%iap9fE)ip$*=4Py2qw{)2B-Ff8nl;e<4#vz(y%uY*s=oS+|%Y-xW2I|!<$H|qL zxkrsxlcs2cnqif82$%4QfGtV)4maU71KWwDOolw{E)qaeINfOL?KccCd>zYk^h~;I z_asQBZb5l|XEt**+Q{{A37WBF4ST=hBH_QXLiee+Dl~K$U|6N+&o8#hSuTfq9CMH3 z?p?JFRKKV>Hosc!Ku!JojN|6RyF^#pEi}A@hi95>Ey1D@p116@;Zt{^&;zr2D)e?o#9lAU8g4yLwahFu1S37Y@&Os3kuV$CGzh+!cbsG!WCu zjh;a(XZcL4b`v*q780g!aNTT#*f760yXPI-uAEIj?20rWh-5raH!bEpkuMclP=={u z0jH{t&;1ai&>HDwgN6QUPNEIpuo|b`D8sLl+x>8{#ESpR{{B+i${5{*^WE>?%Ek_> zhi%)b&C|Pt1d|9ivd%1g{Bzuv-eBgDT_c?gGQ*736G7^)<#Rnx!fS$SN>mk|CeFcF z&V-|&8FKQ9S^24w_%O{9DNXi3j3DvHWfxk4)I>2KY-J2GLbq7Jsaq6Cui$SF$}lUe zPhDu6(xnc&3#Rel%UTj?yQUSUBgg#Ml?DDRRo*7~SRIR%0$*hp0l(Ml4s*Sxbkb^T zwGGO|Y<7aVD-J`Q#uQfXb^+;7)t=F3<+2c;$Gq{OV`O(Ox+zXr*0TM}i>i)8pCyjq z8pTZJXRnwH0<*ezTIBpN8chgkFTN@+47?fVHBUw_s^;q~guyPlz(^c5mYkS3Ey2>q zKMp)$Qo-Xwc(pfDoflj@*eD_*B5#S&x{L|JvzEP>dfzLHp*1cnj!r*?TA(8~hoLy| zB;JFj{+4t{@9cRPZk=v~T|H?^O{gS3>X+zf6K7|VuGI~T$3fEm0D}$4WHk6=&08J> z+y8WW&8Bx2Fl4kexhGsPy0|#9QGa~QZ z=y;X0=x4+1yzn%P!>xJb*N3mOPQsBesQ=iQ3N8Y?lTrjAZv>2B!DY`4v%k4NWowmiV((}uvM8$M~{_N}|d za_&t!H#7Gl*0%2hktzpN7{A>Rb#~^w)qpF7UtU*-Q8XF;F~ge_n8^AQ5y6+5q72n*dB2IIFdX$mH&UggmtcMS0`F^q-z z`@6QSe7BLB+j-AST;9?GHe*<=%`G9ZbihPFuz+x(_~-r4SHoZ z#|#)1l2CBc<1E7!);(C(b!s7#9pwYMLe6^RbblNf;5@@>-0B}6YF+JP zrI?8WMy8vPPhhZ;-)%1^@@&S7m@r7)#6~~>3!tCpQvb^o2FucIZ(BPyG&ar}VuwO4 zsL}be#D9LG_-$+uqOCCRRx-pNF7<#XNo>t-KD$7SiDqSEgAB3ary>I`HUijthv(`R zclFqIK{H>ExR{*W?W4|)&th=yCtXuXm{_!bWWF+aa4?8ty&D2HO*K>=lf!ztrd$#d zc#X}?@g$+4$pF&%c;6I0{Z@MDm@mx^w%Jw_sjaOIaT3OXkkilvP48MeMu2gFU|i3K zs@+#it)6T6<^pGhNSn~WSHFupmd`x6`T3_dK_ukEL!nZMeu0g1{JS=0~}g#*fSuf1oHT z#B&R5(5ze#cz3viI>e3hI8g-lN;aJaJK&zKa`EwnJ%9gF63hAnC5iJ#l(^dg^=qLa))mYVo+R zX^t-iVmSAvuq`V^{S22;Vi;U^DW~aUU!hiLVndcsuegMT|01?mjSIezIPQ!FRK$-2 zB};v{1AB+SkrHG5(UKEN?Bg+7 z4`l&!mRP9EY&Zyk)0DWWetTqJ2?bM#lfBT$km#GJ@nC6BlEkienV<&2*^q(bgW)Lkquv z=bc?^zCpS^**oqkzf71fWnw-kW9dw~&9?-G<_iNe;*v)D64l?TPoBnYb&QV6(aSH0 zJuy&I``l?{vm^ymMFX}73GZq3*Y#=Kapx(%bAA<<9aLf=syJR=SsC!I0M&2K6`w#2 z#K#GL!oI@^Y)eviNc-|@d|6L05w)eIC1S2EbRbJ;n9_WRX07UW+_h*Wxh`cuphFA+ zo9{J!0r3Mw{r^t+s1I04p;hIqN%q{teCsJb>TASMIXSt+nnQ9bDoca`gcA|^I`(s*|!{1QFgi_+P@|jD10dM^Ev)4h)3)_C-QN4}!tBBYD{)H1~?QerSkthVi2Y zays8l(Lmm^#B*3LRg{;vAqMUsxQHoOMVj}TWGh(vxQV_O164nOtzKuovU}W_rl_ch znKXh68|C!$)UL7dVHcp71el*ctg9s|E}_&-$uHD!xwBl;i`_E-(hAxwVLQN$-OY?12{iFe~eN}yOXIYs*H?`wGBucE&y;W zD!hEilJ+_a;odD|Mpco&%4LVDs;UBEP$UQjD)RqDPy-P-U95P8$G_K>iai$hwFAb5 z#v9Q2##UCIC@CpHAo^uwJUl%6*7yV}WPn&K2=q9Y8LrjHM_JNqwPXN#H6p;NjF}TZ zdh`e~7-xU;^eM@RLKc>Pn}MZ$O7c_S&Yp8@y0*1*6~BI= zs;oy-LbGm`l~uAxUojX2X$zOQDG{5ZhUo8v#l4@kBHi8Hg+M?s-PrgL%m>XvUsisX z#l%XC8#5Hln!yWceYg{=nAR50=-Js}fk-BNU}I;ON@#5TMoOUa41{b8s3Pk!?|oz; zym=9BSQ}jf?4ZI%TG7yesW<&39GZ}rsMX~cn(q(7j*YxZ*61%?z3KGy7VK;VMwAe5 zLfVn9kyhF|-xL^&OG^`8E3vb)x7*a#)~mr_%|ZT=TM4kS@a$fAY@cX=kt)XwE+h$v zxgGf~$IA8gRCU14=~^&iZb5JMjyT8_k`p%ReOi2--0Wf;)M2>5Ke!v}*J zNXifBHs-1-(8qf;_Y=WTk?ACBA5KNe@U)qUA?54D1S&kv7q-}0{1v@sTx0*Jp|PA$ zFm!&-jGQv7qSX(nd9@j3(N!{`ncdQ|s<^D|Y03~XBbaU*aX>3=SwF!I2N8o-zL8yIb~{8(xyOuSX>_i zzkt9K3}g_?cLNCts>yv<2^V4~)t3riEikWMt}DmBX~Fz)-C~`_lBQ&0ZH?onMfZ&{ z4|o?K)2*oDgk8idO*QP?{?Yv?3}dR!KYo#f-CZvliG*v2_PUhd&PkMy$1216Qt z`+ji4K~qc1zjPO0HnwX%EL7OfaH3FOaRLsNB~e$A?1R9NV$hIKPS*6RO?T8xU$8<3 zV`@rf?DDl^#_3%3u>!E=9i-y)Vi*NXXVIj}ArJl?K`p5y?tpFVh}MAy4=hR z-REIHMDH;BE%WkNw%jN$P8PGVyE}zaUR91YJv3_{*mG^&J%n zZ=T z-u;zUL|<{r_wf5dxIpW^W2J#Mop|WofBG; z^q~wIi$NH+S$SPbU^r@2e#Ej?MXw_(qgocn1)sF>HSzg$D-H6`1kjGZ)Qr$!zZz_<%&t0 z2H@RN{2>bgm?a%d4V2hc8xfi(ygu={xu4wrZ4rcbL9sjA_V%m>G=35isN4xMD0s7$ zZC{eahPY`D5(D`>>b60)#N=!h2PHdx z#M^`vdx{FK)q{i?2^c%;?7yGRlSQpL>%krBkM1v8>Bh&$A%3x}{`*PwLQRL>hdq?0 zro7FiAJt9B(E$fI2%TEeQc$$__VzZX%Y!_oQ})qBB12}&ku%wLT=09f&L10_9Y^hk z_;gpjaxt$MK%(at>qHvBU?NH^y|~}rVu4;=oZHU6uz$!3_FPjF{Duhy0&-%o%GPmE zo5>d=pULNJ_URFu-l;H9Rhe*x2t4A4#C)ItF9p9|3Wt<51yskO=SO=^D#a5@Pt5@e z#zq0r_Ep|EWYEt|+%+mRwBZp7)mhGm#O6;Uw3XTilYxmWdP|Oq^)ga%r|H$F<@|zz znzTNQAl!EdSxqF~CT!l7ys(PrrZ+gy6JajwU38@VYrWMFH90xypoxWw{5>trdUltH zK*a={u0g-0aITGtLO=Ct@rZ~h?hFhGO|NGzN%Wqcut!7bz1^Zc?qBP)kZP+b-4aS{ zbZ#D=@wjOwXx8R(4D%UdE8EIbB+mQ8JM*Dk@%4)~_Se0iv=>r7C%NX8?+I!eesIoIgJhaiM^K0>@>>OJiv zaqjg_GG#)N5!>~M%dU{Qa!lmK-t}FNO$nXUw#9fu0e2a_F~@M5WzFYmqGW~T1qZV5 zjoe{Y^3T#wO3@jiJ5TnEvRgJ{8E$KP$Q&`0L|j4rvt>3pivd zo5uGxTHee$2CE*)lFwH=*Y@nta~}~@Q{y}Z^>MI$2>V2shic)^6{B3gvYz*sYv!0#SI`r(n$x2`LZ8vY?$?3(Ugo2L zXSxI;YULItX*74{Uw)&%cNki1^+pZw+5`F5uk1q+GYG!%@L0` zZ~QSRxKv<$y&LhYZ>s$KC3lT;^%DkPO^5UAKg}I~Q#)PQi%Briii?YXsIs(kVGj-s z8QIw#{qKdKFmN4}`zf?%4ZIKJN7KV{*(z?L>4g`Kj07h9Shx}K7jIDfR8qd!m7d#u zR&TV<~o@h|gr`y3?c-y4aQh^dR!!iW}^+;D7+31BfI~jq;=^taSGk10kPhdAAj5 z9RtBE=9z4U-Rw$jFEG9!OQBlruHZ)kRMC~1wR%jdz0Fg1uq(;&!NrEFD|c*c?1?jH zkV70A8fK?|8`vmsY}B#ut)i{a-0ObQ!UnTA;3wv(}k2PLSs0s5+Kk%(8w zRArG$D0(2$a+*DEeuGOUGKx(4SZVv@?asG_@aK(Z>SY;V86c4dX#fT?5SHY?kFLoD zhI7(C{Fj=12IaeRB^`s`#udqM>ny)*R;fKP@rx1zcp)e&%0<)0!^bKNr3Cz(|p)cqyw zUVXa`W*hka{kz|!g)G?J_V#m&eX6t}GmxVgRm~Ra6aDHx(qZ_mhI4qbs4MU*L6a@G zq=X&f#~hB(qT}w~PmqD^raK38I>w9R>FEiu0$AQ(^2d%SpA^0gH7VL)*CW6B*?m14 z8k+ddWVQjf)v#xX&E^C6U-yHYyIw<4P3^Zaw|R0f_}9$-x#jdU51TOjmr=J-kXo_+ z)sKXqqa{NMnc0 zRvgsm4!)rw9iA>(r_XL~nh6pA-FIQ*qk!dfZvZDG*ZaK|ZRe@Rdc9pCbu2keQ(jDIv1y({=^C-_BoxHx9{;)Yv9WS|^$ih#=OV-Ns}o14Y98hrNMSUskJ^(v~X zoeM&56g}%fFHsF}f!Onm5e;_M$-TvDbKYz|r z&2S1$Pg^^n%lOmZT`=?k;qS)e=q|3Vtm#x#RDlfgita;^kvPB~AZB8JfVL;K2LUK} z#g=&Ic}PeIbG*WI)ZD%c5Mu(jXS|9sg48ehQ_$L=2Y`#H!HM&zs+DLjH&ZbFC{0K{ zx$^p+l47Fw7N|VXO5LFV4nQK%M?+5TH@9!IWeF?}%2@e@m=JObicdSYf&ezQ;3Y(r zvsRPVqD)Lol-JtZPL!ZVwIQ~co0q3$5e`bS;o!hJ&d*)C)-vB>xHL8!m4V%c4-F|o z49}3kR1{z;k7v)G^}eTxg2;o&)>}{010H0NXCjEo1>jD3Z+TQ*o z^h%Eb1KG^X?BLEzO^pCIWT3NTz9taV|3C$zAujjR%?L&na|)uI!^+}!?enVrf$5&{?j zz2}@}`XbCt)MvlWi2Q=K@=MR!%>4XkBXW@0AX*bwUKgJ@KxWenTtj2bnFiGENJfIB zGd-=V2*O~1*RiDV>E#JY$;eh5>JM&3K`jUrGP6r70pnNHHFg=-YkbPz-?xTks{r^# zbOnII&Wu&f4R1VPBqPA3mH_{-?6GjT*~gEEzu?K>vzZx5Xe~VM>|OYg zFRO~is51>f70C!1G7^Z4Iuh^4d4Y>T69*Z?TUS!2v`eWqQG@87?#EftOd zA)}!|dy&-C$_g7$&V|i0@WLwaLOI~~jg5^YBRJUDh9HEikGy6e1e5p~kwXUSZEL;J z!N4M5vmW8HHLU{m{4Qfq1DP*LcXe|My}R?anFAU^FT_7mc>sz5O6HlWD^iyTU|v4OmU1-2qli=h` zOsll^_V+PuzfOUO+-+u!f!GNdvh2eIBy2q(QW}OogszWzr92_83ZkwN{ zCL;stKpD7A4XB_X+_4`;gPn~{6904Ig@K+fK4uWe`NqE0AQp{+LRGymHKktvaj!5b zi2?+y!V9La@>W(>-vp*VY#^2_3zn=7JXBCjti;X6+#CZD5Sul~$UsA&W7~W(JX| z{qRDdIt|R67T_PLy>od(bbiN!Ms78SDPtb!N}FM_P?h! zH8uDVT@VOv2uegmgmZiz;!+4B*dk%QE-o+@$%vY^DJVw+Y=$FpRp6u`)7tp&@Lq#q zPT^Vf)VQ5oUo7FMQgt=G^uYJMy=e*y|EmuodQ6q)z_8AgU~h#W5XQ&HJIv-60SDw9 zl8fjvp85M183Ke02uPP+E$aWdDk6g$PqkgLZ^7wN%Y2*P^kFu@6iz#)3awfQ%bFi1uwe$V zSPv+Wi?|UuqK%|D&XS&yoGe|T*~DuQ*)<0o+y=0~LGk}8Z)%;|T;wqE49>%{O^5n& z;B8kHV5VA7%5`;kuj$yh0GbLLR~Cq@HZ^tKiw_t`1lU^#&`~t47)wY+k*OBwTFx6F zj4UO{FI$^cXfauCM&6yXMjC+z;Pl_4t#n`ro9d3_+)p6W06qz6^Y{TKiu}EltC|QP z0rakv$~Q|mNPPeexTi$DWme_b14$I@0_;Wrq}M?8kaTLZ#7k$sZ5tiMXOQpM+hg+* zH=xo66^@BU@P1I&`k#EV+Xk^kP)G5odxJ$|9@6a$a0e z7{0b<@+$80TV~XZk&ya&q0p?E+ynsCGf;&o%zw*l_~8Ru&b#eD$GRLL=De7oPwNv1v39j-nKF~%0$v?<>DTDppM590lHf1On&?kZnHXN!ea=uit=UtH$?Td#44kc71)FV*+wk(Cq~A2RP-3=qYyX z9z9S7-01ws5Fn*NLsU;V;T1#78zv+OZS*6~mP=@pzAcru9N6Fz`3wg5?##jhyKm_y zO3-I{%SMXyJ!sCr>sVH^WXgpv7OcFCyZo#kLtJm86KwRh%7Afnd_L+U5t=UaJCyG z%1TQ8lh~$O-JVM~`aoyZRwaS`I|cifjOeoSIXh!atQ{|l9lGP8qoeuFV1|45$>?@E(uK@lD z&w@bMNU^}`xWMS7q@;6xgd5v{nFGPef=&^r#h+Y>0?QkcqeI&ET{;ghOdK2tLHE_# z<~ca)$w2>-9&jxHhzU>@PfbrxxX>m-MFN#Gr92`~-~|l(e+EYQmxKT@3+7L_P=BvR z0zurD;N?XH2m{OfFRV{|AfNI0eYF|@@-jPGRRAFk$+yW3F%yE1Im&?-onumF^~fc)C8O`joPfK-@jrG;I(Vz-|#6?C5#<+>nVu0Fv*ke+=X8=7& z*j9SofVlVfSC*F{0F@g-Xn+^Mof42m#xWQf86nx!HV&0Af|Gk`Xt)b4EHnnmSnR8x zs~yNv_{(;J;Id2ai}wIQVxPf`3}59zI9$2By!_J8Z+(2-eJKC;SR6bi ziF^t4uf2ll0U#kBNc?5=lb{jw-NPdEVpSR7IcEV5Fch8WyLgZyK z@j-kR`i~0nxXPVl0BMBa(HZ;tw$2xsRcjMqqYpHjSF)M7xYSTD0vqOEaF;v#oiWEd;S5_7n*u{T|mFN6X|LtAW%>=soi2@ zY>W&7q}~wl)+~NwLrX-Ny0I|=q?rAG>E5QW>DP)iP4)kZ@~48C&ZXi z_@6z?roO?EtN1%@C%o}fRY>c4gUk+!yXY&p)>*r{nf7u}YZh61rtT--s z3jz$xd3UZ&osASACv@q$WU1klNBnME8MLxC-^l_+2++GbN29fNeAx`TFkT0a8J*qT zFHI=HH({!>2Iw`Qu(EVJv}Dy=23gKu{pj-bh#{^^siRX%qJNvau-Jm+r`4?0HU`{Ga zXf=0tcgb)Aw-q$6RiccxnHdmg_g&U{d~bV>SMYr6HoZZbhGY5ke{Uw40nt|9_wFot z8Z_pZ!{05^?Kl0LP@HpZx;vjs#B3k}K|Ww^zojBkaoQOKHKUIoAL*CX zmaRwSw98lva*Tb=Z&?^uY zyWoZp5;&7Eq7d^$2Y%0mT-CXAP@y>GH1AuYGCJ1MZ&UCs8DP7?dr||VWoQ?)4bb=# z2ZBDPyQ8P1q^Om-Uu`7XgE9cXJVcTuzJsjgD2S?v0%WA^Ysb1G>7wG&VEsXZXCyym z#(8RQkbxufl?GS7`R$d_YE)Obl!I4BCvv;EF(S*lj0wSQrC1itP7`1#BJp=ZEyw#V zmUH#KO#+LU(9g4u-Fm;M4IQ$!w#GNI+YlwNh+cAPnFZH@T;X8(Rn>=rzk1O8l;2KH6hoMy`+J3NaGT^ z`aOo`9T7cMvzNXL1d9`CKmwWV4r3X!CRcB(vyGpN%a2Uo4XLc@M4>ZXNJ1idWo6}c z&xCZQnI;kA<11BU^+uckx6_&@0Mg3!&Y-l+2DtPG#8~_F+7_n$nw7> z?-dy)WUD*IqZp*8{U)9Q=SM1LFzV0`hL*^$K?p^WQ^yrYTt%4)@* zV??72Z_cJ!7U49MFL%~2|8Vyix3|SmEY1h&+RMOHYjp>2yHdn?Wn_!g^|f`QHQuL( zlt-)-O+Wh!H{LAND7kb~+jGZf%SEcbe)Ya{sMYCa^yjAEqy&o3;j_bwznu3d%YhGd z1w|ij_{*P%2Y?bCf~gt-m)##nn}FLRKCP`ge7j3mtfoZAuX|wf0rVK73OR)red?@U znJSkrU#?IeE!0QCVC;F%&D<#K#7{=Kwx9B(RvVk2ihfHA;T&PEt*k3K#ZQb#TB6&| zu9~dIN#(qZYIVM`yPfi_^VJl&Sj<2ZKY8ufHTxZ|H&zR5p{mveO0od%oIpt|d392N z3>m?|2->!tKX^(d(RJb&yxof^2#YRa({ttaZZbNk2R<_L7)r0;M=$2XiQ&hb zlCiee#H`=4dE2boxagutM&^@xXy7`xDAYrLwEoQYqG6W#NJj!QwRrxZMf-k?a+%U% z{*+^Dx6OqkWoUIsVCi>JSxfjUhIeNTlJtI$@MxF44?V%<>}#TbllnCqbZ!z>90C)@ zNMYGB3{kkT%6U5;2}9cfwx-1QvD})rW9Xm+ILfzt=4*=^D|VWJH061l+CV;9ifd1K zt>xE%pIaKtA|oKd|D|f}TI*FDBxQV$?<-#1X!(;h z$LZk=UmGz`TON(@@XA@D#0arP?QHGn`DJ9Tn`xWrDcgJDqr8V--P2H%0SQb=l!<`) zWIn2*yTNDTNVhX(NjeF<!6&=UZg{u{Us#W5JNlY9 zVp&KL&WpxeV7AOcGPKskfWL(FLQZmLna$~wU#Z0X%qXPf+9}Qw^|77XkdfkzUwu;1 zOePgW=*gLW#i@Yq)ol~mev^i>geTq_+jsq|Ikces~#4}~sxWkV>p zodU^(Gs6EGYsBVl9G^B7IsQ@T5i);FG9~{E_3FGxQ14!<&dbM?$R3p`mqp*iS(qSM zN7CE|Dd-L5@qefLgA`LOBSkqcMmf(8-v-`Dl*Fu9p(Y zb7tn4b`6i;w2s_%Y4@Y#U`mWApjBNkI9e_G8pKUvo1G)I9iXjK`VOY!T|EA?mY#kZ zom14)Rke1qv6kg_wdjzKJZJ zLKi=7Maj5R9xAJdGp3xmXF6Jzvz<;C<|<#1R4!t+N$!l#aYLGt$79Q!b3Kk8oU;izmBBiB1JbTWEeZ;E`Jjl%F$j`?|fYabd$Z)$gpP^47chs&2e_^ICmh9;#N zUlOTYymd4iku5O4f1!H1nWD}csI|R!T7<;vXmxMgxaG7!ZPT>H@kB9(<8wCFY2KcX z<8X}YL~5X!a~e*y7G(BX&^$iy`}|xH|DjAJq^?Kz*PI}p^K}<}p7^~FD+z~J83|;6 z?^Ho%s*K112UMuo;D% zI>XP_6gz7|%D0O^#nU`osJ`*rBiQ5mESf?VsC%mHt)`UdySAgBG%hLr70-g7tiLG# zFg3K&mqLynGvDYV>WqQSjuL=GToo;o%#0L;R0SJz|4sikwFsI9@}K9-wNQS8Al)bC6oX9!9pwl(zjX9&5VO$ zkFOKW`Zum^aNp8%KDx`Ew)Ya~O((ud?fYU9D1+YQm+(_E^-J}m<+V0np9gRKGGja) z674Kav0@}YbYg*b%xP0gb5r^H98$z9IJliu)WM~nUcqqf8(KqjD^K{J1eZSbDUZHv z7q?P+hTijxTaX{Apu?;cHerO_iLC(d{02Xa-&-@xU58BEcj7=40+mgiE%BGGBL!lW zmqeq@eHo+f;svF7^lwL%eXv`8n4g=gCI5Ojitwvd@Lr!&I%%DWm|9<0D^R}Ly={4c zU8T|R{Y8k4GHsHtM=AS_0Xs_3(9R0E zOP92wndUbhULkH0siP2eu!h~Q8qCAD7=dd4Xy;ifaC})u#?z1okt${{e$1xZ)=6B;wte{cWSC4A$pkfKiPVXftypad z1-72t$vXM*o!(ESY<$|oa?RK-o1WzvL14>zF$|R|fOOkUAQv80o$f!jc;G2{6Eiqz zPnsw+ySU1`q@%ZKUqltN&-`3?s+Foe?{DX;<$k&p9s3F63zQ&M zs&70$RT|gV+R9q<&b@g0FqI`7J!}k(+y_njwbyt5Iz>jWVf_Uo2#UWh zqSbW_ska{bNs1-7u++KTu0O;s4gS05G7k0=LB3AyT$pR-CdZ?Sh?U}W{oIHhY?HGY zcadODpUoTB%Yf3aC4~181|E1#?N#v^vqZ~di8d|Vb=WYC!Lny{<}KV{Ip(s$ z*Nu_hn-s%FjX&zr8eBDrtf1?DC~-X=wNIj$PEbRZALC~JWEK>gk-0T&wNMK(=8tF& zv0dS63TQu;N6pI>(p9+2`OY7rIJ|`Um_7q0_VtF7fZYtgO8>E$`p8{B|KzqCtG9`! zq<7QXUHl%^&$QreURPOE~rkM z+Glh3T3w>VtUeyRAZF2&?G1E!g~E@4OOYij%Gx$3Rv9L!bm1BsO1)4g7V0Ya8JNok zN4i;d$N9m`Bsf z%(g-O&#~vjuB*l3>2Zc9>G()0yQacHQc93n;j}Tjp}H6b$K--fR_;KLzkzq@z4xre zRedXRFzx(ZdAn!iBvDpP36A<#juP+jAgcZ$t zzt3HMtg~{~y`qte5sqp*IHnim#(CHxA23w87@fcrGt1kwxj&1siudfdN^gM2RcrIB z{60@n3;$q1uOnM`=W^S1Sd0u=4H1~;@wtqA`epFO(6PU*?ekSa7$l?&r2vy^3%Tvy zm0~8pO7OOA>4s<7pvA2f?se@t^=Cvl^ouTbSOXBxYVc|K?MEkNYHI7*fCgvWbGUHXRXyx!17GCn}Up?}ElGeT0DPUh$6VUdXA>iwHOi2xC z?e~04840WpAN|=fxHO)z2!!B6Hk)4L(Uso}EBwJuE~3~txS_3WWbe({!TK2h5ft4V zsrs5mrEmygHdQmvVQoG+z%Rd?9;$pVXA3!2{2tUj@(ptn-vTQ*AZ&;K7IOKlv90y` z=B!P|kTxFZdyp|LX62m4!*S$9)3Pm&V_1b{Hs~Pl&51 zQmt&C*gHX*JM0Q_3k4VF+xn)M(1T?#l!n@bmMvu>3T!EaVxJ+QIzM?oi$JlG$$juF;NK&{US zOnwyf61ZFBhb^;ct#h{2jo}V0v6TLP+^WREZGk0`VULl|9GA3w*i|=0VW>zLZ|aWW z51ZBy$-N&Q^@TbW?t}4}CWnxyCH{dMYM%_y+Wl(V@0H>;#&&w%-^%YhY#KFGU%JSB z>Um9*!CzZokFG5&SAB@0BLt_L5E9}M}w9la^L1jO1>^SYlec+MTvkN zxqkcTKQ?5d_iUodwI9jN1PAoCga&%-*Dw|PuHBfcZuv2K^>pcV@nddR6X_qJlz)lt zd?AdPIb7+G#U}afbA!jMA*9gwJV0$O*~=-qQsD0Y2tk<`$Xi zpBbPt%C;N1q4nrcVZ3=`WNr~${kq^qCl~y?-X2&a9bTr|Q|-Z4J3XW}3RKv9?wSME>O?-tw z6eo`x9|l^{_kCY!-__>m|YB)#9np7y{owenF*!go*b&v!r=3gtIZl(=YbXn z)#GSS_^Awj@!edY>N{dU5%_a+Qt}1*Z?y4cQJI*ydHJv+nt3!PR3g^b52-+fAgjD1utqS zv}P%E<@Liylm2&UM6yV}H@>$>ZpbvZ&2kg;(YWv3oZ-j3Ke}S54%5$N%#TMHaKonL z%M~Pp+RT{m_}H`~>BE6@fD!;S@eO@teU#I`^}o)+M)U~jwj$mn^W?J`eC6ohCYO5l zH)s!+0?P}7JIcy3FDh+bbUw-;M&f|=vyQt=yms(g`qwOd!{Jq8M&^<&)Th9l6iHcb z@JB*q=4KO*6si@9Ss5rH)CHO;YYVWUn{x}{`w1=wr57)repq*SJ2myAxCDumB4JDg zTg(kN`xHe`*H-saq3c~QFE#Cbrb6=}msXo)VZl9-~5H4 zA5uBip1)Ydd=9hrM&&CV-HXggs{r28o zKAbpNm^u09?~TO^j?#9>cNE8qH%qp3he;A1W`0twV&jfyS9ioJkj2`@V>bWotMgOQ z)}?U)p&-d$jY>}~aa{PZynSdb4enSlGrT;O*8($csL_4SH0XPbF|hrmD*Ik|Mzy}So{ig>WlvE*yEwfzQWI~ z$E+hy{`62dSlA|I`P=Flgs9}yG3|Xl?j*Y=$RDp^Mz5jVj?g0KSZIyUgiNTUN7vFd z$MkgHQWLVi-oV*ZyX?^0%1D*2t1XMlwp3Do5ma5~jgw^SwKh7ke-rdTs%LP8xjyp* zch-e^c}ie_M~AFM^Ugj9=6=pri)%U!8NXA-hHRk!@?Si0_s;a8AAR(SO;o6K-nI1+ zkG_znp5jr6IF{4J%6X&Z<>It0&CSTev4J;j#Y*?y%9FyxtWRrm)6+3xKfDv=2##kR zo40V%d`zqnt7a7bnznV>&-vd->sILFi?NDB-|`k|ewK9x-dgB1f+HnY_s z=NW38Z2qg9t_^tS@xGVFG_8kwyx%P?d+)j~EIo>U^lo{asYw#YhLM%qd0Spw7Gz)k z;S`N*Ip$L3{3u)CJzEoaIR95tRA=t_lPpM+8&hyt`naC8iD6M}y_RI(2fR?~(+rffqPd9K$A#_DBg@cjFN|r|fj8 zdC?=G{uyRujWTgJoP~}-5lgolyu-{Gk^IXw|NAg5pY>;)&=+m{bQAZBNw1fOyH`@= zB*clkzh>tpJ|ds7FwG5T9#Z9xh;LAJQY|x1NXk z^@opkQifgIITylJ!wC@UvqZ<7u3;&S@SzYthYFMS)WquQb$8#2Z3XRkX2INV{H`m) zYDC4_-!O1JY?QTW>Vf}xh~0FF9DF}35jg*TW6AtEitf!_^YpFQM&O^oyN%|L?JZ(M zPYcB71O9e?i!~yDJ)o9x7>W!nYiT$vzz8b#k29ku88NZcl5r{WJ7|X>6W|38%hD@A zMSaj6cd(1Lq4!>9Caon?e2;HTZ*#Ejj?(P7ky{BZ8C18o_NO*7aOLo2o$#WwJl%*3 zs@1Fpmt?pTOWabelQsVzp1wLN%IAA{X`~UPyQQV2V<`dYZb?a{q*J;kWEW@ql)xpQl7vsMY_c2!Y+P9y!EN%WK?jd9EOfYjRp1SN^6&thICx_@33KQOL&M}4mo$P{YBVKt*{$Xa-1dk#ZJ9on&O*79VlLqt z)Xl0w|4ATrKr8p2pTk!{NH;z}0*s6tzZhj^_EfQ-mcMCM=|J5k5ci@3lZ5WCZ4?&e#gzt^yd#;Plpx0qop~WGhawSC{ABv_J;7qhHJ;Cs#H2sP~#?<_m$&QAy-m4UMBj2T6J~hD6iV(YrVjnJkx$=ox zxs=>PGutfb(Vo$v~&xOzU!OEh=cP$Io?Xi8v_oZf9C?5D!4z_M$c|cAT9#ldr`DZ9>h2bQFsFh?&22_~t#d;w0Ffuq659ZgkxFa#P!A z)-bI^Dq~2Nopn6VIgvz$x3au)L(rNA$Xd%Dxv8%%0YPw8AWjg>n#n^sOreFhJtC`;Dk{@Ny8jX`Cvy0{b=l_#%J4wyJKA^oi197W!@gg+&n2*pCvi@!_iV zRaOY&7j$gLef&=9FyXuCB8EV!gZoSaSKTEZ;+b?JXI-hop@w|^scK(Gf^Gwgepl5A z&gcHnli=S(0z%O$Wv*8nsTrSV?llIQM6K+}K~(P7jx*L}=hCYvS<&_@}k62w&FfW7ckew;pP>dVUrM5Y!Mqk-O<*;RE9UE)r zoZYN+ubz3RrD<@QXBHZlVo1mR&rFYgPfFY6Kl<-BJS(BYcb&dY4c}LRERPY-guRb3 zu)uD1n5(FDEaZ!6dXxt#3ng~s=bRGwIWf@^#1t~u%TM~B$f$h86Ac^d3E@lA_J1#gbuP^Kx3#!z#36$Q zPH?`3zo6pt_oD1JP5b-&)B;D0$6@sKs?fRW+yhngcr}KeHrGcJ-J;-7ynI~%pb!mL zn&@Q|QW+dXfR#`Q3Vbb3qPJUUMo_O57JQvD^ZQ`lk!oQ+w4-+71Tnpeww+1xEq9}% z37+OFOTM72>__4-3XZ57WWMKXzkrANdqNhb^>rNhg%KB$GV_;~Eo9?1Y-C06;#bqY zf8BoY2=f)Y2=p+~L6;FB@)Aat06lQD_%B?yp;%b&xUW;?iYz391Dsr6tF&kRz_6<; z;geFeDEYPrFuIGVC~7{Qz(4uYc0-H778(@IiQ$e^wT%HgE1bw9@1?YqpR1PiEQOE*xTqjs?+s_ z9VDVHoO_2n+b&%l4}L_f{n&>kv17{daVp11Jp%lLET>g!*X`Dt*~g*6TOvN^;!@&h zKL{Vl^)EeDxg~%wey7Ll)m!uawsI{+P8=fm2JUs!mskrnQ+pHUs2P<_#m_7Gr8rVK zc%+QDaC>dsc9)${t)C?Upso9-dYr=MebLT|8kZRv!EJ!lJ zn@?^ei&D|qNh%>BIQPZbzo*)trWvo&eV%tHDLfIH+J0$xjB%Q>Rvs8$shjtWImpGc zqeh@LR$_nP9966R4DbP=!j5KA|*>)d)o61ZAwmsOvxc3CIkBiw%D zek3WSAAoAaL1TQ&mC$}JRCWDUy-q7@_akDK&(-Ki?b_)ag>@>Rtx%BVxIEq+vAx0Z zCqe~59eyAT^wJ*+{LyX7q(TNk3J%!~=WZX4j+H;WJ*TSs`fKrxKGv4#>{mbwQ8H-< z@;(Zs2&7RZH;vqW4tE;}KeWo+IbrpvSsZg%jAFY+W!vZn6sJ^qZu2FS4r)e9!^bm) zaEM|#BB0|%CB0g>eJ~cBvIVGo`04hVirln^{=D2Va{xnK31W4Kwf=*ff8WMyS7+}q zSWwWjXtw88nLj6=InvUNvkaGa__(zl@iCsbj>SyXfT(Pl0CBkLZ_ynEWNYRbjFPB{ zEkoHH1)zv^xe1O<)8kW9^1HPweKGOt6;$NmEL%C#KrWuI#m5h_3-@Cj(9gx5B4L7W z!%vrQ@8W-_XO8f*m%%mHx|M_X4i^`fzf9_OCe7k^lBnV(8lYj63yysG98xaR-TYc7 zqdQ_hi`y{H%LkJPmt5P8B_=5?gQ<~c8EHTo!w1i5l>f~Oi84P<{^aDU%lT)5{z|{r zt?i44hY{+teC-?z%GSD|%#lt-IurZ)(kc?-mGmfpTw`P)=p1(ggROg~f^Y2EH>*Uo zJvQcIWJ@K&i=LiVIxX-oTD@|zNg`LOJMMh!0jXQ$&JD++e*0oZh&&kIKI;m{MIdIK zs=DUuWpizX$O1@QOA{kYBz8yTvAI`24I`>s+WdKqBkq3qi)wmWz_|)sFxB9R$R)mH z_Oo!4??EpWGD2M@si&L}rYVqw0v#2i?Rw3XCwGyvH?tmED{Fx#&1$qPSvSEf`3Ad( z!VJ$KR|W{OqQ1rEU)f0-%xxQd6Xu%_N1K~yp2o0-evMcOSlBvAXW{I}bW*5)HmmXik%c8DV_V58It z)yL}?hN#$2{VXJunjl;`McET>nmYZIv^AW?vmZY&G=cFYaJgMSpSc7rFEj2@MOBK{ ztA92*sF~7EoI|hTTC?&ixAL{*hgX8C>eeC9p4=dk8KjBJrj>Z2skx}N(+?M?jH5!L z;rIL%IdR1XcY_W+Z)%BUuTM~s3ks;SPq=i2a2}r)(fT_PX=TM8oNQV6PFwxBRe8(g zYr;+k-v9}Sb3hO!vRe|rR>vUPnA;|1$fu**QaQ&mGuNx+{nfMZP5Qj)=}~?U0ui%y z9K?d_^_LoT^awMic5K^m3dsh?;ko|dj2~25y=@tCTW=~?6xQ|@eO?PdRcGqqBdRF8FD zfa3>U3SU&+*S`cN^22NU5!F#^=n4dl)xAW91kGT5XZD%_vm3h5b?7K{>mL@{}Nv@6s%6=r}^nUdPSm8CS8slwrnT9{KCGRO#vg3LU^iSQZ#T zrME#U7Pl1N&PM7-K5fJsi+(rD|Z}%0rgf)>t zTl>>~^s(9glVql>?B&V~*3oiV8@`}BAAEPGk1eDR|g?Qe)qspgI=VXzcoOo&u{ zmj4y5v&(F8V}O+}h3eM(>1mGz*aW6T*+T-$rcsK1 zEPr1(+{m7|rT%)T<&uPN>*#m&;)=UiAuIHPl8e5@{aRz=$xq0{Y8S>Y+U2F5wojB{%T=ogyh|} z1)1o4LN>Z&-f1t2_NX0DsbsiblDDTjFa!74 zi7As$SM$wNmwKxA9dVzH#plT4{nYytA6D-(>ZpYK8j-&#$>TZs3-i_BJMWV-BB9)5 zEiUF#ux8^^bS3c&#VS7AO!|FIV%MfhNuo*_;kL0S(xMb?#q|W~e#7Gyc2%8s`!MZK z+47M>!^+46|A5y7Bsg_VEea;+MVDfSVF8D@G7GIqfh)MwckX1b{>IX=5P2NDEXeYq zh^Rm7475nsY4aejJ#GolO}2%i$}1$P^fhINjq_7{$bnNO?b}ZZ_)`g-?P^rRy;IRR zVbQr<*Z_RIgMs_*tBV-rrX>#Z@rK8#eVumxK>{jQi0JWBkJPDL7$(ZTFbRzyrbED= zUg(sLn+!@6^WPj1fVz8d!7qZght2M~N1&uGFW_T>F1^0IIiJG*k^l0N(gbCIzI3GG zGUiPgZe39B$4VboW2&1L%tFvtSZ!(vT*(D{uMH$=W~g6=zvI)EGjOq+VciJd&`CH z&F`a(IXo5x7-QXdsqadmYt_dP!KC&2{T?~?Uk@Izi{3)A6dZdv-?wT_&;sN+%>N~j zW4ZP7?or_SK@%gh9aXi&`<&C2{94qV@Y>OPAf%bm?%a3kvIzj-&??a&*KL(x2CV9z z!fh9AR?+z7b;?hpAH&Q_7L|tO7##Ke>=v{(cOj3{End3^dp5-k2Eqa50V-w=rNj(p+oL zU)c#+;Gaxr?utO}wWus*3aqsS+sjR`)QjDad>Vj*LXpkbP#VbRSYN0#c%Z=`UMJbR)7qAj%^ARAXT1p7)L^g8T|Tww38Up#La)^ zzj;pu@Pbh8~(IhFJAYQ_BUSh zLi|;;SW&#!e>&AB5hM;5o^6XnM1*ww0o7|u15#+raguhM5{F8s?w_{?oQc{_ zh!CsK?0>}duK>C^bn7t~IjZ8;oNtk(pVmhd75=*EW!+B~iOPnlOHn3+DJ;r1IY@6}J;BJ+@HE@wO#(H0op_WXU#+9@Nt-bOYs%bR<(389eQsMI!&`H%4$F(0*&mAKR0 z+yZ2m%(EDHSd)|j7=}^2m@%prZqeHywa}M{a6SM>zkkqle@J>nVe5oG$WpqP*Dfk9 z_`Ky=ST6?{OOesI$F(LBGDPsRB8q3yxOcTeFuwJIF`_Cr;IT>dJ+%NlxzNwMOqn`u zvGb0tOK%Rv8pz&Fri~+Aqm9MYe`fO*1Y*o1iLcviK^jMfwD2I*+_0QobbFd)aDHq=^w;#AZa?T7f!~IYOV^{RB14*(78M$oamd^mm{~T$P~*&z@RUV^ z;v-Y2-X;B^Ip4*%TzY`xI=y0*8y!Eo*O6QVYP21)7V~NcGmTOQ{LvZd1XROs$@lO$ zqzw#8lW0wVL-}#dYGK|lm0?S4iCwO0zK|;C8^382KGO^M6>KjOP9Tjt)TP6JQ;miM zlgEt|JdeWH`zvSp%Q6*PAG~lG27O8R9!vf6j+pb*rSFGZQOjjd1o}U%RfT^y)Q$#o zo~qDt4wv7C3r<@O`&hOz&dgxj*gr$mn^KTVymz#FJ2z{vX-dMWP=N^uwzK?RMASR! zR(+fPbbkn>-u{~LAImKBPTCw5{|Y01I~HwS;v;Q(_l+Kz0tlAfmJEf~cq^STMqiw6 zva$+9BeK?+>_d9aLaSbj+~#zu!v)GU609 zSnUZOwcYbgZ6EQOn9FMSHF1RAbuwdnG1{2v>%E9kXr4M^uzviT9H3-8wt~OFUm-6M ztmG8_KDCz;dV!uTF|yOJ{|K0j4c8sbRYL=o-~JR8HO40X%>f_U59Y6kCx>6^S(rrLY04?7{FnjYh?Bly@A-joXqbDd=pvyqenYM+(v&W}59U6V20x@5=y{s!w_()r+?NDeF z5{U5Q4+1HuPnE+v#d9Td&*nlUOmG-F`Bu@;gCfCz*ri54W0QVdu?dd0v|`7J4imbm zlIvE#JMM=G@=P~*CK-hbz!Yz!`PG4W944pVRO5j2>T6GUHLuEXkp~ViM>a;6RlO?2p!(^?P1;;R1PJQ1t)#n~_r&|(1 z=Gx!r)3SE&BS6oCZe(^%8evzw{ZG99Kn3YN)`f}CT|zMg$D$g_5AqYA?#rj+7w7Dt zeFLnWt?Q5>H0NAMUDni?$It&43-G!F!V(#c+{8Sh=J?apbY%NZR~5KuD>Ct zsV(vW^I~u8Ky@iuusFEz-R0eS|vPZ%GOXoDI($If-*I73^JE!Y{%oM zww4vJSY6SpiYwzC8rqk<^%b)EA&??-+CvcWMXl-_xysOp!<}Ak(ddTb66#!lz9)_o zc)jEJ<22X5R<}DX#+CpA(XY} z-w$m!z2@5q>BDL;K3<2y%O_Jd^-$;>f^npy3_V{4$nhszIhc%iaAH*f9>KFTo*oV{ zB-IjSof@{@OC1tuzz|T@6EbCZRe2fOs^p4qsE)|TVg=P1pt+R51EZePP^OJyP9 zVj%%RpIs;=vq^);kHs#swfpj_J*|+}Q?hL$pq6`ric+Dv%pH>ooG#?arcf@7nPgoo z(}EWhJd_VhH73MI89(RKnBXk2U*VpaL-u}*-A$MC&m30X==+EtH$x}wJMLHCnubV4y}z@(?{Cf@nNeU{V}<= z?k2Tr^yY2#sE3DjQX(ABtH@`R4nK~!E5r{^;j`wJRM;k zLP<6Jz7mv(Ui81)L2H-4Nl~-biiCplm{L8rkjfS_%LSSSxG)y(R}3+-n*Enf!)c$1 zA&27rpqzmtLv^bTIMqU31?~4BcOb*x@BF|RfrM!0pe6jGek=CXl$+f{WbEkkvOxeB z(aiPd{v?aMDaxUZ!)epSNrh2#q;F>=7m{$E)Uo4k;zD}|??vQmFyvJsDJYwVBIZe6 z!xT&U3#<6E7uk0Wc@ z(335aQ~WZRF4CLYL@4Z+d*vf)$XC2iZXQ%xjfzCYz8z-o*I}0?y$JM&y<>!S>a<+R zOPh`YUL$;G;wXcbU-!r7oCFp2)Y-l#jtU7#OcXC_m?bU;K9QjWgy}u$%{*RXxFayz zP0T(u;f#Xk^}=>iwYZZgS5SWc;cZ3+1y2096mTx}uUmFM?lKzjswSP!_m3?I}cseTWLIfLyd}((MFtsQB zOnSgt=A^^lqKp}3VdUlR0TFhHh3Qo$zsfkXm7HXCmiqB6UB8ou-?tJ;)z(dVzF3rj ztC7u3UTpsE?1aqLz|FOov!&me%lb06={YIagnUkx%J|(*?&r5Z?jBWqp3W3AM^GHA zAoR~}X2kz=kXx6MwXCudfH*zeu^P$j_xO%{e!=~8;W9N!KvFa~3gGW!w#?PyZjSG4 zb`Fo&uM`!*@JoC}%4;q^S^e2W2Tz#mgWtLE4?B*{w^)H37$44;mx}JbuU#UxSpCHL z)|&04?Xc{EX$w4o?+ch~2JiWuL~AZ#nMd@hw`~h~zhcQ`?OqqrAcC;r6*xe-T!=hB zUQZ`~gtG2(UcOZ9^f&6uwuaW)ljgUCs2L$Z7M_HJn(jO z!Iy&yvJ|CE5t|k)+1M0*ppq}g2feCSV=B&g^o9rZ4`Z%xkBg$z8uxS*w0s}sBH&}iK(Wi%e<_)s^)GK%?1MNNQQ?6n2n@dlbQW&@ zYYol$gC1T+~A7qinlt)w%#3dXLRE*66!JWNm$0O(uhK zoN-x~D;}Q9l7TdmgAk_bJO3ih@`6ZCLx?V~SqI#xKh!dXRj2V$>Kl;;wH!^E#tXH2 z!d9_U0YvGq)tX&fj>ZUAx;<4~f_bAse}KS3S`}fVh4!cL{j(&azV+%6->02t2{6ix z?r#k6;xTDA&4t=(4#AswBu)Tw4Z35EM$x%tMJ-MDAnF@QQ+Id?_aKRzPQ%`(^Y`jh zFS{EFjeakn94Dp3)W5)~@;(=g`T&QZKEc~=l(&rCYE9kN@O<#t`9TWqBKrluCW;G< zV9R~@0QOKI2t($5yZp84q)63UBs?w4XCJW`2Z=cPFbSj{1B$u({S%`oiEt0DlYHLQER5gWS`wcOx(LG{g*U}$}ZiAzp=Qm(R@l($n_f~Oji(F^BW`hoc zzMpxUIfR3z72l>!@FRO|n(X!jox;l_DqjHTcVsfi3P%rFK@X-X{lh&`=IH~oE?Ir= zRHZvcx7Of4bpBMq`phi3?2alk2DVxMvE+?~JnTZvw_uQD26o|zWDh78I|ydw+YYU6 zLg5=@l!_>Vez@%2aCGRnHpiCa!0cpC?enR^8qq*3T78zv@AdikPD@0mVP51NoH^--vg{7Z3N(MKj55;fb>=4r65 z4AlbCh@1cX3+HH>elCV=UxLzF?l6uaIHqe^A?M9Tso*+tAf|}Z1zm68u``bfzH?%6 zXU~3Ec?s+ya0-Nw=r;bb`PJ-!jwatQ*h`VYh`0m1t}->`b$tsaG=gj7s#ewWNmgw*=6kj_{jJO_dp?`$EOa~$7M(NL_X3|TO$O3 zxd3mD`@REw`rc;wH$vkG_L$d+Vj7@t0Zu)$-6_{REo~EgG@!tcoACVK+}Lq+Bz$LG z*uR?1Y|15UH=Z|9 zGS6x<8w<^@u6!clfGOrts@z95JI%K3%dZ+mYUf%${B%_wJ*J^Wg#37l6qc&M(uDw8~jxr@BdZ^7ku+h2oa=S}drh`*h^#plJOXR9aQz-s@c zH?*lTv>9jMGb*w`ig7sHb6fBCJ#Rgvj=YBX!-E>ewdmZ!BQLfuqYcMyV1ReAQ@$zB zTuZI3_|M^&Nl1uUr2bb^PqlWTuUZ6McDBJNp|N$JGl~qqA!s(NdA_d9$pc8J(J5}i z=~b-_%52)0SHo>N2bm1jOKHGz5~rIx;iJ7(B*~@gsJ4&#u1!@+k(y72uk5Tn{Bmry zK{FH{>TdUZ-bY#vaL71mm&c@VJWRWelu)WK$=i6E^|in5PNKfA3ozNE)B|bY zfQIVL;9OLz|0P+SpOA0`8o*B^$wVT>ITtPd<)F**&y^XmAS5{jrp`OGTp0ow*_e=@ zfkcbbp&4_2Md$Ft0ysz*7FHws8$4B8-FI3?#*sHk1;UFfrkFwxi*H!*MQ6clUmPj# z>$-jfK4rJVzaHwW4JRqi+f?bZj2kfr+`*w);a;iyL}049XcL~0mDh+38+%-$cT<$B zL1MQuO0n%XXWO4HS^Ut)Iyy%-@Kl}q_6eR&IyWQsQ)HVyc{DUyO^_1IfS~;uqoQ-- zd!%1tF9i|WZ^$-uoZT20_RN9HtB?<@GcU%7&5M4`2}qv~9gGfZj3>E`zF-VMkp$uh zZ`%ECDam$kE1%XXKOBtX$=Xm#f}>q+d4sSCSd{s1#}p94kkh@!3v+;!X1hP&Q#bf< zKQZT>?Ew+di|2(2oQBt_MHcv6A2$+SY)pK#-lZF&&D!F;z2FA?uh@?*-L{nLU)t{m zW$(DZc<&PWA>pNDZ;iQv*#OUvL9dMEu~*D8?dspc5K^ApIbPu^xXnb&va*1S?BSe~ z-K~IFLT@e_du`#Xy`Sb6!{kv=$+bmO@UIJ>X?ssU$;?ffG8A$JyAWCGCF>RIv0t-Rx`y zf_RpnFO9qJ7EU212dLKGSC&vmZ$OS!6JH%`@t_6*%HaD?o@$eVXE_wFXb%DOZ#OCd+t%;9_&4$Cf zg3txo<7^!r1pgsRGJd}k5#jS-ZRG>r@STgHW}d;zz7Gmtd4Kf7&v$mMxG6KZ5i#yr z2U1bt?8;D$M?Z0Io9IvF#7;ABIW=6hI#S*=9IfJZh4i}lwF`OyyUN{LuYA7!@@bV@ z?5nu;IY%LmYmMRF4jX~v8e-J?#x16FiczF1to{F9$3 zPFmo08H>%^w52KFkrFmPLfKNA=ES<)e2AIQjk4e6G}UV~ z(T7CGwM@r{rM40I%F4_xoba7*Lyk>;Cbs#TDlq4VAatb>T^v(ZB|I1P?{;_e^b=Vi z(@Kx+vdGEX__lyVA{yLG_+Gdz19*ME8Fb^sZ1Ov%e}FBi6m9hq@M1bX9JQC;o{r_j z|HKFn+cSBq>2IM8$;jOKSU$@O!XXs_(d14{@qaET=nYT6&=pzm2t=?djOC)EDGBmo z??%oAMfK_(vziQ7;i}F9r6M{BDLT)}N$*9Eu%A;ZbK^uBMonbx%rQz*3M+7UX%~N0 zCopRmP=?=8N0##&|MjG0pb?~VqzXgV7V}zJ*Rpb?uG8}RyWO~5DR~K5Vsy=Y&)J^e zVZr;0K1B)+fP4>ULfaU4ow*5bH3F2QB#su(9fY0mB2mlf+E>%~^3YFtykh46y2Swz z0VlWF54%7xG3A|*A9kA*J~xi)V^=MG9=c`sWq%gcR|1iQ?=UR(tTcWEQiGoQtBtoK z#hxR9_oKgfM7X$_A+wm*KZ}O3e;tLg!d54$>5T+j*6x?>&y+C_B*r(l#$7Y{j8vrt zX!JHRAr|YtG{&D>ISwTH=9}u01J?!E_0NEko%-IsSdPzr?U8BxZN?MpBL*H6+U*bP zJH+Hc2c{NGs3Con3H#)mntYTC&lA#M!HnV2%_n zyLrI9^vRC2<4EUcs0^4_Zv_7|GlTTiGzV75>4i=n9IfEn^5#?puuCA(P?+BGf#>}z z(gPD%H%HvMmV}RH{hQ`NPwX5IY;L2?q_DYZY&>fBb!XURNfob=NIBCJfy!_|K^e9` zz)f>|I}808MidU&>PH3&hQrDXCG*uM$&OXARAe7wLR>6%U{?#MnUZg4{9fAt$TyjI zEH}2R0;*sGf7P3ED)G0gK3fT!6C%3ic?x zvld*NRqMW7Evn2P!E^KOgDppJw)z2$J<+y-X8}poF4nAQ0chq2gSZbL zlhy9yt7)H-Nv&R$M$`X*I{`+=3?9rS{>1&&PkgNT-}WXHtOb)3lYFLsiy~Qh!ebJt z`uy*Mmml@6=VS4hT&CYl;oMzQbU^NmTE>|mdR~Hjw*Wk568ue27eli{5;FJ zEn)BIu%mP0$lmYPI9~FxX{E-#>pc8oY0VqB-tbo+*1nWC#e4~>f6W&^iSdx6fUtvA z6iuPF_&?xvl?XX!{t|mlyZ!qEF7MkTQ((8il>cA=EB&wMY5zYkfzSUI%w_nGI$TrO z(sYyvNkyWPsrfxYFrc3xPJ&=nD5YObVA>_w+APgW5Asf2O793D6J>!(rU~JMg{CE9 za%Yu~{0g>Gu6p9YzT5`pL+A26;_)!!m5<$I<(k;@kigT?UwQDuyG)rGz&!<=){X|< zxuEZ12LH)DB`f8ghiP`8-}#s9?)+8u8_i(|@RACw?}A1EIlIXhyTPwqo)tc`eHd&% z$1oC|5AqKcYS3{J2Zk^*r%j)VJ@1yA1@nS#b}QRsl~X1dc}k{W4NHN~dl{6KYq4U6 zBJtCA;m_yfcIFCKj?BmkpH z6??EIPRsRJS*KHls{f2nH#%Q#;nSY5g>e7FoFHy-OTh7hLFI0B`$cf%&0efX42#(q z0%fT_Uqz+Ml@U-I5kS8n?u+uT)5mt?Hw|IN-Layg{?^c-N?{?j3ESt6P?lbDBZYtM zWpnXxfv9ua9fGU;!jL%Dod&#-Rp$vGR1a*2`FM^roe`HKRjvOJL*r0pY2&$|T@m#| zXr<%ulJ!?Y0Hv4H4s^TBN&)oMET+o!-x-gE19yb-CUu)3S8l_Vj+Z=JWICu3Oi?N7 zb5dhHN-J@&GCAJyybD8iLKDJXKp93FV%9fM~lQ2!pGB#Og;0=n1`vh3&g!tV`UuVbq(Hg#px^TA$MTcrreCG}*7 zti~y;Du9Q%&R_O+n=UgkK^^SIe@0k{37&c#4SJu?j~+{6Z%dUiR_FPrRJaZoZAYSH z<40YF>}@o&ueYBUw>ih~iab~k3!Hy41Lpz<`jrs==X*@F9d1VBOEnLK7=()u;ZQU? z3hCdm!c*;zCih#6Nr!KjjOC8*n}C}c*FDT80QyIFf)VyYas(J%+}(?DT0C~sy$n2$ zqm|Daa)_1R_d9HBdxdTuO^tmnU&`1pSzBBE!?wKxt-hqN{%^e||I48cl;Y49F3&)U zi?1cevZV$58y#XdgWJliRU#q;-R3A9!AC0;z^McE<>s;Yc*#lAXr}6|##o#0>OJN0 zM*;SRckzQ?<7qWMRy#43BhCGMiQs9;vHeTg^e(2y$)WKLHTYqm+NhBH-yN>woc}za zkim=0Q^}meUzE$gA+0M=iF~T6FEIP@9$=&=r)p^Jw^rQlUwof`2ZlZ# zU@NaO8l{7mag)vGU%@VcYU1EN0l>P-tRi$22(N#2xqs76;>0=2<TSs!(*Ar~d&0scjHcf$`tQmW_3so!N87z9-G$eh zK-!4V`rFG~$grDN7l?0v zYGM8Z3U6loosQD0>I8NZmcpNNU#tMk;%U6WxyorD4AKz~rgCwMt$7cHPylp|slsDl zR)DridC%&M29I;fLWFwHIl3uf+=pJ=nbGG4Yxzr)D+qX(PZxr8f8|+f_>=)#B)a;* zwAN{oLb&&4-cDuz-vt$ z5jyWS<3~%5rO`bsFdRmHV18{JlE43N4&(_)buzmty(Sb8q=839W5sGTuZn zH!Irtg0bK9h+(@NqXy1*uoyl$A=rm>I>d)7ghmuY7SR1Yp&#B0!g|)y%1d~V{ahD2!kIby!s%p)+sj`>L0pnxodu63=~C-N1ulS(9KGJrXx>S%I?5F6bhp6<`;fbB9(PpuglWxLv=0EdW%m*!yr{uI_=LzJN30OesUr zDDWdu#LW*mgT1^Sm{`q?sfuSi4Eg1q^k@wi8?_pS{c}@cr#r(pbrHh!C;EF zDWV@sSU=G1b%I&_1K1sbh(QgYp8|kud;r(z86K>3Jb7nHp{33Y(SrZzf>%+ZzACQI z%vW7Xa)RZ^3m+H2Nsk#^2+y81?1viK0G0mMqCnRtfhk`;(gbfvF3p6udZ|)`!a*>u zqDoGb91R=~!Ap-at9MnDyGab;@W3{rx*q@1Jcu$G(K0)QipLsA6-Yn_ zhRjTHOAk5PG-R`ifB9%VkEiwq7u|%FV5M3GEc=gF$=0Mz)Jvs%NzE4-cepEq@Tx%% z!X}wJIAla$UstYwJ4zUz0$|4@TalMN%?L!Xw`1fgq@0quSN~L;S1uDh4_Xw?86*&=q}K74h_GtlY|P*Q>48Z^ zt!nj;EDeDxx3vb4cyI(CSp=QQulbR4p>PtIVOP{?5rKTv!wc->RX0K|lL^&9hlV3g zrz+nsdK-KIW4Ty)`g~jbybICWag)s0da*aJzVBjwpxFx5HVtM}{RxxFuBgD%djk8K zkwGUwlCoODtAJ{Hf%vI_(Vr<2B`h5cAQ07zL41rMhmESL{2c28dm9!s=%>lp{wz=k zt>~xj#G<#biRy9^bdAow&rimUUPRn4!o9NcL`dCvA)e%Z22!nsF&i6ziL%lUmJ4X9 z1xL^;S2CM&5kNJJ{gv#)^?*J_xT=u~TbK)x+nnviITw9zvl5t006I)tqC%dH2r9Dp zx5y8`zF@CdU9!X~_O?i}QkLsBFKgK-{?wmXwE1s9T%8MUEvYUmBTI_#V^${p2vs0O zTPt22p06|>E^lM5>8eA^0ymrXf>&}O9U7pHn3nK|J#nT8htI(zjB28u0^w&X+R(_v zCv^}A2Spw%p+TRL^-)MO%gQq-PWoz%%H|7yR)=K>8rPQ0asizTxH7em z5?wPh$wfdf0pMN*Tq=6-9r^~=egta(wcCM0+W=4VIwd=@+lX_W&EUg5U$^rM1HJ-f zyTKZc`?D{P%B)I<3zROA-T*af>_~7AVJ1-tf{&Nu9H7-GnmR7?=)MGG(DG8o*2huQ z@S-%>t}}Bl6<>VeuK@@e>S-<*4O@=|MgVvP8GJ|GybIx0@vjdSGkRuuXav#zeW(Gr zotCE)Uv$`eps6kH*c%;4P@@uNJzyeR{r6|s$&caUyP$LL>jD&{!gU~WoePI#bual{ zi8dDxW<9x}lFrgNRBl#%V}|-#&#L45S08~2P$YL=)HsshX2Q(jTm(SDx>dpiCZVfq z9n7N8?P`3&DYy?hVO9&0kpmyXjDVsDAQk&ckKhYm4U=fi!7RDT8xfq};2~_)l^RCe zOm^5jvVgkCKV74~b{ zE7))WWHEUKTXg#+}4} zwXpx9xIqA?$GW~<;wQjt{yEo(df|@j%s-p)qL=@w=LLjkXk-vIAk{HR$Z=KAVIGvG zT6>f){JaLn^2cwZS`AK#yUe6azv`aKgMURHhk-TtA%`pPg+ob8(?leck`ccjqOVnV zaI%PohZz7AF;-k#pCVdWX|Cd4G+R!C-oS~|bNhs&p=-B-8XlGo>nNW|G7kqho*LQ` zWX9Y_547Tu40f>BA3#AQxTFJa%y|9uB; z=KTJqvnZv}orVQ2A+n@^81x5l`S1Y*x!3_R(UMJFH107cUl|!_?v)7BR%9(_u`H)* z8yXWN`WHwi*|9?2EK-`Q(9#IPOj#G}0@#lt^-H~i(q(ahJMtCKko$y1BLHY%bpA(i zzGKLSpni&*iP$R$=qBUzml1$xtRGIT2>(dFrQe6G`JBHiscqtFq)s{#j02kT9pGO&MR@+P>> z<@0qq9h$&AVHaSkySq;@;;ME6ptu$p^moZdzGh`OYo11gOASLh*|0|R)wEgJ0mQ#4 zfCKUZ>$#f^U$kpJ-Wf=(mk*$&PMG0-^?8RN3zXt_0H726YWlVT^1TNzXUjqZ^&I-KEQD{L?5d%4 zhsMO8mA=d(i#DlY9EAe+Xv`EqbzM#{8)i0Zemq-x^E9BH^@jdVr9hRypUDNfa3{eA z#Q$}Hqg+&`E*7!&WO;l(TvS$Eu%PHY9U0=}hGK9dxZLpLGrfZNC9{_!J^!d?$nD=# z#TKzvY$=HjHM*Gdd^08$9j+a%`%}9Xg~LHhYQnJCZBdK)T}~f9(E!Hz^YcLt8IIPz>U zX-ZA%3gv%)zOyNYgJ#K?AY4^}1q%oHgVGzwjro>Tk4KH?gq>6rFhK+G0hlvEHMfBk z@7b))Jw3u>7{26FI8-KO=-Gf&v{3D!6zBVP8e&RpO!32PF^wh6lhdk>NJ1Ss0)y zL)drRu)K@oQ;*=aYh$J=&D6i^&ZW&`ukjpx;l*cZfb2K}*35}({w>~D?^t8f6xFnY z)J4iE(rXd?;c#aB4Ve>JcEs94c?9vs5^Qa3imFT7YmF-2`Fg`anQjOvXDrZy17(hv z)D_rvRaVM=?SS<&^=v=VBY|Y3Oc31Si&Z4W7BHB{64F7T*IYc`7+Ed*}Gjpx9@6vTi6ueUcJd{RHskJ}b^m^xQG^Ll7LE^Xo zEa-~Tg&VQAufkC92fGM*j~7*&3x`c7yjjZyGn6y4utX*n%RNKw8DlU&Gg9t!XbZ32 zhtkVy!)xQq%kn@t3&4CiK}SI)HCns!%ZUkeg@0emqvcDIU`E?8bLA_F*4}0HZ?2zL z|03gyTsVpwipjoQUa=R^aF-J;bR=!(0zr*rO@dbQon8k|m}a)S73XEu1zoB zbKIMrZL76$;bBf3vGz9g{?keuo+MH6`$O{d#}t?C_+2}1E%GC*OWrGylWBMmld|y3 z;G92<+n1}clzW5w#tznt>i5~>jlCngYvqvf~N??(;C9%{Ey8W(Y3@#dLGZ(qHN4Zl&^TEsx8w71<`fFG`J)4u2YF4J5`i zWLC|!fd6;xBwFu9ShhS4C@>+|4tv5N|1)WmAnIUs)6BmgM=6Tb;=O)cG+~wu?)r~4IXmM$XaQ(;bdM)+nCT^SJ$JGwORMEw}n^P3H1Z| z7tSF6YMdDpfmIhB1V7T5aS^fmeJjB&5v{Wa7twM`E5Avw`-i_H9z19uoq?7K6wp() zTH`nNhfg_qjQ~PL{8l_#M{fi5GRtj;ef(~G0Guj_hW@cr_fz*9bE3%6u>P|Qg#$$e zLy@Jzt=8yU%|A6fRV^L)>2pwe=oVsUPI)P}7QX*tHFn#{-C4rv*z#_;zaX(DUEA^G zN#P^~^B4s$Jp!+-L@#e>6HCc7;U*~iy zdaLBU1M$G7&eU4dx@urs+TscTU~D`Rg`otJ>xZfudyQ-so2Fya8{0dvxxiLkQ7w;s zWlc6oMY}El0E~se217BI@GWmM+hnV-6%A2E_cm?*$EnyowqiX>0RYBAV1uF5SJtmP z=ew!z6if#7*2%ZjRokVunl^RUcCWi`U)8=%pUYdldd;<9GPvnI0RZKLJ8UqN3d{Q6 z@?VX8C8yP?6OAWye&D=Pxs>b`cD?fVSCq^pi>_N5x>C86Cc+cCv2a7rwm-XSM}wt` z-B+uvtX=oK0D$sGV1uC?a2-&GyF=p(<7>|Q{QBpbiO;CR-Jxtgt0Di;nqf_no@;+j z!BkMA!BI^{CY3Mb)w8c>-LNLzDK`QDKrsY17)rIZT8}n8x^7^Tq;Dp_ktR#qx38&B z6OjpByM1lh_yPBUlGgJ^C;(tB++l;E*e!OQdHBqh@B7B_H}ret_hn-(juzQ1_I1~$ z^XZ~p4cvD3mYfd&u(uJ|U^o@#3cY&t)h*la3EvZv?(`^K>gc|sC9NL~j;=cHv3u5R zA`bvC4gwntr_xfX*Lq&l(``>b@Lr9MM!oaMJNh;B>#}jX#a>cbkaRv>G_VzWa})qz zJOnlvlE?1Rnd4`4YX7NC@8NU$^uehQbZPq1iqDQW94~2)p{b#wwbqI?h6ex`4}lGa zb0pSL($)?A;?r#0jsD%u^vTjiCvir=sS z0PZjq3WdT>9|G7($y`#YY)a=Zo!8~r%bJPJtUAwWbLwQ{Nxk0tx?bz!0 zv%=}HTAVHNIel{5-HUh80*Qb^sgSPDU0t(_!C?E~hC3|)0LmAE4Y(_rODd5`=z8$F z(z&!o=0}vsCUm&&u*@d2j(Lx1DmJBC(OYYl;b^UCUGc`~Ms(G7sn^@P>Gc4B@fiKw06=--4jWLSPIu?J4c_ak*Y8zYjK}UF ztN{R4MW+LxL^g{}KBrHUk=5HDm`!HQ#pgD>uhnc-S8bP$)|Xbd4FF&~1U6s;x@xa00NCYtmID9)u*(tH0001XIRYC10KhKyKWWv7Ti~vQ QDF6Tf07*qoM6N<$g1P<~u>b%7 literal 0 HcmV?d00001 diff --git a/markov-departures.png b/markov-departures.png new file mode 100644 index 0000000000000000000000000000000000000000..99f1392301032994e34d2ecc0c127f3b92d155c2 GIT binary patch literal 43820 zcmbSyg;!Kx)HWqu(v5V7)X*RxB@F{eH`3iD(k&oeD$)(o42^)a#DKuiIdnJQ_4mH- zKk&_BE$*7RvClsH?EO5?**8W*O#ug!0uuoN0Y^zuP7476$qfMk5r&Qmd~?BLoDcj% z@sLr{K?gp8=vL7P2(J*7;s z?7j@C<;HC2hW+Qy{f~pLx0Bv|LO4Z0V*H4TqG9W#w~+R7mmNKp=n6{ z5&z%uyol0z_`f4uy8pie$Sh(sbv@O=cZ}*dLx-<7f<(q|-`yBeXZ^eBRWhSnRCr#6 zC2Uw5((y?|v%BnXOHClXtHpRZQBW+yyho^iauiC?0y<;tAn{7y#m(H&pl+@ zo~Pd?P}NElpUyDeXAuIwCkiXAnA$2rZu!{Rad0TaXgTb^AKma334Ejl&%E5FS{{d7j&&SkLqIs`4RM+n|2*>b zGvm?6a^n$;u{2PKG?@2}o(!_4O3M}^o+M)YH*EKR@1N(7&^n7c%fXQY(?g~hHWi7W znCWqIv&Z2J2}FiEI{G$A<`04h7Drqo{uzXn(oZez-4rR3?BcJUaHIIti>@~C{h^1d z6mwo}8U^>Ozjegqxx|OpmOQc~|2!a>dN_lui19(Vaa-xVnE-B^+TNqc=q;bYC|Y*? z-o3lM(5n|i|4!6o;BZ6xY*;VURmRSm{b|t^Bcv>9GNa8kR>-@j-=xyfcZqGWr4e-~ zu^ceO?FTS;1h%QMX34`e_QZu(zTB#NVIsNNs=IsRss&JbRAp%rBf#Y7Liv=IupxKN zFj2KxnCnO`yVj#s^6E6T=R;w`>L+c7RfDl+)3lGcj-AWwfKQ_Plu}xd71i%fllnnb z8dWByJ+GZEJP`)H>qvhK)L#})piUG)JUjrC!-cgNW5lAd(^j)C(w*e@ea>c%1!~NU zIb7-Ma+3d>gpZ&5wC?-M^fL(~oTQG$UJm*koR+_&uemb!jG%!B{TI4sDU8lMttNCb zhrcmr-*M=l6CVVgJ58YN4I>O6=lO2pRr#Pq2e#5;-*Wu(Xd?Z9m$4mv(}>YXk3ppw zmyXaV_v|#{gV_9fWzyFBJ3LaKnSIq`%&F7IhTXiL!>;6iaf?f=wCbl8!0AiKOeSs_3AT_KA>f+IE5%Z)=wxnFu#XGWC*#q@D_QNWQ>6*?t= z^LBd5lNvnT@w_jZY!&OPH^DH-@Xw@27A|?3!Eag1(@ldPFD$D6cmUgf{AdHmvjI&V2~LGALLm;>%>?Hhv<<^N4~ zI}lt|0!Bcn%ySsBh$~C?NfAi7@+;>sxlzjw>gQ)8ka`vrz*0*L@&8LVG#QL;Iko(P zHLm6r<=Uz}P}-hd+{4o2#o)TC%OY%9^?cj2xVVa%4CW&_eXq|02^@1@L}% zqw#*Thk&~wDfce*n}@;gNwe%$H6l%ik4Z=+CjJT1jLKC;HmBo50=+#(?`d zaTG#QsiKsLMpk8Dm@?v+c2`)dEi;2O?pLZWR-}mvK^-A(62%6s;cMrGYI~#Ja!EK=Ypm`x=Kb2+J*ic zQS}SQ^BU;+D&OQ6k5%-8-9lsD74&9H@g)P%i?Z-%L|G+A@R1px$EuAfBD3MAFX|A!P)hjH$%H0Qb`LL^2<-Q zf1L8V5r5pF?U7NK_&DvK6?s)D0#ktQ#!I!ACJgm1H6B_0a#(y#ToC(gg~a7vYm?vf z_hyHbm6NNwQ&%UAkf%e1m%_nZ=bu6P@S*B{5pd4$fh|=+VZlnmz;aoF7Uo2WOYAi( z_sd4OaJ=yiS%a?A|DCSL?3R$CbQxzoZ{-U~KO+>+kr!FDY%qAM363lXrU}^%4(W)r zcH8MyccaJwz5TByJc+o!S1B~p>dJQd+YKEU*i8Zkj?xI3=#q#phQ~`jBefkrDO*Fd zY}VIHxZ?LuJTPD6%6ywO2MiQON}S1Rk#CYev~f1hi3hWzs4-5aga#$Sc`Hb;mY!~q zsdj>Om;4;V|E(gj*|jwy%uJ8-FDrgge;X?V()FaFQ|oRrJP^g*)}0d^-0vux=UPDd z8K=r(tWGY|Y@Zbm)y7Wi-ea_HdA#d7jO_hGzfoYS@1tsvByM#0hm`a2%0=7%{*bF6 z?)i)-`R?f&BUhqbDioL>VS+?C0$VO{Y0{SFe9PPN8}RW%j=D{#WMV{J4rlzbNl+Cl z=Afx>mIf!Rw-lGTMCbd%l!D6hU#XR;MVx1;XV8;&iALd+M6Alcg6O_G(f|J3dbCbv z8buA~LrV8y%F$G6zi7LzX?yiZo_a{Ele1(@!;;E`R;WH?aJh&NfajldGN(N-+|QzVB(=za2U3Z((08CD~avN z(lor93-CUuyn-4m^<)RY6lwM1NsHIIPcBpt@aELGJGtxJKm zkoZwHt-rMqwb5bhzXa$@&!if7t@OP;YTS|mUae|!7jIt|M7c0G_^YYoIGZ^wNs|6t ztShX-F1+jNQnjElJ>6SG6j-$iV{1z5j#2xK*v_e%2C=58uMM~+1I`4dJO}q32HlQy zE3<(CdsXfo*5tPqM^rdIAuAkeXT|?p@D5ST@UrEh^*NC48}>-$lX#-nKY!PqPgLjB z+2=5C6a@9siQC`K&$wE_(THAf(Xd?I!C6~oc$`h}zkB`g`QPV%8w%XtctP>jVFL$; zC-nRsWwNejV>@w0Tc>}O))0TtmKIi_Jx*bJz;rBZB=;5EIyk>dmBjk11^txnV7~iXhulr&_k@j`cOa;gtQ$`yF#;g5t zHD4Vy6Z~}ggRgR|o==i^Y5zD|@vrHb&|Qr3kGTk`=yza_fVw&Tpox&X=;T;$U0y7r zF?#AA+y{em+Gty4{?T;XEVgko5!G?V73)$|mQ)tQmQ z_s@~f{W05kqb46)1&OPsB!w>z2cva<#+4ge7Yp>IrEzqK+%kjPm0_dP*rH<|#b_{aNp<~sL-*;&@xrVm)+aYMD{Ppu)%?S>k z%aev6R>m{-(Ia-MBw_^lt~j!>t#qnOu0`SSI%7!i{lqOE=`(WT;t%aR##rBgW&Kza2(NTODogvo95dVgA$C{z8LnD%+!9 zjkD0$a`&?$Jq+>6g1;}#dAPM6A3XTFuJ3iE?y;Nep3V($P|(GL@)JYuCeU-m;z*LD z9`a0{IatTScrX)RTrHnR#%?otE$_UlO}J+G+dFok`m{j#96#{;N?|?ddFk4(>R8a` zT|?4?8_w*iVc$xMoLaPm_tz9*kMAD^yH3AW0(Db3%khoex?4iX6GnvKVr-|`XKkJk zaK_L z#Enn;@rZ?PuAQZe)=hXcZRZA75R#PAdivpaU*Pk>wO`RO@%G4h1ynT5q)yeglyIbO zXx4pmzg4x_nD7Z@MSLz$vKHUMhbj}u{~$D_l;a$lqs=wqa~MS?>}*`kP@*4bZS=z6gG- zGTrIzjZg@teZJcY8Pld#Pd;JUO%iaCbP{FWxOJ54kfb$8M!l~xTHlU3UK7234h~S4c(XI<3jZWJI?8v`J9eB# zVz!1gq+0j4KmpI+c6)QlXwf%d-|64;SI)AuhqX&%e>aXc7GI-%M}B}cha?@HY^N$7 z4bOT6ia)<@^><$Ok`=tUohrzXL8H4G3N0n5wNa)d5JoU{(I;qOc!i(Hd$H-q%pKh1 z@AS0o)q9Ha&G&mmGPPC?lPf~9^RXUew`!DY1*Lr-+%#?)K7+9#?R z4mjGSug#w%hS17HM>*Wm#A!FwZU3gMuArk{`FIf~#=dSW;fYOS7_xBF{r;?+UJUH>fDnYkG>LLJeJ{-JaHt6{tiP?9at|<8@8T^Ex68VR$TDnh?k7SF5j3Cv zi+ul2?%eMh^$|LP-GRri_G9rh3)eHKT)&y{+x7n=25R;tXXp4_a26c#XVOb;e2khd z_Pd5aoa*tV!kq|-*ssNDm-Dryx$^+T`bN%%qW5?7L5p|uz^Zn(aj9;e2u3`jh|X zmXLE25S>JL@3^VkD_fGYs6hDpMX0Gi?s3 z8ImO?$^D4kjZXHafp6A$p0Va;1kxrX`GMzs#jbK z4W4kEg8@GA6T*B7K`VCIoLveUfZ$aNA$e2a{F1t7D=~TEQx+>2<5R^9d4#si3Zjj1 z<@}CN$LMFZ176^`%=d{8}zY$QojAnxI8*c6u95`ixUO<^3*WedIU zw$E8#r%iKvb7-|YY}@kmlvHPL(yLXYliBJW5!#^MBwSB&c01YLR>#adXWYchT&tik z)h^@=KBNFgj8DUAMl*fntFt3Uo%CCAhUs_~u$(%LSqxlwMThwFCLFW-L-k&_<&{tI z@9{rmh&@O67vgqHTOk-P+%3vCq_tHwIY!_oIj>}hFZm+}w6?9a!HCn>uAJm&1?2Pn zXspMs{A|3ld)H+ETm_l*nD|t8x+1f+k<_t=eNQKdX&Zu(*oC{M<}xJ?!q5vr0EI9f zD&e+-1Rl}4v{toIOM%WjN=qvMOy8R5Vc4nK@Y*QSUa`RxNJiBxZfXm#Nj@tskG7V& zqG+Vfrz^5p?l~;E?-vDf{l&QYj~MxvCvn>bG!3mll(Df8vskI+3gVxU1g1BKVPG>4$z4N$Np zXyqHlWZgE0un3_;6LxhRg^-5M3y+SE+I6(P$mqGs)r(q$hb(hbZ@q&_2CpQg4*aPH z-J*+ynE4K6jt}}ff&w0YH^MDyDpzT#om4gChZgNs6FwS88NeLWQ>d@Ur^--Kv}?m) z78Wijm#-eDg4dsfX(vKDs+#}ht*-lDU6$Y4YMm*;Z`KB2q#!3yy^itv;Iz~)H)xW& zfKC{xzp1qLPle|MbULA;mZKxu`m&XA7vbw-FBA<=;(#*DgnQaQyI32PUpifp$|J-< zQo$jDc5ZGWr$reUEGbnul@S0m(&}n+llEI(5&-(WL23`oi>R-jB|8;kxCkE#U=lRMlX6 z()@@zLx9WHlurjqs&(BF3oOsCS0(Zeemm)-T_>X1g%(S1UP7m)(X5L8RQgsarMvj@ z8z5dFcou|>^M7sJTUkNWa+n#?Z5Y+HVVjGq)Y03;xc+>?QVQB9sziF1wyo;dF1yUB zNPMun+&B zz``&gzS0|QP?0>LeKVD$K_hHg9w{T&b?!v8fxx8bO-<7Ialm19$w{N~?kgN)H<;jJ zup*NvU<0ynon1YN$oQyKf9W_KkfU@%80d83pq0knPqWwnq#RbWF{uvZE{e&MgkMwN z&ytLN9UI0kuR~<|+PaFSeeSTS!v+n=zz(z3#wAy`JCxOwVaVa8L5(k7O33wnDyo28 zpxryaPW>(mCExW^PH9E9>ExS8DhXM-FbVllKx@(^Ghig;B1kYPJWaUb`cTI|KV0!x zqm0DTFFD_kGI^+G;%bj$ug9mu&1qq4Z`j20^6<^|ExEsY5Yy5@g2RmRp%@bTNx$9C z@q~onsxrIL)6+-1U2_3s|M5QUF3d2VfSpaF#YOkW^(6BvZJsGYG#T~MsL!2ldU9Z$ zSew%xdF1}EUy&%|8aV%gr3Nq9m_V5BYB;~DA5n*g%cW9&8TI+JC4Plq)TpcX_sr(L zgDGqOo)FE*)|@@j(|(QX7+MOgD#Mk>${U<0L&AA);Y83Mha>*lqv}bA;NwxFYY~m2 zDW3}C5u=SifJOz)-}jAW(NaHo4h~G)J3|4tM^D(M#7m2=7xK?54WR?UNtTHB?u@x# za&emRe<)7VWo29(&3R!7vI!Ckm%`tCxbV`$u7rKjeSs{Hc2LKuK9-M?)Y;gwJ^OA{ zz7wQjxTU;iF`hBD?Qt6QWy@crt#-E|9wS zjEr6Q%COI1*z`e|+f-zs$4q%#0BcG);Evc-9StfN=SU%~*asqFdT=BS=)ac)8DiHJhmdH!~JCJa@C&x zy+Qz!xw`c!u6`XTO|mx%>o<3WA2exWy}R}B<=%aW40XO?<6dzI($F`dUsy~kZr&lu zotjP%d>!ggwW8~F=0{ZE=K43$@vSD^pDkk1QqeDZUp24g{kc}Y6!&ngLm%Twe%39MVz9507kYP^0D?5wIJ98O z;b}d$9NO!fIHW|3xYkTn@*qJbr0>ERJ??j-Hl%*QO3#-!R+cZwE7s0HdfUTbPEXY} z+X>H9%n_&;-PNKclUuP}%CJ?7=NnM~ywbTxA)*Fo)_~yBSUIfp`#7X_t&QM>@NuqLBP^;`c&NJXfvHAf z7*gER$$BBRlWXEd@esWY=gqv5q@giGEb9gVoO1Xjcc*i4BWM(pY)BKe}UsX zwEb=#zr@EGnk&b@-%3ttDJo)m+EjlEzrDSshAdxqUQ4JING7cCBuEYvz9(xR?wvoJ zg#vtXx+bv5X)zIjXvH_|*Y97ieL9oPWq3MUo)Hh38<5UPAy!8)$2sXghFR|%AzF-A z3ImQOg&gNP`#4CF2`&Y2x`R}9OS-GRL@dhRTYMoWXd$&5D7dTpvlZC5xPPXm>Nc8* zkzS>!XzQEwRznd#%nLPH6To-v-K?rM;K$b#Pk-TJ`yh7_B3T8g(Px+d@;dUQ8xn=k zOud;NT>zT9_G;3{t{^=NJS16da+L^jQ*P~Ms^WU$$Z2y=HeEuCiNhPyg$OKC8n)2( z9iFFko*^3_p(yp}#>Bi3o8{kzHvX|%HboIH8`IaX37^g~a+Pi=|n5r_=q%1+;Yp%a!0E1-q|bMiR)ncW}#vE#xqSB(z9ap{;Q23%~PaI^k97< zqqCo1mJiIYWDjD-8(n9E@8g*2p*&!btS)(L#X_qa?G+gM>QOz{*vIKCZo+O}tN_DMfpPd!!F;pA^(cc*WIZpblCx))w)?R8tL_Kj=^QiyHw*m6 zyV){zHs`<6UQ|YoY7$xS9J0pb6ch~BXHSSd9QkyORQRB|m1wbbUPF$jR#sLn7V7F= z|K2*ol_g&9)LB88x_ESwSro`>4gTkV{O23DK$b+8mTF<{Egx79o0E(G?{E0geY?=L zC7w4w2HVqfK5~R$rqV7IpweA|={GlQ^LJ&mi7^FpK-J@xQo_Dq^g0LcFa5?HzHZY2 zJ!YRZhA4a7Yh39FVg!P`y}i?oxSLb)xcX7UcE)SSjHGt{uNT1KCMPGSsP^YPP=$Fe z9?o|qmMN>-i{GBQto#xjBav&2`lKZM=;3;{h_Adt4fi7EetbO|?BAstGY_JEDYfGJ z9Sa=lxUfD}fu%^p(hr;WCeUL~<88h{T@@bR$6SJTUI`vVIXa0X#?QS>QnIHb22E$6pKTFRvtn{?I&^qwcWz_VEjH!#@3pB3Q^6jn%h)+MI3A{G zA78paF6Y|lqinqY*z{NGG(A>+kb1PumouG~Yip@jvGFecH_Zg-_>cQ~Zx-ikMzV7X z&!!Z(qU{S<*#V?g@rs0zOH`SblN9o`-Gn}?HSb9w7-;4p?`TL zxm3+e5Z-lW{ekaiPY1u+<+S>>RO#ana^4dr7i;by0*ww`MrbfX^Gdiu=j_X-h~z|G zp2QyrnfhfXFejzW@OdsV`>Tp_cD-tW8id^3+|BK=oXldSG93$GwJkQgfP$K8YLZAz ze826XSNj)@K2%Yv72eP_`Vkun8Pzn2xJ^0~3x|7lm5b`DPs}U!r)~57BBx8#Yua`7 zO{}i|65F^Kop-)mkYxET23~ zrm7c8TEW5S05HKAShun%(L6e$ORwi(47i)3ahE?Y<@XP;`w}aBn_w6{cfe`D8A+1V z{HmVhAc)M?Xc|7~m0WL@aF`G~Y>? z8{&CJpuTi8vx&Ov2!WEc$jHc}V`G|}Bt92C!CQL45y{CfF9dN6h~M^jq}oLzN2;NkI%%%-3+qD$6Ci=`#+HwU@4NP^5VkLf zg+7~MYhZ1CiQG3~VWw>xoS@+dZhxNG5z;Sy!wcGL$k$b5Umv{}3p;B6gVPRS86)T&^hoEiVfRpcl=Ue*&jAOeKx>lhDH5Zu2CvSlu-BU`a)eG^D?KFItovG>K~nxnf3uyQkERHLjr9-aI%rYaRa*WVs=3T#KLNYW z5?p>B$1X{?F`!(&NZzIqhk$ z;Bp{(yLQ20+C!S+p@yK=ssg}WSBJ|4kXPO=v@0@Q?Ks2?Ee77*Yn^$&lrxNpzZYp) zBl9&ukHbe3KwD7LQOyP_i#K5aviwyt5?g|g*RatW3HedVKCs0Ez#P=&9aA5PT*W`H zed9F*BCY2@j2>!*Z`c|DMuuY37%N334+7Ngc7U1_z5VtDvcgc6JCS@u>-f(p>*s55 zc%kHLT)b*;G2HEbMt=p{0Aew5Ma_;MRp&(WUZqyu>;YU#m6&p(kU7TnWb$lfQ~II2 zEk1BVk4)Y82V3BK^izB^_86>i2CE(0JqfqAy`Z<6Cs7PP?ogwByf%b!FWv1fPegqU zKg?Q$rj;ovFJQNsue$8GNPp6xR|<9uZdCkL4W06Y9OfXb6y7}E_y@c$Vg7b1O~2EY znVPzr=afGbno-IW`N|Lbw+~_KZ%oeRlWdeIv7)XeOLQ^{<0*uV5o>mvur&9)l)H=n3m^z9bPieRol_QGfMU)N!>C zqAoaXx+cg=p};{QPn%UE5YDyapBkc2u6$Er+OrFrx2<-v{$;jZVg@_(Ac+QwI6mzM zC!?q(mFnMOpmbMbvLp2K{ZpZpaZ(E`H13!Ho$8IxrUqty7P-pbZp|E)cM3gxzj!`> zRSEqd+W@Mr7Z<6!6U|oUKU>1$ir-zeBZ~V1^RKui7Xi~fZ1GrLTpa;Xkv9GDHm>&M zg|LaK%=aMI1LBi+TMvb85S{hD*T?An3!P*W*uTqL@yCEZ1?MVYBkgPkK>wZ~tQH18?hFHW6@0~(@XMD|H^nLx_04t9TF-G=6Cw}WVaE^NV+tHh zY3jJPG}JvRiXQZ#CIc~68{HOSR*{X=nVp>?T%Cq6jM&+PuEP8(H_ySEV@*>mKgs9u+mIkRa@QF+lSHx+x5b zF6In{i?$oMf*AV3O#K-!h#Q508rDudo$qFxaj?YsZo_g0P&Z$^z6O6btkDLdC|BlOWZ2(_G`S}5#b*4Td?HRmL2obds`IQ%AbO<9 zSvG2%lN(hAsD`Uv=i-+~5ZnNY)AhaKKD?HlJm0aYJhH`TBb>u{*hLgGjg_e5%i{tZsrKVG+<0SlB7 z*D7d{`6kVsf!r}$rCcP_YV?a2`%l!5_I4>MItgAy*8J{rFvzjNppm_`^*!dhxLwIG zY5ib#NoAyD)-)rM^P{z(lBuuei~XXahExlPKkRN4?_{k6MeV!v3Hl)`T8>|@o*#QF@F~9*6fz->?WfDqTb)#SNTdwKG+iljxSgM$XF5>84btDf!hc1PK#(-(!`~TXiGlK?JmV! z?}PouCKxB`?nc;NI6nV#r->>Xrd-?CjUUkTAL(KKG$b_vh81hvS$DNB3abB5VpS&Y z7;w&!D@ARsRD3W@`qHnersllcRcuFb>YMvPpv|zZG5qK}b@zyFVKHj@g9cZX)a2p3 z5KuSjJsNh~-n=46<9QXO&zk?Wwj(^K*~h4_UV|t?k#BZ=2$vgDh%AxcotVKA z>&XY&-Jrbw{)}`B@ix-#^NSW-@C?!K1Vq0FGxHJu_R4V_u+abI z5hK*N!8k53=4Dv6+PDkcS%>}YP4uYV40f2lEos>kVt0`Nr@tYck4TfMxn1&7FIBcV zemvFDW@FylR6E^b7Clov_xC9hL4U-Yu?)l`VY3k;f-lB@5t1jUka#$gn1)Eja-&Ux zw&J9rgeG;eei)VPl}i_~bl;a@9lCXI`fCXBC;*L$$U%s>p-1}c#8VmHqWM5LhJy&x zssUax<7qtTWh^QxicVEm+?riYsOpn)MBDFWY(LQ31|Ir1c}B0gc%zQ4-y!zXZ8AA< zZwVGaw*nJApUr@cWt16LvXyRx?NRLctH^tx-6`k+*IzWjUoN<1kuVl%ibk>Eqkqpm zc&zsij>`Zy=YY^ye;8`8tfi11li_PkqTLi4_wQqXIU`nlUua4-__4#}3*YGJk#;f| z$IO)krg!+Hg*SYG9#76hvLX^5`( zISN;PQ6a(f0sw}bqVD9|`*}Bl=Gt0mNN2Ec)5`H+J*R&_z*N%BTuiwgu!@zgmsPi8 z;S-|^#Y)cRiM?m^oznOritOXK$Zs{#2MH^IN)bl-3gEidxy>OzesVS{}PGG36SDwBC>2PN-MU(1d=&Vw^2@6Q- zotrheDQ`3n>+sSW+Z$xzbk(9&oMmrg(h3t6*z7bA+K6v^cHwUm25W6>pn0^A!C}(c z;$mQ1P$Ox+F3z~5)MQHbPFSbjEbVJO(g;WzPg+q|5K5sEkvRe_&BOuJCsb{^2mgRT z9)d$B1*Kf;_oEXNHSOt&jI2bMtg$j7A$mpK09JKP+kz=mE`HJLmA~A}u!e zRw@A0S65drCmv5u;n1EQ(WERx^e-tImFG?MVo?g+JnbyqR#E6Re>=## z3vyzCr_otbxDpReT71;Ty(k3IGjb$1bl7JGoeKvxK16kNZFXwtMC18BZn2Zs{?>SZ zWspKf$1~;Nfhb$Zzi%7Zs?rL3W!fm5p8g5n%@g3y|JL3J&{7LzfgvkCKqwZq3b0B8 zc-Zb96Ko*?Tw|d-SED#HV$C<5I-jm2oG(4Q`ReEmff^(9GLZv_^P(a1!T2NRi$sCB z2dbsz?DvkzSMGrSue)!DzI{qO4iA?|Mn4Lb5#j%1K3%81OJD% zH@wWq^LU>W>6N^lNp_BQ0wG59xr)j~rwkgN)IffUU5SF!&j0kE733Nf^Ko^egfwXD zZZ*lyzIwg;$j;?|sHlAYxfS`_c+(LVlp0H;^8IEx2@u`ObqMBNl|SMNtre7(E-o(G zpvj6T1rrLA1uXwlfyFu*21(IVXvlhLakaTfK2$2j0v+N&lDZx63+(xPk?HXIt>)>A zPn)DidR7@8B7efPHcv_~JSkS{=qd+ZETP@0BCX0;`n_-nL=vQtjT=Jw;`Ca^WG!sF zy?wyo5|g&FJp#|^uc7lRa*IxlA}tpHl<=okKlM8aio;T8X&g z>_E4ylxXZ?ZJk~^l=x|B!+>P2A0;6Wx3J({+hH()1$%xOab)xEVQ;dA5TxSZ00TZEIIl&`tquWLl8DZ>M+@s z>UWKqrl8*=<+J+v`GA~=K0x^4ETNLAH-?deKeZwRlopt-bNulkNE{bPmwP?CN58TQ zT>fg~cC!(ct#n3whx0W#v+g0whgA2cAF6%c`wL#RgR=Y9$!ILpK$^mzIMv8eKj{T5E9;>*}!(5!n|J za7+^ldxyEw)7eH`W!aFe%7_G9N0E_^+DFK#yEq_=A^z-02(#93T``g=;JTEmki0kHbkTztP3M{Q{Fu~w|8Wy($ zZNvsfy$Anw92L8@Or7x4=RgKuqu65ei%WB$50!^&qnhpR{YVw`^`P^{7mg2QM6nn8 zfx_UZ&DS*sjlyUN6q_Yqd3W;CrWbb{yoXAX(Qg46RHJfX#wn^ZoKrly&uLL<>Fn$* z@`@f%wK%!B%(Iz|jg4;twR$0xz^fpDw*O6ki6gkSayFoPL&NAjpke_ah46FO%Ds#x z5z;r_*4x%uhb^OY+^o%7hZzm@=hKa^W%DB=svP==6s=U3InAz=LjLR#XQdJ(#?3*0 zU2h5}{e0GC{T9S{nmw2AAEVm;ZcosW2uun@+y*A3)hl(EB;$@;bGi8f^01-4ez!rY z3Xm+@+S>GujQX3L+S=Qvw&EwN&!T#Pj+W3IpO@z>rp|g zcz(nKm$A+C01AyoO127cQaxmQ3+S=^pg?S~3UaXKR35u zkZZ9c*XR7k&=wa&Di2wajVjK349>_Spf>TUw$@ z5LA-mC1cD}YXHzp;ndfX5;WCf+=Cc10r|mI{PJ>5woNx^rN;cFCqHXtuZLg9H1`gh z-40PZL!XRe?>_T>GD$Ui3t2R*Ue8N&n1S?034IWj{ES_vQ?6aUpz;p>(k&WrUrtum z`)g5(gcL=_%$%G)H>$h)duu~GJhoV6;Vk-Dspt)XQerIlkzU*jU7O-bfdn&7?hw*| z{t89#9I?pEZ>AK8Q#$$qAy+a01*iu(0zY*2VWvk2N+gI#M66#+31l_s>GHb3df7-$ zsik1STq;BZVuTqK5ofW@5CfA>X@)Rt-RCJ6Qo&42zO*up2C8C@KmKx5YKzM2oFn#s z8MsN}UWWFfY6IRPxSkle zs~D?IY8pB^I*ttZvKXmw`NhQIitR2ghE#?he^8>v_ZftrvVJw0R%a#BL_No~y{ z-{06U>06civ~OE5HMDgkrCm{Yef72JK2r=FHG>{51|ebe#&IWvVH#HsI?xBAyueNX z)M+3G4gj0Z!WX}+NoA>UffO(h@zfQ`pepQDZ@b_l*_voA0`FgIS#N z>63Trf3+RZR&J2qJk)PBJM_l%-_b|OB|F0oE@l#<%edNv;k! z6D%+sEG+t*pl;3JRgK>>wOnWoHkM$@((F(EGvk^sEP%3V+!bQtyce0V`L@k~dO1HD z#SUx89Z`U}<1!V-pE%W_v-$3#5{)-y1>v(_Do|3Dw2x zY~RG@l@Xnd8bMSpL)Xzx#yxOygS4_|j#B>b1)IFxJ?q_J;Kd)!0Cy)!56AesgdAZ! z0VdNCkmx57Z`%zVRff}dUFfO=Cle<0Py!_=dcY!A+|OMdnOH0%E6?U>4(9-^DTnASorJL5^{&!;L4TF% z4cAK+mzsNi$=b$!@xtE)*E_iNtMJAprFAcLis52jlw!09hGz4}-aN7zTy{y{D zz19@;Nc7oePvPt#$AL9JXDm?RwA3%UD+Mzhh)BuD@N&5#)df(yF3z_9;&mAVd7)_kNXtNDinD4}Xw)^r`wn zP@2Q8070bapAvG7M!i_MfrZK>;`~~W>X**}S?4!8q8F8AWn($0$j*(iQ!7yvz{Bk# zx}K!E=1&K6+td1JXLe~~3hfmRD7$DrCQh3aYa5_c9Dr+S>KfeJivLjJ@iplbTL=y5 zaU~XQ-NXoIHZ>k~c`uRFiZaZ$8e*`eQs7F4u#TScKt?CEC(KahSR5KHl5+rldNDgv z0h#C@$IcaLKDt~QgSU)tV}#910qf4~fXq1vXw?lEJ#{;K2Zr4|awI*RNQKNoY0 zdon+NH>I@vLY9KSa+3Xz+sbL`_+KgL1Ftv%%_0%wYnnutPs*X6WNd6=;m41eOT9}Z z$8Q7(<9{h$F4s8!R85T#v*e0btOP$^Ogl;Jgj*P;3I3w{zg~bFI7X$xIm#00q|#L+ z@E7Cb42xV}e)dd#IAiuOg|c&Xr%9b-qT^1d8}q)f4SwlgaQe#=oW8mr5;>rt9*mbA zYW2C~4uX{Uj^D4iA?KQj=sTFk-_`O^XkX%57iPtD#KY$EIOH1;OvrVb zwgRM4fK!qSd*GVZjs@5rN>9X0TkY)V23&Hf#siyfU!3+yJbqhKaAc_-bFAS%O=&(1 zCTVlGs~AIS_ZoN}ATQe@8A{vko*R5t-neh?nXhym-+PZsEK7)(qmpgbl2abD()fk? zup|?CF{{4+0#4@|VKOW}bWeN7G*VRmgZ*87CA$(+JLB&rMiUxQ_(%THaGCA)t&Z{G_#z^Yt5{e`!3v><#?4w++q=LvN&OsZRc*E^ z{78RBE_;@iUqrV$Xg&N$m z$Xm`;Ga){cK201ZQsm65^;)wy!4GEXGVgyg%AL<^;+4ow zaaOs-w+&7HKbpQWAj28^sWXP6Z(GX20fus*Si*EL2;odI^m#OZK#X zPH!wpRR6dA4Uqr!yrv9yu;{jc@Q8Dd$g_W4_hyIpt?7DF^y?Lxc{c~8w6u$Uc?2F*vg|F?D~y-> zyZh0C3zhU6ZkdwcB=+3_>z@Rbb!XoTzK3an*8J`bT>XSkb`-TwT=HK991bpiCxmY| z3z#wc%SPD1Wz%KmB`GW@V@P5ITt_Bcjzat|_v`Bf_viVF;gk8B@tP6C)1u+3(9wV$ zT#+!INTEbZ5hc&giMF%avGZ_ojo!8H&@clo6R6Evd4+?MlSNZwR zI@%m&CUDHW`L2AJZs`sftekpea03?bU^WD{F6TiNG>4fRYz(Yhgq?6%Sk?9dOy&zIF$$-2%Vo9TCC;g{Gru!^Jd}9gyMjP`q<)Yn%ZlPH)pHQx>K+-nF*qDl z>lk$lCz^=8SNaZnbE&1>A0y}hQ`e$`QQKq|(6zDH9t=+%cFtb)kY{A!Nja|I`dY^L zNj9-?apS(t1&{w&&iT$5yvDCG_igQ+yOtbVHRO5eWU9YV?_yopn|j|GgMs9>LL{*d zP|^ocUXjF8vk{aR2qDBqFiP|CZPA>&u#@(LzBQ6!=145P&YJ{G&m7J>Tm)a@CwqHC z2@7h)Sj;l}KTK4GZtn}-t9)xZD~rRt6&sgxTs?G=phU$?2W$0yb^gw*5!YK~+xo3i zM+*gz?Zt=4e@573vu;SpnosDOj}2x(+j*#C5-s6+;gF@@u^x67*Q0*one=5+;pjI! zTt*Nt!j|8APAW%LH3?0^RHkOv<4`$fZ8PV=^xOTTQff!>*u9F*(~bg;H4CW>4$~5W zWFCI<{Vd0i&t7(!Oz?+Cbz4yBlz}xt@dE>D?K8y&#oBhx&WX>)o~h~U%`H1SK1==Y z9}lGRmr@ryqUe`$1K!)>A4XXvPa;cxCYvU8+P;D7u@2R_IwpwG(WENmq5HQpcgjNd z-P>NjKb@pzDujN9C$mZF-dZ^mP>tH#Zj4(edD?? zieXpX0V;Y9UUHZgI~tsvG&t=4+sP(P|nX6zK@8JGbj@Qy3Jk7P$U#E63 z5TeUvC{gcVV6*mr*zIzI4Iqh`FFO{Ds^-FOY<@d~UF`guEnT@a82s8cy|q`Yk@^XfK0fY{jD+Dm9}dr1Njwa>-HFFlM+B}}LhVf`#w`LI+uKIKo{ zu1zN8d?oD)VBDbQJngnUucD$cG_nIf#{?3r4bS4^=dc=pNq6T*Xw zOzDue+KvKB`FqZiNZAq+q(p`w>|@D;Efe=-NETWuaI1kh`>mkiDsfV>FmaJXGlAEK zT04BteGVc-W!%bvAIR__4cVG)eI+HXH1}_}-0!KPl`KEmNnDP-iq@z;})MGW9g9^R1WzAAUwg29T}UIdwuo^vZ~aF#a91A(q>O5| zu4u-N-$lI0?8Wiu{i$(%kgaFRWL4MNLG2DLnkriZbnzVz`hNkp7hkimFl4bXi z&*4DKYvD{-+HpJ&H6whQp`&b8o!mAaXiyeks)M|)?*5e=?~ae$e;)Q`!jeO)?EByN zWR;~)hvF{NWQycmq_W-oxG%)_gw+l<(DsCQV=FS3n48n%EL!T;P`b!=X=G> zG3gbOkah8(M^W2nfpWZ7g2ZjN10!giuwa-or8=3q1;+>ymTO~Uo1>vZi zgZL<>1_#6?mE2Y=NpJ&zl+9b&Oh}+nOB1U;N-Fqd1b4IE-TBDK1=s#rJuUij1svuF z*5OWnXZz5LajtCp>{_y`2a(X~BrE>j{4M{K0)4nRwn-yFuGbT)#>ow*x|Oi}=s|eTjTExk|}DCM*p}7ym5q z2LuGrg?1coqO0|Ij9MYS>du;se4!PB(g)%2!e^ebzVFN%2aVgovVkGjfV%VFy|VhW z6b`O-*+C8Ff>D{D#2hq-rLECB1tc^ zW=Nqp(nNYE(ux1BxMCaG0&^lS+>{U$6ck1`o4k_Abbc8Q zn{=qDtJ^sah`lJ0agX?S#My}FJM;$>>ZfYge$6-N*q&kHpt^$_r1;VEOeKnq zjknSYLHPdpNtJs?3crj>0_P5&s<*45lUY;pKL|(=BY#3gs)xO;t&2i71WD2cbT&6$* zzEnt1R7iBYJ+m+XNuqSR5g$wtr(b_uSFbI&!NsT zE?!HU8U*_e#}u=#zbi7TN)>HmyEdfsb79>^Tlnj$>B6RP1bK5 zhYbnX*${HSC=!}Asm@Ci4K9QGe`gdG^dr69afG^runL(m%O(oi>?NfLDgF>zpQ<2j zi%a(S;!xf9{^?*uI6;(y2f4o)hPA?oPf%1>(tKw36ua+}zzmR=qAP-=9ND-0v!6Q@ zYN<1@d`Ov@VMJ(0luUe6cVdZYX)+GIM@hE$9w8u9u_OGj2EHcE@@F|-c1{&GfpXAY zs_`xRbeP1zsx;Zn{G+E&95LAqp_rH`ChVcC;=3QlB6|pQ`+F*7 zaWK4m3M&FseG;&BTn>N+jS~Tz_^tpN(N4&~otOOKyjN2qv%47MH@Ps|zB)0nD1GrD zdxm76GCpqFOh$x7?cxy=^!%fwxx0itJ`Sz>q$LL4#1yX?&mo#)6&FJ=2c`*`b!Yp7 zVb<>b>X2z8NI)JI#_HBXycS(TKUCiPS#D&8=C$`6a%FOcs58>LeH6c=HRMaTxOt!Zlnas?)T#!?T=cQGD^h~%WpU94hi(h$K17pvE zxYVT>*#lJLM@4T6gTW+3K`3cAj}4JMo?kbktAO`hS?2V*Yw6gdg;5(De$jez9vOk% z{&Ay8zCuu^lSZ-%RnlO>o_P6vql3A;32A_UA#z{zcy!#$^Yb4Rj>3Tfc&y$sylx8x1Is z2hW|Pfc1-X8NSuIuOOS0I?8?+DvP&4W(-u4J-w&tb#sb{-bGBKB$}1(<&dF150ARK zly*IN=)09iWKH4gp8HNciYTlW{yTJW&pYBS3QX@MZPe1}%l4VK_O+8P=ga=!{A&N#6tI}s zbw*~`4QfToZ*uA#AecV$_~050Cco9mHxqd-WTB0kf+shv$O@O9U!dGVkoS6$>D_O^ z;F*~ho0|f2o1gWC^)iU9_(Ej>|nHwA(#PIpT>H$GGRN7ccd+Fz+Khgn; zTzVM3&d;{>xmFf2VS^WPq!)al`8Va0V>5Sal>*iGpYLV++c+ zjonVnl}|$H+v7)UbOz{+Ce&Q3X1s_}O8C=x_!Idk4kq>_NM+io!qC9gN~E)=tD%kT z?d>})s(F}d8!=9g7P~57Q`0lk%%ste8voS}?PzqS6HeLf8LU?r>PZ*w-Si67ULt;>( za-4)`5=derzduqrF)>MooRD;a*(37(spP?g|7f|QIS!6OW+s;2g-;ZC-uAzKqD}Vd zCLew_p>d|HEyMvDTVs^ypFezMS&JV3iMM5@a{pUHLOfnJn-U-)SNmH> z<7`;>C5Zmq0SYN_#X$>G<<+V`c|$6U0^_^U22!g9JjQJ)lm4I=Hem_)^bMy>Fkka$ z84uGgtq;X$kuenBZ4W}aE-I%9oYM%g?gmBLB!LHJ2_>xxEm`CY6MJH{8tiJLHTk*Y z-Nq$yThytefYl$S$)?T*Gnz1YNlmNpLyzp5^JjPNsEUI*U#_{?8mKvYg%dfezH9-A z)sLGoP7Gu#@3zIN#L&z-37WzUy0xUdTvYQ67dL zfA-m;nHBql|I@OX(YsKSp;<26PjaB^93skjCfzjg@w2Lmkb#1*)xiECZb5(0UFo` z^XkVr--QtIWd(^SwSVx-73@Gl&onDdD)UhY--JbkS)l`jc=pVZ=Dh7mA>CpKU}&A z;c~Xf-eE3-E?-Ah7e7)u&(%1sXKn%GyTm|&D2Lx**j|YB?o#y<_)9Aqxn;EKZa?_F zl*ar(V&=w}u5H}M{aenP(zf$@T|eBKi!D0*D+eDaWZmUv zi-N#%n)mg{1S_dQLw)9`?p)V;d3kTND)eyvy1uuNbanqdqBnc_6>(Ca5X40kMn;U8 z?~M_UgkL=21jysg>+@Bh>vUq&VaW9XUm#wisYt8|Lve!HN}VrK;-Yo(x-q4Yn(r!d zQYG6==JuvO`=3wJk%_-O=hyxUjgqx1D<7JcVI>N-C*N7s7{MZmQE{)@l=6bIR{Y=} z=NA-rUtgb@ck*r80Hp{;;uLB~6)mJS*&g%+Do)^(Ay@bI@#UY#CH2c|$oo`HZ^p8= zrHsym*ZlFe?1jeZK>%Z%>~@TLZ{P``@PlQ^0xDAl*A8Ac9A1+9|2}OC139Gh4W>KE zYf&#w3b06J%$@p^hmAsm#X$H!Bk_QyB}^P)V#f#e6KS=X1Gbq`GQV>FlL%EqL!^Zv zx1V>coMUE_IZ_?|eYY6$5ogZYwPm`4P1cw5CX5P(S& zU0v71evo+2(vF%7879lBd79*YhT0k1`x92UhSzY)3rn_OISw&O0}H0|$oM{amSHc% zp%HHFmc|980*$W8_p{5c&rNfF~zd9zQ#y4>!0c%5ctNs z&Nm~0e89_JFm zyixe!`}X~USlkwu8^Dl*`8~*JA&L!ZIN4hOTGH&DX9Hc`kG8I!ULY8*@q$Yy^&mDzMcb0Ps!sRMd#l~o@ z5DXQ+{~{R|1{*cmk``B^Ry0wz6@6FP8euv1abuDr*7t1q@)uDEUL!094hd{tSaz`B zi+?U1Bqp1@2?{Q(&(-EWew>D}&OV)aLQl!&#pQ!La2q*^0vlqBOkQ>VBZ1jCtw1Lw zFoy!f0gr{6CNX}yO*SV^EFNb}X}dyrgQ?g@DUJQx0&{}V!E1{p^>8jBB72-55OC(*H^hN)f z-=iMcuT8hJGlM{M?69r*qh(>Lr$=lc&R9!jdCLqX>!L8hy|!x?XwE-G1gNe>5(L%i zHqR~M0s;&4J~uCfNDNBZEUM2=^zW%5^Cuc zy<)WP`k}HuiDyedD!^DeY&y8DHeh`dh~{xkH7mA95o64boXX6fy|b^>9sd*&TsVmg zD51UK`KD&RvjAqj>6*C#d{3C$jt&w#Mh5&zZ<#nAPQiz)MXvt~NYnd-d8jhF5i16$ zXXwxW<{sgjHb$c0%|@6Z&z_xGi=%N{I#rM6sa7rq(ZjRhd$Xt&6=Duf+KpRcOd!J# z6X#&vhpunR)YgJJw``7UL<6B3!jk$d5VS*rT}u_D*>5%V`&`rGH;Ikcnk*a}4&s!$ z)#KFO#F;TF9vDpq!z}}4{6%18<)3b0wZfBgKFt;_?(4_)hGHTsvv;nP) zbEg;Od=L+Ix#;IVdr(#R`k+Ab+ddhaIC#g^c*Epc1SvfMGmN_stDb_|FD{9J7$1}r z412Ewy&DG59v>18d_!d+iRTg3c+E}Lj=>yc@*)+QB?89{!+lSKXWe=2bk5;yDMnd{ zEv0Q=&uz7F3qqUS&tr~IzSkxE7a5b})dc!i-4|l=uQ#zyF)ZaEh{dLt5hX{L2F1qC z!awdxOLyMgZ6S}~2!C%MKdi*XJ=+`x8*GY;RNq;!m|tz{Qcf*8tiN7CG>aUippkV< zY-D5?_;GwKhp#Iu2@iy4EUFkcbDfZ!K5gx2B1tQOB3>wucrK{P;$7w_8E$x0h>W0A zjOhe=X2zo*)u8!C)KDmas}4yjfpxq_!O;zenIr7VRB=jLf1K*Cjfy6S$kPB#0uE9( zRO8UqUMV@_XN4CFk>)mYM-)_oA65RO&xvj>drfvb$vVmiN}dgLiW36ga`?cm7LE_( z$4>uP`wbYs*WV8?W3Fsf^ne_-?>KsjRDAFKp5Y9=plh+IT3xxmc9v-JY&J{JFwWgt+k5&kFKf|GwJ3}Y7R=Y6_u5&!j7GE#0i^<_Rlo*A|gWVYYi@21cr1OnJW0xuDR0A z(k90mQ@TmNI0+IZ(gm-l?#+{B|Mus;*`kRTrQN`;jL17hj|KTqD9%9{817iXle9ie zOLsF?Hx4#R9CXGPg12T;+a&GNxsYFZSWJ~XF{>VHsxG4OT-h6}%RWa7{?Ba+POdYi2<*K}2BdtOcTcNEx?HZKdE~$BjJid0LHSXHEtTz) zmBCFNk4x*Bo^r5B5Np-X&$6^5(~U2e2ffepWOnGLs|JHSSvg2Z7RBt>1)6lrq07&x zjM4Nhp27S6-ux%~@1Ucboud>67ZMDyKh&9!N*NPY32xOlr_Ag77VdopyspFz2J=YW z>|M`8G0zuGv=Ws`h+-^DXQ%8}gzQx9>*uALSSz~Q{pw{_r)qY!n`e&^{Qjfp|BnTT z@7!KEDs`SGLI-X@RipR!a!&yX5KDEcG#$~AQdy{Y(k7x-`2;CbO2+I+8sk#Qm>X%y zE@j1B9U2O5(gP9InBu6X!kv$YGn4F_z08R}7zd;wVC?xY!_^+0HlYLApRXX~h`4Uj z>&jFV85Fd9ze6TGE!2ouA@Dx>=0Tp93H0&)6#Sp#4Nrq)vIQ61UzIAy7kEx_Drw~8 zJKMH<`K5Z>{Rj@f+P=Sq=p?@y*~956e6S?QR^g=bPC!tk7Y#mdz!RAX)OUIX75BbB za7(}DSMBw&iu*oOBGO*4e!k_FguP<-EKzc9J@?r>4)US_@}b}ZqbHE!&?&85*>r;w z^VrTmPohMm_pjQnjfvWCj8ajpWI*@Muw=y*eI~mi&YaPsn}!z>;-W3iij9KmnslYg z3sh@#dX}qsr9%9i8AuIu$9w4c53Q`! zgQP#ZWh>=$e7$^AO4&3$HBT+aXi3`U+dOssTc3p>OF!#c>Z}Pl@3@56!?ro%drn)y ziXcv$UrV^Ue!q~3KX+A}N(dG!s*IwPOEOR=c3bR=D&lT+?(2RUThXHKU~!7xJ#KK)n{CK3)(~y~BR7AnqW0(l2H=Hr?>5QbD_4p8aT`L@CEw~L&E;q(KsQ{gIJ2+M;@Hb~zU zPEzcjrdx96>+lP&z2jQHZNPrq)OLn)Bn|F3mX}SKPLnQLb%m3st{$AzH(ubY%^j?f zbn+)nEK7)k#vUFY@dg;bj1N~=-RkoX)}N+jDrI5cA``EY$fHpUXL7Aea$lAs^8bN( z>@F2y6QcCk>6XvvR@VkKLu0gYLU}O3PwaEKz({R;Gb_UdSTJ2O)e{bBkae!?jMLK*H`%zk(9;My#=u5yr z3o`<*N|N!4Fz}`uE1S}~!;KB`#*3bfE!X!NiLrSZW}%UNzEf{t$qdYL91EyhKSSr$ z-=CUA?8Xr>-3QUgZHR5Dm``enoC#*;W4TU#_1kc!hX9j}^#TD^;258mwvM24ZM8u- zmhzWtPF7eh>vV^l)>4swFO_#fCMZSfCy$2Cr8sGP)@AQqp1@`?Z#g)gu1NLTt7EOK zdC}SR#jFE$i?5!1)+~N5>?*f4q?tYw8Lv-=Kj;)#hixepDI_v&@cf@2CFfEmfp@kk}?b$WllZ5$+4@>b#n`23Jd{A5C>B_AnPu+USd}H94<{LM~^M# zugcY)zkJmtGvvS^Yg;RaJ2JX5G~Y#+SNJjgt%*m?cZMs0m-a~rcV@LZC6Vi@DIIcK zx*kpU;P?A-TgXKz@kH77rC@($^ysiSbKn^>-eB7|PX?BhW?r@}KHBayeFRNrMwaCo zu|cp+e$0~Qi@xp)(y5P$S9`QM>%U<9`!BENo&TI6Jju8}Ut(|Z>LumYH%xQ00!b9l z-d|sa7t|MHwJ#%I?nUW{hyqPi`DR8D^HG)m?(26OB`lE5VNT5E|C?(cX=7-7>*3*F z>l(3s5sF`kh*a%~d^l`m@yzA=_S@Wfe&{`;m@URSmKzer+a2`qs+Z0mHqxFt@FGrc z*Q08JnJ=syrhz1>qi_#LSAG|WpIiSf?bce^r;KoDjMJvS2t5jIOjOfUcO@eiF0DP# z(X!iqdUILc;&j5i(RNA3R_A@0&<%9mVOO*1epD?AoW0P*m&BX3!2`ul+~YJiz1CdPk z!pLOK3i$&`W-lD~JVgR`M!kC#6i-)}yDO$W$kBE>Y4=^^w#ZBy;s2Z({v&I#eet9q++yJ;`3J9uND6))&t2x6J4jL%mT<)@$>WN%okVnE zmjNea!KEp&Vm+Sl8B371Ag2#6H_SEEi9D5&pq<5ak#yoOyE5Rr(cRdEN;<0_Y@JAT zJJ2IaKC9kQG8qh1$}mXv;*{bYl_ZB~p_$3@x)jeGgxKRH~M95)HJol$DT@1v> z5BQ1y<|7p%Rhq+d-ejRdWEcOeSLYa5ohFbI^lacZId3C`x!0)AYUjRa;ukmrQ8+ZD zv6C_@X{a}!YbII6wbecSl!gGT_|~XcdulB8v7Cd+>Ez)=`asI0D@&W{QvfZ zxdnYnYfmo!8>B7zCCY4SK}ViBFm^xShsmoSCY4*7)D~^x!9%w+Qs??ugzS~=_l(zg za0^0ai1YR-nEt)HkJ#wS!hlsI5N?^eCY9T9+;XD!cTz?aZ$$2h$!pvxntM@4WJB&Z z7O00m&;C7Em$~#&hArXn=){l9?AGmc(s~VztS8{8g$IvZ9!$l?yX{T3g{IzmUE`2u zoq`@7xfM^V|F!JopWhC1*Y-GXYNdDlWKcM&FUg<;NC?-xuS~{A#*m5?1BoZg`^T|$ zS0-P)Xhl|6PP3C%d zzDx!EHfMOLPN{M#!#8pQ#N1R5ARM#6{r3P1!!})4sDQIiF0S)JJ4){Ib8N?|p(}w1 zXAzCumb5MT?AdmD3u3H|aA)}^QKBlgwu2wXvRdktL+icZ3k6H@9X0mzvrp0cKG!DJ z)j@SaTc1412|jZE<)LRw`65Zaw4|&{4-bqPrwqO?*(egIftQiR6g2VncSp1s|HGO_ zJBB^w71eN?(NnIgmEDfp>r%s@?b0A>lj~QUC44=r0su(#cRt~yMM$qz#=c&Lx&qc{ z4_u!1qV}y&o#iHyqs33- zBL}c>9$SfK0I*6sP`lIN{Kla>K}JcE@%S)1vU{-t6HRWh>h+}k-UK7fAB;_0Fn~4i z9T}WIeEewso1K>z%aKV)+mYg4k7?LYZ*8XNp6^+|Y{;uy>AlotT0Z{(CqzyOaVQG@ zvsf;<_-C6Svf$Cs40wFUqjMwo;IFr^pm0P8EKh%m$fP*_nVRBOx!*qAeW ziO~@9us8jzkcFUcw6{6%pQYcwB89{Z+bx2j{quXNrj_$few9Bfktku?lDgXc;Q3Iupen9k&9vS;(z?=h_ z)jxtwzlnL^2CUqQ^uiR#35FQlvOkf#O#7@ZFq*awwNep<2Lo>Dz`6&}FEXKZ+%w$` z9zE80_>7UQ>*mA2z+P_9zB>K+5jHdy0DER&E~0JgWw7J1t%D4=9YI|Y{jba%hvuJu z6MJH$LjnQ~F(5;T8p`NGgC(_Is@3{6h-WOh4fbHREOs5vqw_Svz%s9Rd*m3|53#vd zZ9&*JeZkL$yfVVQ^|uRi)@Oj@yUb9zLLtW(7>P@&9AKAKLMRgTwV>pik;sk;yYH^+ zFFn9UV9Ephl&F{5o&3+kDHq8J%zkrfDDrP}BI6#(#Hz`2**#vqP#`0zA{0PP|_CoK`=;(GTx)XDAW z4W8_|?yY1*a)ho3Y&oQii+SgV4N(f z0a%hN&}tFr`BC5)xSB(5ajQx)XL|TL3N=7`GZF-qqbZ z^^r;LT0Y%f-UdF~ZlRjiU$H;_(P!N+YPu)!mB-%bg1E&b#kLGVgi(Zc>z`xWM?#h?W?-LmtBl42hNIb^hy#nOc$ za6S?|vCr#@oq4OPcQ^FVKuYa;B!u)I=-K-;kr-2{IUo+aN*B9I|F8)z{39oaVJ1}x zk1$hqR4G;0i)%N`QFYIw2_uXseuJ8L%=Z4UH-Ge(=xg-wipL^Jhz9RwP>+@sP8GT0 z&$&;_hlS5bnzZj}KbUWcp=MhQy0NjDgxnPUy919(B`b?T)*H8VCNzm+|8yi&UU^Pf59l?NWi)7x8=* z9;qD$1s|=sKK0;hDNjHkrLANby^WnMpXx*GNt zg=Fr)R$VWaMr+Cc0PwRbIIX|fB$(Z&$5Q;j`Y?DtcaqpyHhR2^$ijQefSvTaudAF8 z{3Pz(gps{1wt!hCOLNvIW?-JEa-Q_Q_u=?A@~|`j-k2yW`X+S_`h~ukx91^{5|$0* zR|JLP?v?=WRjrUxb@Wc@vW<*PqQ*>b+$H^Dfrxl$MQgRPHy}ZjfUIE9$vErV`gllj zpAW>Bch%!}JJ}9O^JjK@lg;$oGyrS6eUidj@sTrY^B@RHj@p_rlpO>%;c$6udcl25 zJ^RrI%R$Hn&CiCO7rzU_qJ$fTip86AjqzA*;kEdP@p(4R!cfhKEYBOA4cc6_Ry@?SZAa32Qyk7_U3 zc_O^hA`E%s4T4DH$rtBqGw7BQZ>EC!x!Vp%YDhvaaF0v_Gv>~wZ;1d$Y^xLVhzF__kxGC-WDrLB^OQ|YC8hC z5*kn``HU%{aG3%#lleM8791E-xSmDTSx&!YZ0E>?$O%1p!B|lq3x}KwB&b3fY2}1s z0XH&V`)Q)e;*sBwCti^K^xL@v^2P6$!`J!+aSv7m<*(GZY06K?tHx|s)zd${TWlzw z9zJ*n0##2sc%tKam(*r;9=hTHDjZ1Xlyl(kg&My2Oewb&sY@WICmiw}0i9)a7E0wh zz!JdL+-e%FB?%V+NX&ZKTxEhkg&Zt@(uWiBPc8jMZzzA%Tl`*l5Ll*9v@lh}FOF zyWw^;`of;;dY6TMZFDauIvMgP~{lPfx?jLnF_9W@TlU{cs z)Gdv+4n&EUoS+=^G0P{HC#31dj~01olri&j+FWB*Z>o*>loQnM&RAfwMl@elqU{-c z%B<*n{+0BOlIZE>rQ^4CC6H$nnuNx#8dmFY$@Issy-3o&u#av4(u^hRNvYC@jtt7!~)8T(SKy z;GU6)R^p|{l8H5bIo{`+01OCc&+BKI;OjR&=e8(DJdyu8a<;Bu`F?F zg=nUKv;d5-Y16jzZkLRYnSB#|t`BB7!d9KsESH<{E+FIv?vP>E8Z0@0_+{ktL z65*bkH1*DN>`!7ei?v0B&Gj{?0Hk}JXWajo$?vI&8_R&WQ}l0e z;)X-XU&NpVflDIFzW;677rceo(OeUZC%~CXBFZ9cH!SznZKe(odsy< z{F{WvRhhJ2ehSpiDX&PmBU2$)q#RHi6C51uXwb z+48SiouAm~Lb?Bq;Sl+>=yaq z=z(=FL9?dU8P5%c7}zs+Nk-_4(%A|b_OO?NR9qu#Row22LaMoKZJF+?0}H2@_8FG2 zNua`0^4$7=^9{R<*B||3D#dMf<%&j_7yCM8mmQ80z%B!#RBd$?qs7wI)H0-cfex36 zC&gZ#p1jiPcOTAqtO^1)&7zXJDarePE4_xnl1wXtFJuCr%$;63uuDc(@X!bfn6!N9 zzyjEbE&YKEX=P>Q0P~!?*U$y#ZUV_NDDyCtUNF+k>OI`kd6MygWmAEmzeinv+9I^v zpgc1#t#kufO4BOMgtd`CcvOEy=TOw>ow;?Xw}Z|9zQB~+U7g;Ek@NR`pA4hoKL6O& z^ALB(&y&@Dt)qza-l^+NmKY?Z$0Tr{1g=d4O0Pu(S*%EsRYD2KnCB1A#XL9ujU4+= z;@(<$ggOttcv<$^9F8$xmfeorBQlrec#(8BUbyQk+~bEVToSK6>iTWyR6>(>kWWxT zvemW%XBcRiJ5j<_52|}UUcp$%H{O+BDlr$!eh!b_Icyr;7rrxY?nK3}YTwXI{!h}*nYuJt1{hICgdZ5r+GfZsGSQKd(DY9fVl#`yitKlMp@ zbmq3_KSm4xi zY7`$B)@L3Fna=cX-~DbeysC(>k|agYj@G-B??9ZV+3R*OC>o zz0*vU%F7v=(g)KeMZWol>x}gy=jk)hyBmXk7s(9n`0G{=ZmpU5Z<5l3m*k;I-X^}R zznG%DEOYQ@Z=-ufC0y2tVY11lvLWZ{gU9=;lIYnDoV`KBY7%cR7s=hxlT6k`V?o@Y z;8TSaduIO%jyGl?U2vV=axMqLGH?cv-I;?3$=;dJLHlZhhX&|OJ2&3s7seGVx=-&2 zhyAo%y`l2EJ$Dj0Vp&qMw^IC{alp)|U4rc)1A;va1NMF0!KRWu}yXC;%9=g56tCtttKtn%Ic zAXIhRKR8DbeYRJ({8ifT8Uh$ee!BE+6cu7yh>d9p{;1QdCJP_>mlYV7Ps6yu@Z2 zIkWWY8^q|S(aR4oUV$^=n=m~zAEr9U=gN#>2Qwc^@EGkBGf7&|Demfd>V6gbJZ=Hq zZ4s*}KlSO|T?~?#ly}i00j6&PKivV01a6`)Q+p~Y=O9U~L9eq7C@Ah+pq?E%P`v@X zS=?VrFZg_oA-5rHf9g=^+5nlg<=xC3>-JhN_q$64B-J}d6FFwVkN%Z!6Sjf4$VQ3# zSd*6Gs-7p}ZJKrV<7@-rup^Uw_}NOl)|FQfLx9?JN@dfM=Yb@x`d(YcruBakns-yb zt4V<8ckH|_7Xp;YImi@-5S2E9Xk$UKf5^?cCl+>}#w+dbExg11f&*v?;n)~jrRb$7 zBu)QJ-%^Ag@B1wslRdZ#oxVZ2govS)V%xnt>M}Zevun-JDQ9u+0R=;6>Ernb;?8+8 zXVo7_G*rB4VtLh~KB&#vQy1X7ek%bfpFNyPbpO!M3V5+(j8RZ_KbnQ!?2S`J7$s*-_W|DCKPj5QgtMFUPdW-xz=Mk?+CI~{4+%q6uoOBeh+L9e zX4}?kexOi?{QY-S|6jgS_GSo)3GW^0G&VQ>C{_5>A+L))P?m4&W89f)5haaId$ZW% zRkTQxG0`Gd{Biwj9)W1W$*tVR%|;W}bU5k=SmwD*j^>9kDH91f-j2IHO&9}Vpu*`E zoEbXx@2}A8iF{t?`x0P=SC*3$&xW^JF<7VRQxzk=Qz{H+`FX<^HIdV#RI>Er*81(>W=VRSH} zt&itPD|wJy*YbvS@2Q$CS&9uQ-Z;q__MD0`q&C*-j`3U}EfaHJL0X&%o)wh_z1AAk z8Jp#%y~hiG7wp|8##Cnf6if0oe`)$&%d=MPPCa<6sQ>@F!xH`h9CKQ&)3AgYC) z!52@Q4eqF?_!EqvVk3;@|CnwT{~7ZXWJRHfOd)5j zv}e(T$?h#MvbFoTx+@#(Hj#)0W~3-)^P5}}m6Beyu2vb~QYnuv9jF&=_!6GG5?hMr z+L}IG`bvT;{&_lCN;W2cm_g=$ljyM<8)gqxL4RpVXBaDud#PQ;91X(Z%EA0u3vv)AqNnbaTq1g;0~^IoNR&Ye2Pc=x2kbGMDc5P+tMAboxA zLVy)ugQTnO@w_4-yCW@*yhehKTleo5%me=_mNv+mB7C-m(Ked$>=fq#O^EHOv6P1L zEp=lnSje!D_qKeuT~dtU(a$*)sI6(i5;SkSPt3v&)8yc|d(#FpB5Jk1IA;z#Z(YZ> z8gyyCHpj~_INnS(1Z=7q$M)+7<)!pX8=ndn&X5Ma-s=3_SZmecQrGTnOKDX?(RcT3 z5SV2r*iE^S@Y#}n^UCYY&ObwP-|IP(Ume**R6JGQxFpE`2}&TYB8G(T`2NtpsjeZ^{(aPpAp8}k zn4xVpYK)?&DWhL{a<4Wpsz=uluV%W8gr$J7*^ajbhzXbqN)8khE2o!5 z5n87=#ntA1Na+PUy~v!bk_{j+NF#21?TID~slMP4G1H<7WZS~}W;Qvw%;hXNd~qJ^ z`taXr$=y?PXb~_Qfc8@X>5DSVYG7SwSf>HQ6HKy-26$wo3~=+z+)L}nv2G{H_H;U& z@z^y#^U+<`S?s*Bxh!ApzB4yy?0mrCt7I~&tq@p`4GI+Q{(+OS;CQqD%p>g2H!HzS zY_wO$FKz5VRj(j>w*AQKF^yuX?&h#D@35sqN<+WQsa4{!CyE1OD-Pc#@tlw z^;a??@(Zi)WHL_S<5DIu3EWp5Dqk1Mtd{TA!oCOn%CCMp>=D5MtR*{VhO>7JVk$?O zp#@#19i4EhrZLID7)&o}&L!uH*N#V&XrEGrK_9?MGFGP58 z^*6fr$p`U*Na|K$hE=tKsz#pwc_)hhhyvd70K;H%+%3lzFB2~|m78T8f8T3Y^-Lq2 zckviA=BB9+%xnBv!fABScxGV#nP&3|P)Su5e;GV^fB0ZQ55j$S!tMXl*;W5V`9$lb zrCAV=5RsM=frX_*LP3!3mhSFGbO8Z{FCev)(jnc_B`qx>F5TUAhkO5nyPy4OW8RrF z=RD_m&O0-2rM^b#@z-bqVk=%I*Z$<1%zg#qUd^NHWQ`E(T%QV;Mv6`@M~7+0cO49Q zmEwq5WkUl-;AhWe(VG_CvP!=sDry$`J8}0l9uRa{BKPk@2=SQ4_K4Iu`NaSZV|hvs zw+GIq?UvIg*jopKF$>i8sV9%^T_^hlL4tyBw6^`cP;7jeJbG2hXd50+-1Ec1L!gL0b+7bQ(HoJ=+f`_svWt?>3qxoG=NyV3Km&#_Y& zbhLH@2^=)oAejBF1lsIh$LIhUL*(RlIlSXB6Aw{+Zeol-mkrSrjKX_FEkrZrY=weICW>%PJ+!DnttFx;Fz0A+7b8yDveh>3nB#rO zhle{4`okaU$B{sxC5&`^;b8&cx6VnH>asgB)WC_nN!DaohIV44Ng^AWQ**JEiX3g6 z2Dng5kHP-C(+tSyG#EJQk}ZkAQ(VTDUbwja$? znl&8~)(7Y^s_zR6c^*HoH;S!jy70SDaw1)i2d_Q#?^NO2U_C zK=ZEP6nfu8Do}kMxtp%j%aBkuymvxK(}^1j zsht(B<;*A>tgllO@DV$gk$*^B^?sz{4Uga#?SuF&+-qw~w6!rIHtgX+C=?0{bJ&rp zn)|x!yj{ca(a_MezuAf<4yHe~Q%KtRERyf4qhhDNZYxH#Q4K?!7`cr=ebLF^7T{1> z=kwzH(tVakx&KERk56GmiW{`1IrW7mo)$$#o@9wH60-A@s-z87d8l2Qmo=W%T5ihc zB3VFRdb)=CwQ=IRucMC{TN6I2ZuyB4vYs2!pDY^aDi*P3N#V?rAX^$UQ?HopKfj

<|~``7ZZz} zYpA$mse5#i2WcOh`B%Ro#pAWw*nuZ+*xuWogRy$14`V{hpZ=VtiNp_~#?64QFT*g# zUSq$Pk*T_+ou&=~#Ovt_BlrUVjx;J;ByOT&JKcaE*oMrosFS zQ;B22PHO_oTht+@sl$fL5tq1I`qdUTXy4%1YX9kHzQJ}TL|;>+G4pThvsde9ebd_~ z^lZY^@ANrsg_SuiN&YiZ-WL7^TZ35KIL3s9G{9z>)JL=8|WAMPJ zmd)`FOsUr6V}5?6mv7(3G7gU)%Pt>{$xbmn10pMVO*@qy0)5@7)$++9@Htab@VDHT z`cmC6r>}LTwsmou&cf+k8b-21JWp}a{mCsi+`+@k+3mlluxb20y)gGy_(X$&HzAl2 zbg9(jA4t)^bFIvJDB8nt=nn^UKf{;u625Yz3B+KjWkf z8-boOu!*EFa`YYC2(#u1K!Wun^-7;9cv$6YDXO^tGwF>T_Uv-zr)WP7rrcF?Yu+{a z+FF(UFWnsb`2frQz_O?jQW3RmhP@mLW};3vL3?iG zH6{Vvl-F@O6{-iXl-vBGsOHEI|2CZt_4@afGpM%E2u(;TPdruR2D3K6saNS?e0PDh zy%U`&xLN6g2e5VN$WLZ_6Yt-#3~3%q-1H>0bFxNKmBi|6>qPzW;6>4dM#7FpYdt-P z1LW70l)_0TEpX4F-|;@Nxf#CjFBS`J>Q9va0!b$%mZsx6nXR^3LV0 z8HILbxFl!t*#1;cx5C0z-kr0=&+|nsNUJs-O?%MAvH0wjaxCkM_yNs*V@VkqjUYeY zj{OEh6&S`|Ec1_oE~mZ*!xW_nb1qGMR9cBj^{iU->|FiNss`q5qRahPobQLds!<20 z4~W2W{zPUCy}fz^j#LnJU$tQaOm6VN>f=+7fjv3J*08bwO9`S=*@G@8y5~N7m8>k2 z4F(|KKG4@2OxG5WBpH0wm0>S4&73fHe=AzTkX#h_cJ{+xWiHV%7Q|ReWu0jWCYrUI zB6v@e9k=s`U@7&aWt$m|y~wlvI#p#+B$vdgZJC+MvS9Ekhr@1eTgC9#7p@nd1}*l- z?|gH%1D5c0mo+ge8ZXx{K{hJ1@RKK5V~N)puz|mz?pauP@F6d%(up#c(#0!CQFBVQ zntrI@Lrb`o9Ou+HONoj{Bt3-75z4iTN}Frad$1kX5F)E2uQ2vSfS~`PA?>GswRO^V zcW?C})mvFUl8k=(JSw;-NrxS!;&4s6;eaViLeDA%GK!HQd)3pM{zKBx;G&*r)VvrJ zI0jQiEvZhDl{$QU%B;Z1Lv11y&RVO^{LH>ScdL5F$x+}%E#m8J!%SgnxT-Ogp}g9d zOV+@g1{n*{2aIXTW77rwpBjG{BkFkKrIlg(SFr@BaqsMP)`OjEI-6vz9vK;#!7LG! ztd&l;J8x`l>5!>n>XW^gdEv6MO_tIwzG>Q{Bp(HfLQj^VzBg(8%r8kIG04cU`MGwc zMJ7cK#>_499>G{~OMG2Cux}*wRAW<`Z4X4AHUwpg+*4-zZypoAj-nF@2yDEtm~E%chIGpaJ=T zsU%i_vD$KKT#&6{|DR4BTl^IDf1{5N%y>KYKf36zUD0RUSooBWq~>+xFbAPt=leUnv(TAl5w_vkKYyl^UtWH5KBd z1*8n{BtJ3^|9!QMUMEodUS6-`^WOREDXPTsJXSScL?e%zoxVukruU872A_+ULj^@X zpo*}{o79}IiYqV1A9qU#zwd0Y9K_IMi3T#P|hLd(> zYxLsG2{8%8?A%zn@&+qwo}88?b|Z0&uNv76ivh(2*=NyA{P&u=g-I6 zjNIj$61bBrJ9LXVXgQ+PXN6!EYgdDw$8kvh17Kdki>yBAT3C=ag1v5 zQ}wT>=hT{&$APIe^d@T5v83{)JB%eXJbtdHn8L4!fDsv3mo*-b_0cMS;#xePfS2Yy ztdm89X3#vL+H94ygQS~2_eWNHIOYEleGuCd<}XextLljSQuLqV4{`aaozxLPU!W8H z8xc%Dk5(Vto~GON+I?6#a%vF@&E))7z!-3Ta&k^7ecJ6_1`?0r&gpYCu5#MIN9a19$Pk50+;vcMjdP{t0(4HF1Vjm0) z+0@8ykV&OiwjzYH}g;ZTV2bc+WlOW$Gw-fR;NzH4GJ>5J4Efw|#6Jc;xn%f40$=y2w z6!qU@Gdc->C-l7-ZpmiVEH_JDKo_TcEI`MH;3CN~dZP+~fy0snBEq5GCO-)EXG@M2 zlMK=o-?^GvkQEeCcM8pO3~`fL@gnTJvmxJ(x+KayIyxgpz0lF#Bz}|bqzCp6l1Z37fvWW3QHdhq%qQ0>6T3ODD3Vvz;+X; z)CPnhWl*Qd{gjhp-^9u3QD7{ltl)m<&)te)VZrJO_K8Almx%(EW)QH{Q3@%ND2f|{a_?|KG;?ez?F*>|O3^!+cX~7Ws zg(@Dr2r~OiveevaGF})(hJ5G30%FBiGzT?jUO~ihZ&hW#kv~%J`Y3m|dSn=)?vAgY z`LA5v9a3S#cxLBJ^e6~=HspfP0 zh!m=NbU9+8-#2`F6g#vialJS`7TnKV`Ta8JoOHn`qRdw?<3leP5_C^j4A(1@0e`pO4ZZwHeX}jcB84*jKwtNQ) z+;e;;^IEVsizkY6TFfA$Rso%HA3O%3)ifQhAk&<8Q|`(c545260PbNpo5}{0GkV;0eZIO!+cqU$N%_(+EADJ(CwejH_Rmw% zo79ix^%fpzw2;(XJ0iD6e8R263(@P_iRb&up2=_u0e;rl^>#4&{onOe{Z=haJW;G? zXRTIaaqsUNc8I*(AO8|K*HS{h(Gdr3}6*lN)M#kd+Y(qejIHbvj1T?|Bx_h~Bi;{Mb7OZ{va# zhdeDlM3{~6p?zU&$IXi>%wk5l)iJyUy5zEsNPq{_#$#A6r(X+gEJGopb#4xGg&kV|wi%t15wfVG@V?Vv z3GI`NvXSJ!5pFJ?`W5z4#QqE-pwnylw~uBid(Tfk*}A9-1-rT7<8SVrQ;6S? z#A+JTCDdeaWaM(`3~`Rr*l2H6tjz3szS6bjp+gSTN5HthNHq#9{UJmdaC^xPe_Mqf zD!_%uaYro(m%CRhy|*^~A8P>!(D2)0AX{_w;qYaFCF!(=ef0EfWr^ts-*|{2#K7=} z#1@o7Pa=!H{b&Q{?{%#qF?D+QMlS)aI%tjYoV9GF%vFbbhKB$^C~<<7Jos!um1`rd z`X4Nyg`|^w$)_&5NN}^GS>LQC!!YgjKf)nhU^$QCRVmsZr(BvHtD! zj&<{dA*~5B{6_D}F+g+bFhUgjyc&$a4m(zsu&PnyQ=@&i8(J#>^p;1+l7oA1E-d4g zn$zQRVJV(1;BHeNO|cG`9wX~+Bc-ah1Jdz@Xur5CAW5bC6P|^Jeo)7}-*H*HJTd>l z8NIlWUBkn}(o5E$;HbxHOWmm{?Az}sk`PYl-UyIw_wS_b)r>pC$BeWT8LbJsCg5BQ zYZLqkx5jxA%(hW_Wp`bioU!g2fKbFlHGgWJyf%k5dE4UQQ#Bqq0B9Y|S$!$bAw-$C zrP~inS}*ces=7U{#oo_q6R5KnMztjxgm`DWRpssU=}~d^(p@^TyS~r-|E}Q+t`V%S zUs!~@Ou*<+-(8}i7ZsM8bG~RoBa`||vjcO1%CMEgp5Tp)3}GplS2dRo+faDpk@K9w z_v%fjlcn-z!w1t3MIo){(iG2|BtpFZ{7L-`MhhK>k=3T4u;+7m6U0#Yq=5Rp-QJV( zig0t?@XyKsWlc=DC!m?sN`|3z-%%eXEKtB-;?}+Fm8xF6=0+pl+inf{nZNTM2lSyO zu{A1>^~->5wJ|*iBwQsoaNrXK7byQMPp4SFo1K5$4Z^ZF?&f)fw_exZj5HH1z^AF@ z3`60n51+m!)zAz#EiM+M41*We#C-k~yR#=}H}VsetP8@)mdOM6e@(z4MrlRa8DTau z3WHwEF^D%bl6g7AwC8%0x0V#oMU-P{{Q%i(ejHFcLzghL`MM=>brY7DLTQpqr zd*io#&xk+Zrlr3^U3m4l_#_?yf|Gx`iHy+itA}e=3mB7s4_>lkXfT{+{Z}qFUuUPj zQEUJ-N!}T4i%E+bM^siJf^f42vPw!(iI?|pI!L(uDJGERtoaDd1^2_)_3n{ z6jJKC{_9PA&w3Zh)y`Y*Z zQJh~G=`9*~Hf!jMpA2HKs8lNL?_SFVjXXa!mrD|^lA=y&!~FMM*23ug zztQq%?)RAnhz$C?^_nxAh6weg2%0v72O=WX4cvX5r2U_>=HIt6GIr`y^g~-**Q*+(byBLUCfVL1;LypZuFK}N z&I=F-UfydNDGdr3g3AF7paBm^&@+8ZhlMw%1%*^_AFhzf_}9lh*Pw!#4O2-AF&ePx zoj<*)jPC<1Hu(*l=vXA6E#6b$#pseC^cA~xf> z%)+BYJ324@iAk9%in#vp`FYdrb%KA_;|xP@m@+p{$#YX2QNQh}lPt#&m-COdADCsr zAhFBs7X_%J4D|@w(!4`!ju*0KgS>8%*X(lgxh@+kU;~o~i^>C1dK~AcuqY&wZhNkN zZ03v%s@k*24o6F*lwu0;7N+c?EmBvP8k%ab?4P5res zbEptRr#JteYAn!Ko5;KGDp)qF+o5DIvx{ zLKdUY8qnXQK`7+Vn6b{YzcvV15H1F{R~w-BGV^#`YHr()hD=IH9v80!;R8gKG7N)5 z9$=!s`mP4Nt43b{u(;ZXMP0uUlLK6M(=E?J4GqIhcCU}kW=x16yph1`_C2Mdy zRjk>YK9`rd!oYElV_xR#|H&?P)&}3XJn-I2MnQHx8}L5;#1##Acz*R9gDap`T%FH) zZ`k=N@7c?*J?_HWd0KB?L<*^c$2Uw|Yrn==3nCCbdk%3U7h6~M$AKS-lFa)r z2|csl-Dn&9;FV2K7u7RUZ@_)*=`r_ffeO!gV=cTy7o-f1HvTQXzdig))+ry{g`;H{ zT-+2Vwoc53kz%rE?7uvg6R4Km)IWct&mLtw(c%4)6DLFng0)UGwL6zWLT>f9#a@e* zV)2OJ?r~-7S)kp{^PhWOAzV+;nVyXALzJV3{*~1J<@zZ(lAn8UmI^?jc6DcHsRZ z;L7v(?2M5*nm0IyaO1engQ0InxWh=aF6VLV_BLdwS>>`@Qe;0l58pvHk?)ZDGwt&R zumYYWS`Hd57sb&fCY8Bow8cjumlQ+{tfDlp{|O?guMf7M>$oV;#5#TzwEDg<#0&{2 zK?8Dg6xE{ITgihxfaJR2sV!6aMq>06^{{dcQhogGVU+cg#lweIO9WUtY3S0|9h6X2 zF@6~m`6^W{P70G|$O{Ab;R9-z#+-K>E8!SCyG5tncr)WZ)W88ue#d{=K^|u}d2zBHO z1Y==*R~mMUe0$qZ3VT~!DcPC=j1U3(7h1RCZ-1!33N00!k{g&L*>^QR4$u}UMIcfh z++POw7ikQUNAWfO?WFW%k-Z<3tnR8dxDko|yRy|dXee;D$|7^$3x;9vg!_6TAXthP zs!C>4M?b`KsPZ3`x9DT%`d;aroh6nVu{*X0S#v7ol2 zJw>mqYV`tkL0cMg&8z`)^c(K%JfrWQe>8VWUe&o9wyoQBN;c|CwuvsjkJCzgXR=U0=OQ`wba>d!|Q9L|g)i|f< zXlZ@#jx@B*5T^4~HSEuwE`0{%b}z`_#>*>^pzcZ#-)b@OmAE8P(%r)Ji!GRO@yNZT z+05o9qdB}NAjfg8O-;FdDkqomA$vf}#zID^bqB{&3{CX3dLqE7C#N+eFA@U|S#N2% zJ}Ygqb>KpWr2A=|1%g_M#$Xt{qxawMmAjvt5XZjpaboA4KZ1{q$W`Mb95~F!Z#Ra6 zLx>YwY8`O)H(Jn%?&8~Ptf6SHhGz`qv-VBTWla`VuhT_T;HjY4=E3-N)%H(~Hg^Jb zcUg>>(J7tou8g>Z;h~%A@lvnYaNC}7Zc2qW|KGXAt`imotJYc5F2-P z2!wT)ZDV?&75(deesU}=_gFUUrw<5Uz&_<4RPV6eo=xsd`iZtlw^DAJLF8q|F>R@_ ze46JUgnPaVygi9K8yIXRcsXq5a-cC|72e_Z@4(rSaWoP{3E3XxgVr=%!m@7}(1Yw6 zK>ag?L!%cew*wBsjk)~Z>d&gy8O$j&>p@>*XJdp1?HXAsvxD+gc*(kf%CPrJi)+d(H`Z)t_`S1Nq)BOz^%g2e^PqJ zjzIK21(F7mS#(79i25=f7T~pql#o~K$DuU>njgAZdWLuZ8;@su4`n5UMUd}J+3LIx zT1xW0(m1`$rb^4Qn0>tnwO#?WI6jRz#y{xG4OYs28vT-2{@EKpd4Rlst!+`cs#@$l za(B36ZL6pQ4@gB&4Ve$CW1iWDEgvnZOvr-d>Ak}JN{ysqu4^$Ge7{aaNY)9&B6RfE z#P=T|;1dLU2R#rehybO0;si>?$HzbRAmH^{ MR#~Q0+9dRU007DM_5c6? literal 0 HcmV?d00001 diff --git a/tsconfig.json b/tsconfig.json index 23d1d4b..4e18105 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -44,9 +44,11 @@ ], "include": [ "next-env.d.ts", + "external-scripts/*.ts", "lib/**/*.ts", "src/**/*.ts", "src/**/*.tsx", "types/**/*.ts", + "" ] }