From 16e94d8941c3e5978781d5d014337c1120447ae8 Mon Sep 17 00:00:00 2001 From: Lucas Parreira Date: Wed, 1 Oct 2025 13:05:08 -0600 Subject: [PATCH 1/5] - Getting rid of set-output as it's deprecated. - Moving build/commit workflow to publish action, which is also now scoped to production. - Updating neofinancial/coverage-upload-action to latest to fix coverage job issue. - As we're no longer building/committing in the pull request action, added a note in the readme file on how to test feature branches. - Changing all runners to Ubuntu 22.04. --- .github/workflows/ci.yaml | 2 +- .github/workflows/publish.yaml | 45 +++++++++++++++++++++++++---- .github/workflows/pull-request.yaml | 18 ++---------- README.md | 1 + build/index.js | 2 +- src/index.ts | 2 ++ 6 files changed, 46 insertions(+), 24 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 67e34d6..e1b2157 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -13,7 +13,7 @@ jobs: node-version: 18 - name: Get yarn cache id: yarn-cache - run: echo "::set-output name=dir::$(yarn cache dir)" + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - name: Cache node modules uses: actions/cache@v4 with: diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 880b5ed..b17e665 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -3,11 +3,43 @@ on: push: branches: [master, main] jobs: - tag: - runs-on: ubuntu-latest + publish: + runs-on: ubuntu-22.04 + environment: production timeout-minutes: 5 steps: - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: 18 + - name: Get yarn cache + id: yarn-cache + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT + - name: Cache node modules + uses: actions/cache@v4 + with: + path: ${{ steps.yarn-cache.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Install + run: yarn --prefer-offline --frozen-lockfile --no-progress --non-interactive + - name: Build + run: yarn build + - name: Package + run: yarn package + - name: Import GPG key + uses: crazy-max/ghaction-import-gpg@e00cb83a68c1158b29afc5217dd0582cada6d172 + with: + gpg_private_key: ${{ secrets.NEOBOT_GPG_PRIVATE_KEY }} + git_user_signingkey: true + git_commit_gpgsign: true + - name: Commit latest build artifacts + uses: endbug/add-and-commit@v7 + with: + author_name: ${{ vars.NEOBOT_AUTHOR }} + author_email: ${{ vars.NEOBOT_AUTHOR_EMAIL }} + signoff: true - uses: Saionaro/extract-package-version@de8268c348d3a9ed3514c86a9ad8d4568ab8b49e id: extract_version - uses: mathieudutour/github-tag-action@d745f2e74aaf1ee82e747b181f7a0967978abee0 @@ -16,7 +48,8 @@ jobs: github_token: ${{ secrets.GITHUB_TOKEN }} custom_tag: ${{ steps.extract_version.outputs.version }} coverage: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 + environment: production timeout-minutes: 5 steps: - uses: actions/checkout@v2 @@ -25,7 +58,7 @@ jobs: node-version: 18 - name: Get yarn cache id: yarn-cache - run: echo "::set-output name=dir::$(yarn cache dir)" + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - name: Cache node modules uses: actions/cache@v4 with: @@ -38,9 +71,9 @@ jobs: - name: Test run: yarn test - name: Coverage - uses: neofinancial/coverage-upload-action@0ffd2ee97816db805bdedcca37bcac50b9521f37 + uses: neofinancial/coverage-upload-action@v2 with: coverageEndpoint: ${{ secrets.COVERAGE_ENDPOINT }} coverageToken: ${{secrets.COVERAGE_TOKEN}} env: - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} \ No newline at end of file diff --git a/.github/workflows/pull-request.yaml b/.github/workflows/pull-request.yaml index 8840020..b1a5490 100644 --- a/.github/workflows/pull-request.yaml +++ b/.github/workflows/pull-request.yaml @@ -13,7 +13,7 @@ jobs: node-version: 18 - name: Get yarn cache id: yarn-cache - run: echo "::set-output name=dir::$(yarn cache dir)" + run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT - name: Cache node modules uses: actions/cache@v4 with: @@ -38,18 +38,4 @@ jobs: instance-dbName: validation instance-port: 27018 instance-storageEngine: wiredTiger - mongoms-debug: 1 - - name: Package - run: yarn package - - name: Import GPG key - uses: crazy-max/ghaction-import-gpg@e00cb83a68c1158b29afc5217dd0582cada6d172 - with: - gpg_private_key: ${{ secrets.NEOBOT_GPG_PRIVATE_KEY }} - git_user_signingkey: true - git_commit_gpgsign: true - - name: Commit latest build artifacts - uses: endbug/add-and-commit@v7 - with: - author_name: ${{ secrets.NEOBOT_AUTHOR }} - author_email: ${{ secrets.NEOBOT_AUTHOR_EMAIL }} - signoff: true + mongoms-debug: 1 \ No newline at end of file diff --git a/README.md b/README.md index e26488d..3eadb8a 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ The memory-server is stopped (and destroyed) subsequent to the completion of thi ### Testing This repository's CI workflow has a 'validate' job @ `src/validate.ts` (technically, `build/validate.js`) for internal, CI-time testing of the action's functionality; this simply opens and closes a connection to the memory-server to ensure the validity of the provided ENV variable. There are also a small number of unit tests to ensure the memory-server's configuration values are passed to the memory-server appropriately. +If you're looking to reference this action before it's released, make sure to build it and commit the output manually. This step is automatic once the PR is merged to `master`. - please try to cover the new capability when making small changes - as necessary, add validation for variables passed directly to the initialization of the memory-server diff --git a/build/index.js b/build/index.js index 10c21a4..3efe906 100644 --- a/build/index.js +++ b/build/index.js @@ -1,4 +1,4 @@ -(()=>{var __webpack_modules__={924:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var o=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function verb(e){return function(t){return step([e,t])}}function step(i){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,o&&(s=i[0]&2?o["return"]:i[0]?o["throw"]||((s=o["return"])&&s.call(o),0):o.next)&&!(s=s.call(o,i[1])).done)return s;if(o=0,s)i=[i[0]&2,s.value];switch(i[0]){case 0:case 1:s=i;break;case 4:r.label++;return{value:i[1],done:false};case 5:r.label++;o=i[1];i=[0];continue;case 7:i=r.ops.pop();r.trys.pop();continue;default:if(!(s=r.trys,s=s.length>0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0){e+=" ";let t=true;for(const r in this.properties){if(this.properties.hasOwnProperty(r)){const n=this.properties[r];if(n){if(t){t=false}else{e+=","}e+=`${r}=${escapeProperty(n)}`}}}}e+=`${A}${escapeData(this.message)}`;return e}}function escapeData(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},2186:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.getIDToken=t.getState=t.saveState=t.group=t.endGroup=t.startGroup=t.info=t.notice=t.warning=t.error=t.debug=t.isDebug=t.setFailed=t.setCommandEcho=t.setOutput=t.getBooleanInput=t.getMultilineInput=t.getInput=t.addPath=t.setSecret=t.exportVariable=t.ExitCode=void 0;const a=r(7351);const A=r(717);const c=r(6321);const l=s(r(2037));const u=s(r(1017));const h=r(8041);var d;(function(e){e[e["Success"]=0]="Success";e[e["Failure"]=1]="Failure"})(d=t.ExitCode||(t.ExitCode={}));function exportVariable(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env["GITHUB_ENV"]||"";if(n){return A.issueFileCommand("ENV",A.prepareKeyValueMessage(e,t))}a.issueCommand("set-env",{name:e},r)}t.exportVariable=exportVariable;function setSecret(e){a.issueCommand("add-mask",{},e)}t.setSecret=setSecret;function addPath(e){const t=process.env["GITHUB_PATH"]||"";if(t){A.issueFileCommand("PATH",e)}else{a.issueCommand("add-path",{},e)}process.env["PATH"]=`${e}${u.delimiter}${process.env["PATH"]}`}t.addPath=addPath;function getInput(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r){throw new Error(`Input required and not supplied: ${e}`)}if(t&&t.trimWhitespace===false){return r}return r.trim()}t.getInput=getInput;function getMultilineInput(e,t){const r=getInput(e,t).split("\n").filter((e=>e!==""));if(t&&t.trimWhitespace===false){return r}return r.map((e=>e.trim()))}t.getMultilineInput=getMultilineInput;function getBooleanInput(e,t){const r=["true","True","TRUE"];const n=["false","False","FALSE"];const o=getInput(e,t);if(r.includes(o))return true;if(n.includes(o))return false;throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${e}\n`+`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}t.getBooleanInput=getBooleanInput;function setOutput(e,t){const r=process.env["GITHUB_OUTPUT"]||"";if(r){return A.issueFileCommand("OUTPUT",A.prepareKeyValueMessage(e,t))}process.stdout.write(l.EOL);a.issueCommand("set-output",{name:e},c.toCommandValue(t))}t.setOutput=setOutput;function setCommandEcho(e){a.issue("echo",e?"on":"off")}t.setCommandEcho=setCommandEcho;function setFailed(e){process.exitCode=d.Failure;error(e)}t.setFailed=setFailed;function isDebug(){return process.env["RUNNER_DEBUG"]==="1"}t.isDebug=isDebug;function debug(e){a.issueCommand("debug",{},e)}t.debug=debug;function error(e,t={}){a.issueCommand("error",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.error=error;function warning(e,t={}){a.issueCommand("warning",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.warning=warning;function notice(e,t={}){a.issueCommand("notice",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.notice=notice;function info(e){process.stdout.write(e+l.EOL)}t.info=info;function startGroup(e){a.issue("group",e)}t.startGroup=startGroup;function endGroup(){a.issue("endgroup")}t.endGroup=endGroup;function group(e,t){return i(this,void 0,void 0,(function*(){startGroup(e);let r;try{r=yield t()}finally{endGroup()}return r}))}t.group=group;function saveState(e,t){const r=process.env["GITHUB_STATE"]||"";if(r){return A.issueFileCommand("STATE",A.prepareKeyValueMessage(e,t))}a.issueCommand("save-state",{name:e},c.toCommandValue(t))}t.saveState=saveState;function getState(e){return process.env[`STATE_${e}`]||""}t.getState=getState;function getIDToken(e){return i(this,void 0,void 0,(function*(){return yield h.OidcClient.getIDToken(e)}))}t.getIDToken=getIDToken;var g=r(1327);Object.defineProperty(t,"summary",{enumerable:true,get:function(){return g.summary}});var p=r(1327);Object.defineProperty(t,"markdownSummary",{enumerable:true,get:function(){return p.markdownSummary}});var E=r(2981);Object.defineProperty(t,"toPosixPath",{enumerable:true,get:function(){return E.toPosixPath}});Object.defineProperty(t,"toWin32Path",{enumerable:true,get:function(){return E.toWin32Path}});Object.defineProperty(t,"toPlatformPath",{enumerable:true,get:function(){return E.toPlatformPath}})},717:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.prepareKeyValueMessage=t.issueFileCommand=void 0;const i=s(r(7147));const a=s(r(2037));const A=r(5840);const c=r(6321);function issueFileCommand(e,t){const r=process.env[`GITHUB_${e}`];if(!r){throw new Error(`Unable to find environment variable for file command ${e}`)}if(!i.existsSync(r)){throw new Error(`Missing file at path: ${r}`)}i.appendFileSync(r,`${c.toCommandValue(t)}${a.EOL}`,{encoding:"utf8"})}t.issueFileCommand=issueFileCommand;function prepareKeyValueMessage(e,t){const r=`ghadelimiter_${A.v4()}`;const n=c.toCommandValue(t);if(e.includes(r)){throw new Error(`Unexpected input: name should not contain the delimiter "${r}"`)}if(n.includes(r)){throw new Error(`Unexpected input: value should not contain the delimiter "${r}"`)}return`${e}<<${r}${a.EOL}${n}${a.EOL}${r}`}t.prepareKeyValueMessage=prepareKeyValueMessage},8041:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.OidcClient=void 0;const o=r(6255);const s=r(5526);const i=r(2186);class OidcClient{static createHttpClient(e=true,t=10){const r={allowRetries:e,maxRetries:t};return new o.HttpClient("actions/oidc-client",[new s.BearerCredentialHandler(OidcClient.getRequestToken())],r)}static getRequestToken(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable")}return e}static getIDTokenUrl(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable")}return e}static getCall(e){var t;return n(this,void 0,void 0,(function*(){const r=OidcClient.createHttpClient();const n=yield r.getJson(e).catch((e=>{throw new Error(`Failed to get ID Token. \n \n Error Code : ${e.statusCode}\n \n Error Message: ${e.message}`)}));const o=(t=n.result)===null||t===void 0?void 0:t.value;if(!o){throw new Error("Response json body do not have ID Token field")}return o}))}static getIDToken(e){return n(this,void 0,void 0,(function*(){try{let t=OidcClient.getIDTokenUrl();if(e){const r=encodeURIComponent(e);t=`${t}&audience=${r}`}i.debug(`ID token url is ${t}`);const r=yield OidcClient.getCall(t);i.setSecret(r);return r}catch(e){throw new Error(`Error message: ${e.message}`)}}))}}t.OidcClient=OidcClient},2981:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const i=s(r(1017));function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,i.sep)}t.toPlatformPath=toPlatformPath},1327:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.summary=t.markdownSummary=t.SUMMARY_DOCS_URL=t.SUMMARY_ENV_VAR=void 0;const o=r(2037);const s=r(7147);const{access:i,appendFile:a,writeFile:A}=s.promises;t.SUMMARY_ENV_VAR="GITHUB_STEP_SUMMARY";t.SUMMARY_DOCS_URL="https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";class Summary{constructor(){this._buffer=""}filePath(){return n(this,void 0,void 0,(function*(){if(this._filePath){return this._filePath}const e=process.env[t.SUMMARY_ENV_VAR];if(!e){throw new Error(`Unable to find environment variable for $${t.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`)}try{yield i(e,s.constants.R_OK|s.constants.W_OK)}catch(t){throw new Error(`Unable to access summary file: '${e}'. Check if the file has correct read/write permissions.`)}this._filePath=e;return this._filePath}))}wrap(e,t,r={}){const n=Object.entries(r).map((([e,t])=>` ${e}="${t}"`)).join("");if(!t){return`<${e}${n}>`}return`<${e}${n}>${t}`}write(e){return n(this,void 0,void 0,(function*(){const t=!!(e===null||e===void 0?void 0:e.overwrite);const r=yield this.filePath();const n=t?A:a;yield n(r,this._buffer,{encoding:"utf8"});return this.emptyBuffer()}))}clear(){return n(this,void 0,void 0,(function*(){return this.emptyBuffer().write({overwrite:true})}))}stringify(){return this._buffer}isEmptyBuffer(){return this._buffer.length===0}emptyBuffer(){this._buffer="";return this}addRaw(e,t=false){this._buffer+=e;return t?this.addEOL():this}addEOL(){return this.addRaw(o.EOL)}addCodeBlock(e,t){const r=Object.assign({},t&&{lang:t});const n=this.wrap("pre",this.wrap("code",e),r);return this.addRaw(n).addEOL()}addList(e,t=false){const r=t?"ol":"ul";const n=e.map((e=>this.wrap("li",e))).join("");const o=this.wrap(r,n);return this.addRaw(o).addEOL()}addTable(e){const t=e.map((e=>{const t=e.map((e=>{if(typeof e==="string"){return this.wrap("td",e)}const{header:t,data:r,colspan:n,rowspan:o}=e;const s=t?"th":"td";const i=Object.assign(Object.assign({},n&&{colspan:n}),o&&{rowspan:o});return this.wrap(s,r,i)})).join("");return this.wrap("tr",t)})).join("");const r=this.wrap("table",t);return this.addRaw(r).addEOL()}addDetails(e,t){const r=this.wrap("details",this.wrap("summary",e)+t);return this.addRaw(r).addEOL()}addImage(e,t,r){const{width:n,height:o}=r||{};const s=Object.assign(Object.assign({},n&&{width:n}),o&&{height:o});const i=this.wrap("img",null,Object.assign({src:e,alt:t},s));return this.addRaw(i).addEOL()}addHeading(e,t){const r=`h${t}`;const n=["h1","h2","h3","h4","h5","h6"].includes(r)?r:"h1";const o=this.wrap(n,e);return this.addRaw(o).addEOL()}addSeparator(){const e=this.wrap("hr",null);return this.addRaw(e).addEOL()}addBreak(){const e=this.wrap("br",null);return this.addRaw(e).addEOL()}addQuote(e,t){const r=Object.assign({},t&&{cite:t});const n=this.wrap("blockquote",e,r);return this.addRaw(n).addEOL()}addLink(e,t){const r=this.wrap("a",e,{href:t});return this.addRaw(r).addEOL()}}const c=new Summary;t.markdownSummary=c;t.summary=c},6321:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.toCommandProperties=t.toCommandValue=void 0;function toCommandValue(e){if(e===null||e===undefined){return""}else if(typeof e==="string"||e instanceof String){return e}return JSON.stringify(e)}t.toCommandValue=toCommandValue;function toCommandProperties(e){if(!Object.keys(e).length){return{}}return{title:e.title,file:e.file,line:e.startLine,endLine:e.endLine,col:e.startColumn,endColumn:e.endColumn}}t.toCommandProperties=toCommandProperties},5526:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.PersonalAccessTokenCredentialHandler=t.BearerCredentialHandler=t.BasicCredentialHandler=void 0;class BasicCredentialHandler{constructor(e,t){this.username=e;this.password=t}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BasicCredentialHandler=BasicCredentialHandler;class BearerCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Bearer ${this.token}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BearerCredentialHandler=BearerCredentialHandler;class PersonalAccessTokenCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.PersonalAccessTokenCredentialHandler=PersonalAccessTokenCredentialHandler},6255:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable)){o={enumerable:true,get:function(){return t[r]}}}Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.HttpClient=t.isHttps=t.HttpClientResponse=t.HttpClientError=t.getProxyUrl=t.MediaTypes=t.Headers=t.HttpCodes=void 0;const a=s(r(3685));const A=s(r(5687));const c=s(r(9835));const l=s(r(4294));const u=r(1773);var h;(function(e){e[e["OK"]=200]="OK";e[e["MultipleChoices"]=300]="MultipleChoices";e[e["MovedPermanently"]=301]="MovedPermanently";e[e["ResourceMoved"]=302]="ResourceMoved";e[e["SeeOther"]=303]="SeeOther";e[e["NotModified"]=304]="NotModified";e[e["UseProxy"]=305]="UseProxy";e[e["SwitchProxy"]=306]="SwitchProxy";e[e["TemporaryRedirect"]=307]="TemporaryRedirect";e[e["PermanentRedirect"]=308]="PermanentRedirect";e[e["BadRequest"]=400]="BadRequest";e[e["Unauthorized"]=401]="Unauthorized";e[e["PaymentRequired"]=402]="PaymentRequired";e[e["Forbidden"]=403]="Forbidden";e[e["NotFound"]=404]="NotFound";e[e["MethodNotAllowed"]=405]="MethodNotAllowed";e[e["NotAcceptable"]=406]="NotAcceptable";e[e["ProxyAuthenticationRequired"]=407]="ProxyAuthenticationRequired";e[e["RequestTimeout"]=408]="RequestTimeout";e[e["Conflict"]=409]="Conflict";e[e["Gone"]=410]="Gone";e[e["TooManyRequests"]=429]="TooManyRequests";e[e["InternalServerError"]=500]="InternalServerError";e[e["NotImplemented"]=501]="NotImplemented";e[e["BadGateway"]=502]="BadGateway";e[e["ServiceUnavailable"]=503]="ServiceUnavailable";e[e["GatewayTimeout"]=504]="GatewayTimeout"})(h||(t.HttpCodes=h={}));var d;(function(e){e["Accept"]="accept";e["ContentType"]="content-type"})(d||(t.Headers=d={}));var g;(function(e){e["ApplicationJson"]="application/json"})(g||(t.MediaTypes=g={}));function getProxyUrl(e){const t=c.getProxyUrl(new URL(e));return t?t.href:""}t.getProxyUrl=getProxyUrl;const p=[h.MovedPermanently,h.ResourceMoved,h.SeeOther,h.TemporaryRedirect,h.PermanentRedirect];const E=[h.BadGateway,h.ServiceUnavailable,h.GatewayTimeout];const m=["OPTIONS","GET","DELETE","HEAD"];const C=10;const I=5;class HttpClientError extends Error{constructor(e,t){super(e);this.name="HttpClientError";this.statusCode=t;Object.setPrototypeOf(this,HttpClientError.prototype)}}t.HttpClientError=HttpClientError;class HttpClientResponse{constructor(e){this.message=e}readBody(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){let t=Buffer.alloc(0);this.message.on("data",(e=>{t=Buffer.concat([t,e])}));this.message.on("end",(()=>{e(t.toString())}))}))))}))}readBodyBuffer(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){const t=[];this.message.on("data",(e=>{t.push(e)}));this.message.on("end",(()=>{e(Buffer.concat(t))}))}))))}))}}t.HttpClientResponse=HttpClientResponse;function isHttps(e){const t=new URL(e);return t.protocol==="https:"}t.isHttps=isHttps;class HttpClient{constructor(e,t,r){this._ignoreSslError=false;this._allowRedirects=true;this._allowRedirectDowngrade=false;this._maxRedirects=50;this._allowRetries=false;this._maxRetries=1;this._keepAlive=false;this._disposed=false;this.userAgent=e;this.handlers=t||[];this.requestOptions=r;if(r){if(r.ignoreSslError!=null){this._ignoreSslError=r.ignoreSslError}this._socketTimeout=r.socketTimeout;if(r.allowRedirects!=null){this._allowRedirects=r.allowRedirects}if(r.allowRedirectDowngrade!=null){this._allowRedirectDowngrade=r.allowRedirectDowngrade}if(r.maxRedirects!=null){this._maxRedirects=Math.max(r.maxRedirects,0)}if(r.keepAlive!=null){this._keepAlive=r.keepAlive}if(r.allowRetries!=null){this._allowRetries=r.allowRetries}if(r.maxRetries!=null){this._maxRetries=r.maxRetries}}}options(e,t){return i(this,void 0,void 0,(function*(){return this.request("OPTIONS",e,null,t||{})}))}get(e,t){return i(this,void 0,void 0,(function*(){return this.request("GET",e,null,t||{})}))}del(e,t){return i(this,void 0,void 0,(function*(){return this.request("DELETE",e,null,t||{})}))}post(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("POST",e,t,r||{})}))}patch(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PATCH",e,t,r||{})}))}put(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PUT",e,t,r||{})}))}head(e,t){return i(this,void 0,void 0,(function*(){return this.request("HEAD",e,null,t||{})}))}sendStream(e,t,r,n){return i(this,void 0,void 0,(function*(){return this.request(e,t,r,n)}))}getJson(e,t={}){return i(this,void 0,void 0,(function*(){t[d.Accept]=this._getExistingOrDefaultHeader(t,d.Accept,g.ApplicationJson);const r=yield this.get(e,t);return this._processResponse(r,this.requestOptions)}))}postJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.post(e,n,r);return this._processResponse(o,this.requestOptions)}))}putJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.put(e,n,r);return this._processResponse(o,this.requestOptions)}))}patchJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.patch(e,n,r);return this._processResponse(o,this.requestOptions)}))}request(e,t,r,n){return i(this,void 0,void 0,(function*(){if(this._disposed){throw new Error("Client has already been disposed.")}const o=new URL(t);let s=this._prepareRequest(e,o,n);const i=this._allowRetries&&m.includes(e)?this._maxRetries+1:1;let a=0;let A;do{A=yield this.requestRaw(s,r);if(A&&A.message&&A.message.statusCode===h.Unauthorized){let e;for(const t of this.handlers){if(t.canHandleAuthentication(A)){e=t;break}}if(e){return e.handleAuthentication(this,s,r)}else{return A}}let t=this._maxRedirects;while(A.message.statusCode&&p.includes(A.message.statusCode)&&this._allowRedirects&&t>0){const i=A.message.headers["location"];if(!i){break}const a=new URL(i);if(o.protocol==="https:"&&o.protocol!==a.protocol&&!this._allowRedirectDowngrade){throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.")}yield A.readBody();if(a.hostname!==o.hostname){for(const e in n){if(e.toLowerCase()==="authorization"){delete n[e]}}}s=this._prepareRequest(e,a,n);A=yield this.requestRaw(s,r);t--}if(!A.message.statusCode||!E.includes(A.message.statusCode)){return A}a+=1;if(a{function callbackForResult(e,t){if(e){n(e)}else if(!t){n(new Error("Unknown error"))}else{r(t)}}this.requestRawWithCallback(e,t,callbackForResult)}))}))}requestRawWithCallback(e,t,r){if(typeof t==="string"){if(!e.options.headers){e.options.headers={}}e.options.headers["Content-Length"]=Buffer.byteLength(t,"utf8")}let n=false;function handleResult(e,t){if(!n){n=true;r(e,t)}}const o=e.httpModule.request(e.options,(e=>{const t=new HttpClientResponse(e);handleResult(undefined,t)}));let s;o.on("socket",(e=>{s=e}));o.setTimeout(this._socketTimeout||3*6e4,(()=>{if(s){s.end()}handleResult(new Error(`Request timeout: ${e.options.path}`))}));o.on("error",(function(e){handleResult(e)}));if(t&&typeof t==="string"){o.write(t,"utf8")}if(t&&typeof t!=="string"){t.on("close",(function(){o.end()}));t.pipe(o)}else{o.end()}}getAgent(e){const t=new URL(e);return this._getAgent(t)}getAgentDispatcher(e){const t=new URL(e);const r=c.getProxyUrl(t);const n=r&&r.hostname;if(!n){return}return this._getProxyAgentDispatcher(t,r)}_prepareRequest(e,t,r){const n={};n.parsedUrl=t;const o=n.parsedUrl.protocol==="https:";n.httpModule=o?A:a;const s=o?443:80;n.options={};n.options.host=n.parsedUrl.hostname;n.options.port=n.parsedUrl.port?parseInt(n.parsedUrl.port):s;n.options.path=(n.parsedUrl.pathname||"")+(n.parsedUrl.search||"");n.options.method=e;n.options.headers=this._mergeHeaders(r);if(this.userAgent!=null){n.options.headers["user-agent"]=this.userAgent}n.options.agent=this._getAgent(n.parsedUrl);if(this.handlers){for(const e of this.handlers){e.prepareRequest(n.options)}}return n}_mergeHeaders(e){if(this.requestOptions&&this.requestOptions.headers){return Object.assign({},lowercaseKeys(this.requestOptions.headers),lowercaseKeys(e||{}))}return lowercaseKeys(e||{})}_getExistingOrDefaultHeader(e,t,r){let n;if(this.requestOptions&&this.requestOptions.headers){n=lowercaseKeys(this.requestOptions.headers)[t]}return e[t]||n||r}_getAgent(e){let t;const r=c.getProxyUrl(e);const n=r&&r.hostname;if(this._keepAlive&&n){t=this._proxyAgent}if(!n){t=this._agent}if(t){return t}const o=e.protocol==="https:";let s=100;if(this.requestOptions){s=this.requestOptions.maxSockets||a.globalAgent.maxSockets}if(r&&r.hostname){const e={maxSockets:s,keepAlive:this._keepAlive,proxy:Object.assign(Object.assign({},(r.username||r.password)&&{proxyAuth:`${r.username}:${r.password}`}),{host:r.hostname,port:r.port})};let n;const i=r.protocol==="https:";if(o){n=i?l.httpsOverHttps:l.httpsOverHttp}else{n=i?l.httpOverHttps:l.httpOverHttp}t=n(e);this._proxyAgent=t}if(!t){const e={keepAlive:this._keepAlive,maxSockets:s};t=o?new A.Agent(e):new a.Agent(e);this._agent=t}if(o&&this._ignoreSslError){t.options=Object.assign(t.options||{},{rejectUnauthorized:false})}return t}_getProxyAgentDispatcher(e,t){let r;if(this._keepAlive){r=this._proxyAgentDispatcher}if(r){return r}const n=e.protocol==="https:";r=new u.ProxyAgent(Object.assign({uri:t.href,pipelining:!this._keepAlive?0:1},(t.username||t.password)&&{token:`${t.username}:${t.password}`}));this._proxyAgentDispatcher=r;if(n&&this._ignoreSslError){r.options=Object.assign(r.options.requestTls||{},{rejectUnauthorized:false})}return r}_performExponentialBackoff(e){return i(this,void 0,void 0,(function*(){e=Math.min(C,e);const t=I*Math.pow(2,e);return new Promise((e=>setTimeout((()=>e()),t)))}))}_processResponse(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((r,n)=>i(this,void 0,void 0,(function*(){const o=e.message.statusCode||0;const s={statusCode:o,result:null,headers:{}};if(o===h.NotFound){r(s)}function dateTimeDeserializer(e,t){if(typeof t==="string"){const e=new Date(t);if(!isNaN(e.valueOf())){return e}}return t}let i;let a;try{a=yield e.readBody();if(a&&a.length>0){if(t&&t.deserializeDates){i=JSON.parse(a,dateTimeDeserializer)}else{i=JSON.parse(a)}s.result=i}s.headers=e.message.headers}catch(e){}if(o>299){let e;if(i&&i.message){e=i.message}else if(a&&a.length>0){e=a}else{e=`Failed request: (${o})`}const t=new HttpClientError(e,o);t.result=s.result;n(t)}else{r(s)}}))))}))}}t.HttpClient=HttpClient;const lowercaseKeys=e=>Object.keys(e).reduce(((t,r)=>(t[r.toLowerCase()]=e[r],t)),{})},9835:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.checkBypass=t.getProxyUrl=void 0;function getProxyUrl(e){const t=e.protocol==="https:";if(checkBypass(e)){return undefined}const r=(()=>{if(t){return process.env["https_proxy"]||process.env["HTTPS_PROXY"]}else{return process.env["http_proxy"]||process.env["HTTP_PROXY"]}})();if(r){try{return new URL(r)}catch(e){if(!r.startsWith("http://")&&!r.startsWith("https://"))return new URL(`http://${r}`)}}else{return undefined}}t.getProxyUrl=getProxyUrl;function checkBypass(e){if(!e.hostname){return false}const t=e.hostname;if(isLoopbackAddress(t)){return true}const r=process.env["no_proxy"]||process.env["NO_PROXY"]||"";if(!r){return false}let n;if(e.port){n=Number(e.port)}else if(e.protocol==="http:"){n=80}else if(e.protocol==="https:"){n=443}const o=[e.hostname.toUpperCase()];if(typeof n==="number"){o.push(`${o[0]}:${n}`)}for(const e of r.split(",").map((e=>e.trim().toUpperCase())).filter((e=>e))){if(e==="*"||o.some((t=>t===e||t.endsWith(`.${e}`)||e.startsWith(".")&&t.endsWith(`${e}`)))){return true}}return false}t.checkBypass=checkBypass;function isLoopbackAddress(e){const t=e.toLowerCase();return t==="localhost"||t.startsWith("127.")||t.startsWith("[::1]")||t.startsWith("[0:0:0:0:0:0:0:1]")}},9690:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2361);const s=n(r(8237));const i=n(r(6570));const a=s.default("agent-base");function isAgent(e){return Boolean(e)&&typeof e.addRequest==="function"}function isSecureEndpoint(){const{stack:e}=new Error;if(typeof e!=="string")return false;return e.split("\n").some((e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1))}function createAgent(e,t){return new createAgent.Agent(e,t)}(function(e){class Agent extends o.EventEmitter{constructor(e,t){super();let r=t;if(typeof e==="function"){this.callback=e}else if(e){r=e}this.timeout=null;if(r&&typeof r.timeout==="number"){this.timeout=r.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,r){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const r=Object.assign({},t);if(typeof r.secureEndpoint!=="boolean"){r.secureEndpoint=isSecureEndpoint()}if(r.host==null){r.host="localhost"}if(r.port==null){r.port=r.secureEndpoint?443:80}if(r.protocol==null){r.protocol=r.secureEndpoint?"https:":"http:"}if(r.host&&r.path){delete r.path}delete r.agent;delete r.hostname;delete r._defaultAgent;delete r.defaultPort;delete r.createConnection;e._last=true;e.shouldKeepAlive=false;let n=false;let o=null;const s=r.timeout||this.timeout;const onerror=t=>{if(e._hadError)return;e.emit("error",t);e._hadError=true};const ontimeout=()=>{o=null;n=true;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT";onerror(e)};const callbackError=e=>{if(n)return;if(o!==null){clearTimeout(o);o=null}onerror(e)};const onsocket=t=>{if(n)return;if(o!=null){clearTimeout(o);o=null}if(isAgent(t)){a("Callback returned another Agent instance %o",t.constructor.name);t.addRequest(e,r);return}if(t){t.once("free",(()=>{this.freeSocket(t,r)}));e.onSocket(t);return}const s=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);onerror(s)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){a("Converting legacy callback function to promise");this.promisifiedCallback=i.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof s==="number"&&s>0){o=setTimeout(ontimeout,s)}if("port"in r&&typeof r.port!=="number"){r.port=Number(r.port)}try{a("Resolving socket for %o request: %o",r.protocol,`${e.method} ${e.path}`);Promise.resolve(this.promisifiedCallback(e,r)).then(onsocket,callbackError)}catch(e){Promise.reject(e).catch(callbackError)}}freeSocket(e,t){a("Freeing socket %o %o",e.constructor.name,t);e.destroy()}destroy(){a("Destroying agent %o",this.constructor.name)}}e.Agent=Agent;e.prototype=e.Agent.prototype})(createAgent||(createAgent={}));e.exports=createAgent},6570:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function promisify(e){return function(t,r){return new Promise(((n,o)=>{e.call(this,t,r,((e,t)=>{if(e){o(e)}else{n(t)}}))}))}}t["default"]=promisify},4855:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6006);var s=function(){function Mutex(e){this._semaphore=new o.default(1,e)}Mutex.prototype.acquire=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,n.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._semaphore.acquire()];case 1:e=r.sent(),t=e[1];return[2,t]}}))}))};Mutex.prototype.runExclusive=function(e){return this._semaphore.runExclusive((function(){return e()}))};Mutex.prototype.isLocked=function(){return this._semaphore.isLocked()};Mutex.prototype.waitForUnlock=function(){return this._semaphore.waitForUnlock()};Mutex.prototype.release=function(){this._semaphore.release()};Mutex.prototype.cancel=function(){return this._semaphore.cancel()};return Mutex}();t["default"]=s},6006:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6984);var s=function(){function Semaphore(e,t){if(t===void 0){t=o.E_CANCELED}this._maxConcurrency=e;this._cancelError=t;this._queue=[];this._waiters=[];if(e<=0){throw new Error("semaphore must be initialized to a positive value")}this._value=e}Semaphore.prototype.acquire=function(){var e=this;var t=this.isLocked();var r=new Promise((function(t,r){return e._queue.push({resolve:t,reject:r})}));if(!t)this._dispatch();return r};Semaphore.prototype.runExclusive=function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r,o;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.acquire()];case 1:t=n.sent(),r=t[0],o=t[1];n.label=2;case 2:n.trys.push([2,,4,5]);return[4,e(r)];case 3:return[2,n.sent()];case 4:o();return[7];case 5:return[2]}}))}))};Semaphore.prototype.waitForUnlock=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e;var t=this;return(0,n.__generator)(this,(function(r){if(!this.isLocked()){return[2,Promise.resolve()]}e=new Promise((function(e){return t._waiters.push({resolve:e})}));return[2,e]}))}))};Semaphore.prototype.isLocked=function(){return this._value<=0};Semaphore.prototype.release=function(){if(this._maxConcurrency>1){throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead")}if(this._currentReleaser){var e=this._currentReleaser;this._currentReleaser=undefined;e()}};Semaphore.prototype.cancel=function(){var e=this;this._queue.forEach((function(t){return t.reject(e._cancelError)}));this._queue=[]};Semaphore.prototype._dispatch=function(){var e=this;var t=this._queue.shift();if(!t)return;var r=false;this._currentReleaser=function(){if(r)return;r=true;e._value++;e._resolveWaiters();e._dispatch()};t.resolve([this._value--,this._currentReleaser])};Semaphore.prototype._resolveWaiters=function(){this._waiters.forEach((function(e){return e.resolve()}));this._waiters=[]};return Semaphore}();t["default"]=s},6984:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.E_CANCELED=t.E_ALREADY_LOCKED=t.E_TIMEOUT=void 0;t.E_TIMEOUT=new Error("timeout while waiting for mutex to become available");t.E_ALREADY_LOCKED=new Error("mutex already locked");t.E_CANCELED=new Error("request for lock canceled")},4038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=t.withTimeout=t.Semaphore=t.Mutex=void 0;var n=r(4351);var o=r(4855);Object.defineProperty(t,"Mutex",{enumerable:true,get:function(){return o.default}});var s=r(6006);Object.defineProperty(t,"Semaphore",{enumerable:true,get:function(){return s.default}});var i=r(5124);Object.defineProperty(t,"withTimeout",{enumerable:true,get:function(){return i.withTimeout}});var a=r(2621);Object.defineProperty(t,"tryAcquire",{enumerable:true,get:function(){return a.tryAcquire}});(0,n.__exportStar)(r(6984),t)},2621:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=void 0;var n=r(6984);var o=r(5124);function tryAcquire(e,t){if(t===void 0){t=n.E_ALREADY_LOCKED}return(0,o.withTimeout)(e,0,t)}t.tryAcquire=tryAcquire},5124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.withTimeout=void 0;var n=r(4351);var o=r(6984);function withTimeout(e,t,r){var s=this;if(r===void 0){r=o.E_TIMEOUT}return{acquire:function(){return new Promise((function(o,i){return(0,n.__awaiter)(s,void 0,void 0,(function(){var s,a,A,c,l;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:s=false;a=setTimeout((function(){s=true;i(r)}),t);n.label=1;case 1:n.trys.push([1,3,,4]);return[4,e.acquire()];case 2:A=n.sent();if(s){c=Array.isArray(A)?A[1]:A;c()}else{clearTimeout(a);o(A)}return[3,4];case 3:l=n.sent();if(!s){clearTimeout(a);i(l)}return[3,4];case 4:return[2]}}))}))}))},runExclusive:function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:t=function(){return undefined};n.label=1;case 1:n.trys.push([1,,7,8]);return[4,this.acquire()];case 2:r=n.sent();if(!Array.isArray(r))return[3,4];t=r[1];return[4,e(r[0])];case 3:return[2,n.sent()];case 4:t=r;return[4,e()];case 5:return[2,n.sent()];case 6:return[3,8];case 7:t();return[7];case 8:return[2]}}))}))},release:function(){e.release()},cancel:function(){return e.cancel()},waitForUnlock:function(){return e.waitForUnlock()},isLocked:function(){return e.isLocked()}}}t.withTimeout=withTimeout},9417:e=>{"use strict";e.exports=balanced;function balanced(e,t,r){if(e instanceof RegExp)e=maybeMatch(e,r);if(t instanceof RegExp)t=maybeMatch(t,r);var n=range(e,t,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+e.length,n[1]),post:r.slice(n[1]+t.length)}}function maybeMatch(e,t){var r=t.match(e);return r?r[0]:null}balanced.range=range;function range(e,t,r){var n,o,s,i,a;var A=r.indexOf(e);var c=r.indexOf(t,A+1);var l=A;if(A>=0&&c>0){if(e===t){return[A,c]}n=[];s=r.length;while(l>=0&&!a){if(l==A){n.push(l);A=r.indexOf(e,l+1)}else if(n.length==1){a=[n.pop(),c]}else{o=n.pop();if(o=0?A:c}if(n.length){a=[s,i]}}return a}},336:(e,t,r)=>{"use strict";var n=r(1642).Duplex,o=r(3837),s=r(1867).Buffer;function BufferList(e){if(!(this instanceof BufferList))return new BufferList(e);this._bufs=[];this.length=0;if(typeof e=="function"){this._callback=e;var t=function piper(e){if(this._callback){this._callback(e);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(e){e.on("error",t)}));this.on("unpipe",(function onUnpipe(e){e.removeListener("error",t)}))}else{this.append(e)}n.call(this)}o.inherits(BufferList,n);BufferList.prototype._offset=function _offset(e){var t=0,r=0,n;if(e===0)return[0,0];for(;rthis.length||e<0){return undefined}var t=this._offset(e);return this._bufs[t[0]][t[1]]};BufferList.prototype.slice=function slice(e,t){if(typeof e=="number"&&e<0)e+=this.length;if(typeof t=="number"&&t<0)t+=this.length;return this.copy(null,0,e,t)};BufferList.prototype.copy=function copy(e,t,r,n){if(typeof r!="number"||r<0)r=0;if(typeof n!="number"||n>this.length)n=this.length;if(r>=this.length)return e||s.alloc(0);if(n<=0)return e||s.alloc(0);var copy=!!e,o=this._offset(r),i=n-r,a=i,A=copy&&t||0,c=o[1],l,u;if(r===0&&n==this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length)}for(u=0;ul){this._bufs[u].copy(e,A,c);A+=l}else{this._bufs[u].copy(e,A,c,c+a);A+=l;break}a-=l;if(c)c=0}if(e.length>A)return e.slice(0,A);return e};BufferList.prototype.shallowSlice=function shallowSlice(e,t){e=e||0;t=typeof t!=="number"?this.length:t;if(e<0)e+=this.length;if(t<0)t+=this.length;if(e===t){return new BufferList}var r=this._offset(e),n=this._offset(t),o=this._bufs.slice(r[0],n[0]+1);if(n[1]==0)o.pop();else o[o.length-1]=o[o.length-1].slice(0,n[1]);if(r[1]!=0)o[0]=o[0].slice(r[1]);return new BufferList(o)};BufferList.prototype.toString=function toString(e,t,r){return this.slice(t,r).toString(e)};BufferList.prototype.consume=function consume(e){e=Math.trunc(e);if(Number.isNaN(e)||e<=0)return this;while(this._bufs.length){if(e>=this._bufs[0].length){e-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(e);this.length-=e;break}}return this};BufferList.prototype.duplicate=function duplicate(){var e=0,t=new BufferList;for(;ethis.length?this.length:t}var n=this._offset(t);var o=n[0];var i=n[1];for(o;o=e.length){var c=a.indexOf(e,i);if(c!==-1){return this._reverseOffset([o,c])}i=a.length-e.length+1}else{var l=this._reverseOffset([o,i]);if(this._match(l,e)){return l}i++}}i=0}return-1};BufferList.prototype._match=function(e,t){if(this.length-e{var n=r(6891);var o=r(9417);e.exports=expandTop;var s="\0SLASH"+Math.random()+"\0";var i="\0OPEN"+Math.random()+"\0";var a="\0CLOSE"+Math.random()+"\0";var A="\0COMMA"+Math.random()+"\0";var c="\0PERIOD"+Math.random()+"\0";function numeric(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function escapeBraces(e){return e.split("\\\\").join(s).split("\\{").join(i).split("\\}").join(a).split("\\,").join(A).split("\\.").join(c)}function unescapeBraces(e){return e.split(s).join("\\").split(i).join("{").split(a).join("}").split(A).join(",").split(c).join(".")}function parseCommaParts(e){if(!e)return[""];var t=[];var r=o("{","}",e);if(!r)return e.split(",");var n=r.pre;var s=r.body;var i=r.post;var a=n.split(",");a[a.length-1]+="{"+s+"}";var A=parseCommaParts(i);if(i.length){a[a.length-1]+=A.shift();a.push.apply(a,A)}t.push.apply(t,a);return t}function expandTop(e){if(!e)return[];if(e.substr(0,2)==="{}"){e="\\{\\}"+e.substr(2)}return expand(escapeBraces(e),true).map(unescapeBraces)}function identity(e){return e}function embrace(e){return"{"+e+"}"}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand(e,t){var r=[];var s=o("{","}",e);if(!s||/\$$/.test(s.pre))return[e];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);var A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);var c=i||A;var l=s.body.indexOf(",")>=0;if(!c&&!l){if(s.post.match(/,.*\}/)){e=s.pre+"{"+s.body+a+s.post;return expand(e)}return[e]}var u;if(c){u=s.body.split(/\.\./)}else{u=parseCommaParts(s.body);if(u.length===1){u=expand(u[0],false).map(embrace);if(u.length===1){var h=s.post.length?expand(s.post,false):[""];return h.map((function(e){return s.pre+u[0]+e}))}}}var d=s.pre;var h=s.post.length?expand(s.post,false):[""];var g;if(c){var p=numeric(u[0]);var E=numeric(u[1]);var m=Math.max(u[0].length,u[1].length);var C=u.length==3?Math.abs(numeric(u[2])):1;var I=lte;var y=E0){var S=new Array(w+1).join("0");if(Q<0)b="-"+S+b.slice(1);else b=S+b}}}g.push(b)}}else{g=n(u,(function(e){return expand(e,false)}))}for(var v=0;v{var n=r(6800),o=r(5497),s=r(7113),i=r(3797),a=r(414),A=r(972),c=r(6142),l=r(8522),u=r(3639),h=r(5846),d=r(5325),g=r(9502),p=r(4636),E=r(2259),m=r(1031);n.BSON_INT32_MAX=2147483647;n.BSON_INT32_MIN=-2147483648;n.BSON_INT64_MAX=Math.pow(2,63)-1;n.BSON_INT64_MIN=-Math.pow(2,63);n.JS_INT_MAX=9007199254740992;n.JS_INT_MIN=-9007199254740992;n.Binary=o;n.Code=s;n.DBRef=i;n.Decimal128=a;n.Double=A;n.Int32=c;n.Long=l;n.Map=u;n.MaxKey=h;n.MinKey=d;n.ObjectId=g;n.ObjectID=g;n.BSONRegExp=p;n.Symbol=E;n.Timestamp=m;e.exports=n},5497:(e,t,r)=>{if(typeof global!=="undefined"){var n=r(4300).Buffer}var o=r(2863);function Binary(e,t){if(!(this instanceof Binary))return new Binary(e,t);if(e!=null&&!(typeof e==="string")&&!n.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e)){throw new Error("only String, Buffer, Uint8Array or Array accepted")}this._bsontype="Binary";if(e instanceof Number){this.sub_type=e;this.position=0}else{this.sub_type=t==null?s:t;this.position=0}if(e!=null&&!(e instanceof Number)){if(typeof e==="string"){if(typeof n!=="undefined"){this.buffer=o.toBuffer(e)}else if(typeof Uint8Array!=="undefined"||Object.prototype.toString.call(e)==="[object Array]"){this.buffer=writeStringToArray(e)}else{throw new Error("only String, Buffer, Uint8Array or Array accepted")}}else{this.buffer=e}this.position=e.length}else{if(typeof n!=="undefined"){this.buffer=o.allocBuffer(Binary.BUFFER_SIZE)}else if(typeof Uint8Array!=="undefined"){this.buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE))}else{this.buffer=new Array(Binary.BUFFER_SIZE)}this.position=0}}Binary.prototype.put=function put(e){if(e["length"]!=null&&typeof e!=="number"&&e.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof e!=="number"&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(typeof e==="string"){t=e.charCodeAt(0)}else if(e["length"]!=null){t=e[0]}else{t=e}if(this.buffer.length>this.position){this.buffer[this.position++]=t}else{if(typeof n!=="undefined"&&n.isBuffer(this.buffer)){var r=o.allocBuffer(Binary.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length);this.buffer=r;this.buffer[this.position++]=t}else{r=null;if(Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"){r=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE+this.buffer.length))}else{r=new Array(Binary.BUFFER_SIZE+this.buffer.length)}for(var s=0;sthis.position?t+e.length:this.position}else if(typeof n!=="undefined"&&typeof e==="string"&&n.isBuffer(this.buffer)){this.buffer.write(e,t,"binary");this.position=t+e.length>this.position?t+e.length:this.position}else if(Object.prototype.toString.call(e)==="[object Uint8Array]"||Object.prototype.toString.call(e)==="[object Array]"&&typeof e!=="string"){for(s=0;sthis.position?t:this.position}else if(typeof e==="string"){for(s=0;sthis.position?t:this.position}};Binary.prototype.read=function read(e,t){t=t&&t>0?t:this.position;if(this.buffer["slice"]){return this.buffer.slice(e,e+t)}else{var r=typeof Uint8Array!=="undefined"?new Uint8Array(new ArrayBuffer(t)):new Array(t);for(var n=0;n{"use strict";var n=r(3639),o=r(8522),s=r(972),i=r(1031),a=r(9502),A=r(4636),c=r(2259),l=r(6142),u=r(7113),h=r(414),d=r(5325),g=r(5846),p=r(3797),E=r(5497);var m=r(2139),C=r(9290),I=r(1273),y=r(2863);var B=1024*1024*17;var Q=y.allocBuffer(B);var BSON=function(){};BSON.prototype.serialize=function serialize(e,t){t=t||{};var r=typeof t.checkKeys==="boolean"?t.checkKeys:false;var n=typeof t.serializeFunctions==="boolean"?t.serializeFunctions:false;var o=typeof t.ignoreUndefined==="boolean"?t.ignoreUndefined:true;var s=typeof t.minInternalBufferSize==="number"?t.minInternalBufferSize:B;if(Q.length{var t=function Code(e,t){if(!(this instanceof Code))return new Code(e,t);this._bsontype="Code";this.code=e;this.scope=t};t.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};e.exports=t;e.exports.Code=t},3797:e=>{function DBRef(e,t,r){if(!(this instanceof DBRef))return new DBRef(e,t,r);this._bsontype="DBRef";this.namespace=e;this.oid=t;this.db=r}DBRef.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};e.exports=DBRef;e.exports.DBRef=DBRef},414:(e,t,r)=>{"use strict";var n=r(8522);var o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var s=/^(\+|-)?(Infinity|inf)$/i;var i=/^(\+|-)?NaN$/i;var a=6111;var A=-6176;var c=6176;var l=34;var u=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var h=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var d=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var g=/^([-+])?(\d+)?$/;var p=r(2863);var isDigit=function(e){return!isNaN(parseInt(e,10))};var divideu128=function(e){var t=n.fromNumber(1e3*1e3*1e3);var r=n.fromNumber(0);var o=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3]){return{quotient:e,rem:r}}for(o=0;o<=3;o++){r=r.shiftLeft(32);r=r.add(new n(e.parts[o],0));e.parts[o]=r.div(t).low_;r=r.modulo(t)}return{quotient:e,rem:r}};var multiply64x2=function(e,t){if(!e&&!t){return{high:n.fromNumber(0),low:n.fromNumber(0)}}var r=e.shiftRightUnsigned(32);var o=new n(e.getLowBits(),0);var s=t.shiftRightUnsigned(32);var i=new n(t.getLowBits(),0);var a=r.multiply(s);var A=r.multiply(i);var c=o.multiply(s);var l=o.multiply(i);a=a.add(A.shiftRightUnsigned(32));A=new n(A.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32));a=a.add(A.shiftRightUnsigned(32));l=A.shiftLeft(32).add(new n(l.getLowBits(),0));return{high:a,low:l}};var lessThan=function(e,t){var r=e.high_>>>0;var n=t.high_>>>0;if(r>>0;var s=t.low_>>>0;if(o=7e3){throw new Error(""+e+" not a valid Decimal128 string")}var _=e.match(o);var M=e.match(s);var L=e.match(i);if(!_&&!M&&!L||e.length===0){throw new Error(""+e+" not a valid Decimal128 string")}if(_&&_[4]&&_[2]===undefined){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="+"||e[O]==="-"){t=e[O++]==="-"}if(!isDigit(e[O])&&e[O]!=="."){if(e[O]==="i"||e[O]==="I"){return new Decimal128(p.toBuffer(t?h:d))}else if(e[O]==="N"){return new Decimal128(p.toBuffer(u))}}while(isDigit(e[O])||e[O]==="."){if(e[O]==="."){if(r){return new Decimal128(p.toBuffer(u))}r=true;O=O+1;continue}if(b<34){if(e[O]!=="0"||E){if(!E){B=C}E=true;Q[w++]=parseInt(e[O],10);b=b+1}}if(E){I=I+1}if(r){y=y+1}C=C+1;O=O+1}if(r&&!C){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="e"||e[O]==="E"){var F=e.substr(++O).match(g);if(!F||!F[2]){return new Decimal128(p.toBuffer(u))}R=parseInt(F[0],10);O=O+F[0].length}if(e[O]){return new Decimal128(p.toBuffer(u))}S=0;if(!b){S=0;v=0;Q[0]=0;I=1;b=1;m=0}else{v=b-1;m=I;if(R!==0&&m!==1){while(e[B+m-1]==="0"){m=m-1}}}if(R<=y&&y-R>1<<14){R=A}else{R=R-y}while(R>a){v=v+1;if(v-S>l){var U=Q.join("");if(U.match(/^0+$/)){R=a;break}else{return new Decimal128(p.toBuffer(t?h:d))}}R=R-1}while(R=5){Y=1;if(G===5){Y=Q[v]%2===1;for(k=B+v+2;k=0;V--){if(++Q[V]>9){Q[V]=0;if(V===0){if(R>8&255;q[O++]=J.low.low_>>16&255;q[O++]=J.low.low_>>24&255;q[O++]=J.low.high_&255;q[O++]=J.low.high_>>8&255;q[O++]=J.low.high_>>16&255;q[O++]=J.low.high_>>24&255;q[O++]=J.high.low_&255;q[O++]=J.high.low_>>8&255;q[O++]=J.high.low_>>16&255;q[O++]=J.high.low_>>24&255;q[O++]=J.high.high_&255;q[O++]=J.high.high_>>8&255;q[O++]=J.high.high_>>16&255;q[O++]=J.high.high_>>24&255;return new Decimal128(q)};var E=31;var m=16383;var C=30;var I=31;c=6176;Decimal128.prototype.toString=function(){var e;var t;var r;var o;var s;var i;var a=0;var A=new Array(36);for(var l=0;l>26&E;if(s>>3===3){if(s===C){return b.join("")+"Infinity"}else if(s===I){return"NaN"}else{i=e>>15&m;p=8+(e>>14&1)}}else{p=e>>14&7;i=e>>17&m}h=i-c;y.parts[0]=(e&16383)+((p&15)<<14);y.parts[1]=t;y.parts[2]=r;y.parts[3]=o;if(y.parts[0]===0&&y.parts[1]===0&&y.parts[2]===0&&y.parts[3]===0){g=true}else{for(Q=3;Q>=0;Q--){var v=0;var R=divideu128(y);y=R.quotient;v=R.rem.low_;if(!v)continue;for(B=8;B>=0;B--){A[Q*9+B]=v%10;v=Math.floor(v/10)}}}if(g){a=1;A[u]=0}else{a=36;l=0;while(!A[u]){l++;a=a-1;u=u+1}}d=a-1+h;if(d>=34||d<=-7||h>0){b.push(A[u++]);a=a-1;if(a){b.push(".")}for(l=0;l0){b.push("+"+d)}else{b.push(d)}}else{if(h>=0){for(l=0;l0){for(l=0;l{function Double(e){if(!(this instanceof Double))return new Double(e);this._bsontype="Double";this.value=e}Double.prototype.valueOf=function(){return this.value};Double.prototype.toJSON=function(){return this.value};e.exports=Double;e.exports.Double=Double},7998:(e,t)=>{var r;var readIEEE754=function(e,t,r,n,o){var s,i,a=r==="big",A=o*8-n-1,c=(1<>1,u=-7,h=a?0:o-1,d=a?1:-1,g=e[t+h];h+=d;s=g&(1<<-u)-1;g>>=-u;u+=A;for(;u>0;s=s*256+e[t+h],h+=d,u-=8);i=s&(1<<-u)-1;s>>=-u;u+=n;for(;u>0;i=i*256+e[t+h],h+=d,u-=8);if(s===0){s=1-l}else if(s===c){return i?NaN:(g?-1:1)*Infinity}else{i=i+Math.pow(2,n);s=s-l}return(g?-1:1)*i*Math.pow(2,s-n)};var writeIEEE754=function(e,t,r,n,o,s){var i,a,A,c=n==="big",l=s*8-o-1,u=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=c?s-1:0,p=c?-1:1,E=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;i=u}else{i=Math.floor(Math.log(t)/Math.LN2);if(t*(A=Math.pow(2,-i))<1){i--;A*=2}if(i+h>=1){t+=d/A}else{t+=d*Math.pow(2,1-h)}if(t*A>=2){i++;A/=2}if(i+h>=u){a=0;i=u}else if(i+h>=1){a=(t*A-1)*Math.pow(2,o);i=i+h}else{a=t*Math.pow(2,h-1)*Math.pow(2,o);i=0}}for(;o>=8;e[r+g]=a&255,g+=p,a/=256,o-=8);i=i<0;e[r+g]=i&255,g+=p,i/=256,l-=8);e[r+g-p]|=E*128};r=readIEEE754;t.P=writeIEEE754},6142:e=>{var Int32=function(e){if(!(this instanceof Int32))return new Int32(e);this._bsontype="Int32";this.value=e};Int32.prototype.valueOf=function(){return this.value};Int32.prototype.toJSON=function(){return this.value};e.exports=Int32;e.exports.Int32=Int32},8522:e=>{function Long(e,t){if(!(this instanceof Long))return new Long(e,t);this._bsontype="Long";this.low_=e|0;this.high_=t|0}Long.prototype.toInt=function(){return this.low_};Long.prototype.toNumber=function(){return this.high_*Long.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Long.prototype.toBigInt=function(){return BigInt(this.toString())};Long.prototype.toJSON=function(){return this.toString()};Long.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Long.TWO_PWR_32_DBL_+this.low_};Long.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Long.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Long.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Long.prototype.negate=function(){if(this.equals(Long.MIN_VALUE)){return Long.MIN_VALUE}else{return this.not().add(Long.ONE)}};Long.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.subtract=function(e){return this.add(e.negate())};Long.prototype.multiply=function(e){if(this.isZero()){return Long.ZERO}else if(e.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){return e.isOdd()?Long.MIN_VALUE:Long.ZERO}else if(e.equals(Long.MIN_VALUE)){return this.isOdd()?Long.MIN_VALUE:Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Long.TWO_PWR_24_)&&e.lessThan(Long.TWO_PWR_24_)){return Long.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){if(e.equals(Long.ONE)||e.equals(Long.NEG_ONE)){return Long.MIN_VALUE}else if(e.equals(Long.MIN_VALUE)){return Long.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Long.ZERO)){return e.isNegative()?Long.ONE:Long.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Long.MIN_VALUE)){return Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Long.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Long.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Long.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Long.ONE}s=s.add(A);n=n.subtract(c)}return s};Long.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Long.prototype.not=function(){return Long.fromBits(~this.low_,~this.high_)};Long.prototype.and=function(e){return Long.fromBits(this.low_&e.low_,this.high_&e.high_)};Long.prototype.or=function(e){return Long.fromBits(this.low_|e.low_,this.high_|e.high_)};Long.prototype.xor=function(e){return Long.fromBits(this.low_^e.low_,this.high_^e.high_)};Long.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Long.fromBits(t<>>32-e)}else{return Long.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Long.fromBits(t>>e-32,t>=0?0:-1)}}};Long.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Long.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Long.fromBits(t,0)}else{return Long.fromBits(t>>>e-32,0)}}};Long.fromInt=function(e){if(-128<=e&&e<128){var t=Long.INT_CACHE_[e];if(t){return t}}var r=new Long(e|0,e<0?-1:0);if(-128<=e&&e<128){Long.INT_CACHE_[e]=r}return r};Long.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Long.ZERO}else if(e<=-Long.TWO_PWR_63_DBL_){return Long.MIN_VALUE}else if(e+1>=Long.TWO_PWR_63_DBL_){return Long.MAX_VALUE}else if(e<0){return Long.fromNumber(-e).negate()}else{return new Long(e%Long.TWO_PWR_32_DBL_|0,e/Long.TWO_PWR_32_DBL_|0)}};Long.fromBigInt=function(e){return Long.fromString(e.toString(10),10)};Long.fromBits=function(e,t){return new Long(e,t)};Long.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Long.fromNumber(Math.pow(r,8));var o=Long.ZERO;for(var s=0;s{"use strict";if(typeof global.Map!=="undefined"){e.exports=global.Map;e.exports.Map=global.Map}else{var Map=function(e){this._keys=[];this._values={};for(var t=0;t{function MaxKey(){if(!(this instanceof MaxKey))return new MaxKey;this._bsontype="MaxKey"}e.exports=MaxKey;e.exports.MaxKey=MaxKey},5325:e=>{function MinKey(){if(!(this instanceof MinKey))return new MinKey;this._bsontype="MinKey"}e.exports=MinKey;e.exports.MinKey=MinKey},9502:(e,t,r)=>{var n="inspect";var o=r(2863);var s=parseInt(Math.random()*16777215,10);var i=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=true;n=r(3837).inspect.custom||"inspect"}}catch(e){a=false}var A=function ObjectID(e){if(e instanceof ObjectID)return e;if(!(this instanceof ObjectID))return new ObjectID(e);this._bsontype="ObjectID";if(e==null||typeof e==="number"){this.id=this.generate(e);if(ObjectID.cacheHexString)this.__id=this.toString("hex");return}var t=ObjectID.isValid(e);if(!t&&e!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(t&&typeof e==="string"&&e.length===24&&a){return new ObjectID(o.toBuffer(e,"hex"))}else if(t&&typeof e==="string"&&e.length===24){return ObjectID.createFromHexString(e)}else if(e!=null&&e.length===12){this.id=e}else if(e!=null&&typeof e.toHexString==="function"){return e}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}if(ObjectID.cacheHexString)this.__id=this.toString("hex")};var c=[];for(var l=0;l<256;l++){c[l]=(l<=15?"0":"")+l.toString(16)}A.prototype.toHexString=function(){if(A.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id instanceof h){e=convertToHex(this.id);if(A.cacheHexString)this.__id=e;return e}for(var t=0;t>8&255;n[1]=e>>16&255;n[0]=e>>24&255;n[6]=s&255;n[5]=s>>8&255;n[4]=s>>16&255;n[8]=t&255;n[7]=t>>8&255;n[11]=r&255;n[10]=r>>8&255;n[9]=r>>16&255;return n};A.prototype.toString=function(e){if(this.id&&this.id.copy){return this.id.toString(typeof e==="string"?e:"hex")}return this.toHexString()};A.prototype[n]=A.prototype.toString;A.prototype.toJSON=function(){return this.toHexString()};A.prototype.equals=function equals(e){if(e instanceof A){return this.toString()===e.toString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12&&this.id instanceof h){return e===this.id.toString("binary")}else if(typeof e==="string"&&A.isValid(e)&&e.length===24){return e.toLowerCase()===this.toHexString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12){return e===this.id}else if(e!=null&&(e instanceof A||e.toHexString)){return e.toHexString()===this.toHexString()}else{return false}};A.prototype.getTimestamp=function(){var e=new Date;var t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;e.setTime(Math.floor(t)*1e3);return e};A.index=~~(Math.random()*16777215);A.createPk=function createPk(){return new A};A.createFromTime=function createFromTime(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);t[3]=e&255;t[2]=e>>8&255;t[1]=e>>16&255;t[0]=e>>24&255;return new A(t)};var u=[];l=0;while(l<10)u[48+l]=l++;while(l<16)u[65-10+l]=u[97-10+l]=l++;var h=Buffer;var convertToHex=function(e){return e.toString("hex")};A.createFromHexString=function createFromHexString(e){if(typeof e==="undefined"||e!=null&&e.length!==24){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 A(o.toBuffer(e,"hex"));var t=new h(12);var r=0;var n=0;while(n<24){t[r++]=u[e.charCodeAt(n++)]<<4|u[e.charCodeAt(n++)]}return new A(t)};A.isValid=function isValid(e){if(e==null)return false;if(typeof e==="number"){return true}if(typeof e==="string"){return e.length===12||e.length===24&&i.test(e)}if(e instanceof A){return true}if(e instanceof h){return true}if(typeof e.toHexString==="function"&&(e.id instanceof h||typeof e.id==="string")){return e.id.length===12||e.id.length===24&&i.test(e.id)}return false};Object.defineProperty(A.prototype,"generationTime",{enumerable:true,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255;this.id[2]=e>>8&255;this.id[1]=e>>16&255;this.id[0]=e>>24&255}});e.exports=A;e.exports.ObjectID=A;e.exports.ObjectId=A},1273:(e,t,r)=>{"use strict";var n=r(8522).Long,o=r(972).Double,s=r(1031).Timestamp,i=r(9502).ObjectID,a=r(2259).Symbol,A=r(4636).BSONRegExp,c=r(7113).Code,l=r(414),u=r(5325).MinKey,h=r(5846).MaxKey,d=r(3797).DBRef,g=r(5497).Binary;var p=r(2863).normalizedFunctionString;var E=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var m=function calculateObjectSize(e,t,r){var n=4+1;if(Array.isArray(e)){for(var o=0;o=C.JS_INT_MIN&&t<=C.JS_INT_MAX){if(t>=C.BSON_INT32_MIN&&t<=C.BSON_INT32_MAX){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}case"undefined":if(I||!y)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;return 0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof u||t instanceof h||t["_bsontype"]==="MinKey"||t["_bsontype"]==="MaxKey"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1}else if(t instanceof i||t["_bsontype"]==="ObjectID"||t["_bsontype"]==="ObjectId"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1)}else if(t instanceof Date||E(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(typeof Buffer!=="undefined"&&Buffer.isBuffer(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length}else if(t instanceof n||t instanceof o||t instanceof s||t["_bsontype"]==="Long"||t["_bsontype"]==="Double"||t["_bsontype"]==="Timestamp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(t instanceof l||t["_bsontype"]==="Decimal128"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1)}else if(t instanceof c||t["_bsontype"]==="Code"){if(t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+m(t.scope,r,y)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1}}else if(t instanceof g||t["_bsontype"]==="Binary"){if(t.sub_type===g.SUBTYPE_BYTE_ARRAY){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1)}}else if(t instanceof a||t["_bsontype"]==="Symbol"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1}else if(t instanceof d||t["_bsontype"]==="DBRef"){var B={$ref:t.namespace,$id:t.oid};if(null!=t.db){B["$db"]=t.db}return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+m(B,r,y)}else if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"){return(e!=null?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}else if(t instanceof A||t["_bsontype"]==="BSONRegExp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+m(t,r,y)+1}case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]"){return(e!=null?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}else{if(r&&t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(p(t),"utf8")+1+m(t.scope,r,y)}else if(r){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(p(t),"utf8")+1}}}return 0}var C={};C.BSON_INT32_MAX=2147483647;C.BSON_INT32_MIN=-2147483648;C.JS_INT_MAX=9007199254740992;C.JS_INT_MIN=-9007199254740992;e.exports=m},2139:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";var Long=__nccwpck_require__(8522).Long,Double=__nccwpck_require__(972).Double,Timestamp=__nccwpck_require__(1031).Timestamp,ObjectID=__nccwpck_require__(9502).ObjectID,Symbol=__nccwpck_require__(2259).Symbol,Code=__nccwpck_require__(7113).Code,MinKey=__nccwpck_require__(5325).MinKey,MaxKey=__nccwpck_require__(5846).MaxKey,Decimal128=__nccwpck_require__(414),Int32=__nccwpck_require__(6142),DBRef=__nccwpck_require__(3797).DBRef,BSONRegExp=__nccwpck_require__(4636).BSONRegExp,Binary=__nccwpck_require__(5497).Binary;var utils=__nccwpck_require__(2863);var deserialize=function(e,t,r){t=t==null?{}:t;var n=t&&t.index?t.index:0;var o=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(o<5||e.lengthe.length){throw new Error("corrupt bson message")}if(e[n+o-1]!==0){throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(e,n,t,r)};var deserializeObject=function(e,t,r,n){var o=r["evalFunctions"]==null?false:r["evalFunctions"];var s=r["cacheFunctions"]==null?false:r["cacheFunctions"];var i=r["cacheFunctionsCrc32"]==null?false:r["cacheFunctionsCrc32"];if(!i)var a=null;var A=r["fieldsAsRaw"]==null?null:r["fieldsAsRaw"];var c=r["raw"]==null?false:r["raw"];var l=typeof r["bsonRegExp"]==="boolean"?r["bsonRegExp"]:false;var u=r["promoteBuffers"]==null?false:r["promoteBuffers"];var h=r["promoteLongs"]==null?true:r["promoteLongs"];var d=r["promoteValues"]==null?true:r["promoteValues"];var g=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var p=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(p<5||p>e.length)throw new Error("corrupt bson message");var E=n?[]:{};var m=0;var C=false;while(!C){var I=e[t++];if(I===0)break;var y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var B=n?m++:e.toString("utf8",t,y);t=y+1;if(I===BSON.BSON_DATA_STRING){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=e.toString("utf8",t,t+Q-1);t=t+Q}else if(I===BSON.BSON_DATA_OID){var b=utils.allocBuffer(12);e.copy(b,0,t,t+12);E[B]=new ObjectID(b);t=t+12}else if(I===BSON.BSON_DATA_INT&&d===false){E[B]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)}else if(I===BSON.BSON_DATA_INT){E[B]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}else if(I===BSON.BSON_DATA_NUMBER&&d===false){E[B]=new Double(e.readDoubleLE(t));t=t+8}else if(I===BSON.BSON_DATA_NUMBER){E[B]=e.readDoubleLE(t);t=t+8}else if(I===BSON.BSON_DATA_DATE){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Date(new Long(w,S).toNumber())}else if(I===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");E[B]=e[t++]===1}else if(I===BSON.BSON_DATA_OBJECT){var v=t;var R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(R<=0||R>e.length-t)throw new Error("bad embedded document length in bson");if(c){E[B]=e.slice(t,t+R)}else{E[B]=deserializeObject(e,v,r,false)}t=t+R}else if(I===BSON.BSON_DATA_ARRAY){v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var k=r;var D=t+R;if(A&&A[B]){k={};for(var N in r)k[N]=r[N];k["raw"]=true}E[B]=deserializeObject(e,v,k,true);t=t+R;if(e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==D)throw new Error("corrupted array bson")}else if(I===BSON.BSON_DATA_UNDEFINED){E[B]=undefined}else if(I===BSON.BSON_DATA_NULL){E[B]=null}else if(I===BSON.BSON_DATA_LONG){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var T=new Long(w,S);if(h&&d===true){E[B]=T.lessThanOrEqual(JS_INT_MAX_LONG)&&T.greaterThanOrEqual(JS_INT_MIN_LONG)?T.toNumber():T}else{E[B]=T}}else if(I===BSON.BSON_DATA_DECIMAL128){var O=utils.allocBuffer(16);e.copy(O,0,t,t+16);t=t+16;var _=new Decimal128(O);E[B]=_.toObject?_.toObject():_}else if(I===BSON.BSON_DATA_BINARY){var M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var L=M;var F=e[t++];if(M<0)throw new Error("Negative binary type element size found");if(M>e.length)throw new Error("Binary type size larger than document size");if(e["slice"]!=null){if(F===Binary.SUBTYPE_BYTE_ARRAY){M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(M<0)throw new Error("Negative binary type element size found for subtype 0x02");if(M>L-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(ML-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(M=e.length)throw new Error("Bad BSON Document: illegal CString");var P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var G=e.toString("utf8",t,y);t=y+1;var Y=new Array(G.length);for(y=0;y=e.length)throw new Error("Bad BSON Document: illegal CString");P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");G=e.toString("utf8",t,y);t=y+1;E[B]=new BSONRegExp(P,G)}else if(I===BSON.BSON_DATA_SYMBOL){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=new Symbol(e.toString("utf8",t,t+Q-1));t=t+Q}else if(I===BSON.BSON_DATA_TIMESTAMP){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Timestamp(w,S)}else if(I===BSON.BSON_DATA_MIN_KEY){E[B]=new MinKey}else if(I===BSON.BSON_DATA_MAX_KEY){E[B]=new MaxKey}else if(I===BSON.BSON_DATA_CODE){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var V=e.toString("utf8",t,t+Q-1);if(o){if(s){var W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}}else{E[B]=new Code(V)}t=t+Q}else if(I===BSON.BSON_DATA_CODE_W_SCOPE){var J=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(J<4+4+4+1){throw new Error("code_w_scope total size shorter minimum expected length")}Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");V=e.toString("utf8",t,t+Q-1);t=t+Q;v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,v,r,false);t=t+R;if(J<4+4+R+Q){throw new Error("code_w_scope total size is to short, truncating scope")}if(J>4+4+R+Q){throw new Error("code_w_scope total size is to long, clips outer document")}if(o){if(s){W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}E[B].scope=q}else{E[B]=new Code(V,q)}}else if(I===BSON.BSON_DATA_DBPOINTER){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var j=e.toString("utf8",t,t+Q-1);t=t+Q;var z=utils.allocBuffer(12);e.copy(z,0,t,t+12);b=new ObjectID(z);t=t+12;var $=j.split(".");var K=$.shift();var X=$.join(".");E[B]=new DBRef(X,b,K)}else{throw new Error("Detected unknown BSON type "+I.toString(16)+' for fieldname "'+B+'", are you using the latest BSON parser')}}if(p!==t-g){if(n)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}if(E["$id"]!=null)E=new DBRef(E["$ref"],E["$id"],E["$db"]);return E};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;if(functionCache[hash]==null){eval("value = "+functionString);functionCache[hash]=value}return functionCache[hash].bind(object)};var isolateEval=function(functionString){var value=null;eval("value = "+functionString);return value};var BSON={};var 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);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},9290:(e,t,r)=>{"use strict";var n=r(7998).P,o=r(8522).Long,s=r(3639),i=r(5497).Binary;var a=r(2863).normalizedFunctionString;var A=/\x00/;var c=["$db","$ref","$id","$clusterTime"];var l=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var u=function isRegExp(e){return Object.prototype.toString.call(e)==="[object RegExp]"};var serializeString=function(e,t,r,n,o){e[n++]=d.BSON_DATA_STRING;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s+1;e[n-1]=0;var i=e.write(r,n+4,"utf8");e[n+3]=i+1>>24&255;e[n+2]=i+1>>16&255;e[n+1]=i+1>>8&255;e[n]=i+1&255;n=n+4+i;e[n++]=0;return n};var serializeNumber=function(e,t,r,s,i){if(Math.floor(r)===r&&r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){if(r>=d.BSON_INT32_MIN&&r<=d.BSON_INT32_MAX){e[s++]=d.BSON_DATA_INT;var a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;e[s++]=r&255;e[s++]=r>>8&255;e[s++]=r>>16&255;e[s++]=r>>24&255}else if(r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}else{e[s++]=d.BSON_DATA_LONG;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;var A=o.fromNumber(r);var c=A.getLowBits();var l=A.getHighBits();e[s++]=c&255;e[s++]=c>>8&255;e[s++]=c>>16&255;e[s++]=c>>24&255;e[s++]=l&255;e[s++]=l>>8&255;e[s++]=l>>16&255;e[s++]=l>>24&255}}else{e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}return s};var serializeNull=function(e,t,r,n,o){e[n++]=d.BSON_DATA_NULL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeBoolean=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BOOLEAN;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r?1:0;return n};var serializeDate=function(e,t,r,n,s){e[n++]=d.BSON_DATA_DATE;var i=!s?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+i;e[n++]=0;var a=o.fromNumber(r.getTime());var A=a.getLowBits();var c=a.getHighBits();e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=c&255;e[n++]=c>>8&255;e[n++]=c>>16&255;e[n++]=c>>24&255;return n};var serializeRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.source&&r.source.match(A)!=null){throw Error("value "+r.source+" must not contain null bytes")}n=n+e.write(r.source,n,"utf8");e[n++]=0;if(r.global)e[n++]=115;if(r.ignoreCase)e[n++]=105;if(r.multiline)e[n++]=109;e[n++]=0;return n};var serializeBSONRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.pattern.match(A)!=null){throw Error("pattern "+r.pattern+" must not contain null bytes")}n=n+e.write(r.pattern,n,"utf8");e[n++]=0;n=n+e.write(r.options.split("").sort().join(""),n,"utf8");e[n++]=0;return n};var serializeMinMax=function(e,t,r,n,o){if(r===null){e[n++]=d.BSON_DATA_NULL}else if(r._bsontype==="MinKey"){e[n++]=d.BSON_DATA_MIN_KEY}else{e[n++]=d.BSON_DATA_MAX_KEY}var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeObjectId=function(e,t,r,n,o){e[n++]=d.BSON_DATA_OID;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(typeof r.id==="string"){e.write(r.id,n,"binary")}else if(r.id&&r.id.copy){r.id.copy(e,n,0,12)}else{throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId")}return n+12};var serializeBuffer=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=r.length;e[n++]=i&255;e[n++]=i>>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=d.BSON_BINARY_SUBTYPE_DEFAULT;r.copy(e,n,0,i);n=n+i;return n};var serializeObject=function(e,t,r,n,o,s,i,a,A,c){for(var l=0;l>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=a&255;e[n++]=a>>8&255;e[n++]=a>>16&255;e[n++]=a>>24&255;return n};var serializeInt32=function(e,t,r,n,o){e[n++]=d.BSON_DATA_INT;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r&255;e[n++]=r>>8&255;e[n++]=r>>16&255;e[n++]=r>>24&255;return n};var serializeDouble=function(e,t,r,o,s){e[o++]=d.BSON_DATA_NUMBER;var i=!s?e.write(t,o,"utf8"):e.write(t,o,"ascii");o=o+i;e[o++]=0;n(e,r,o,"little",52,8);o=o+8;return o};var serializeFunction=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_CODE;var A=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+A;e[n++]=0;var c=a(r);var l=e.write(c,n+4,"utf8")+1;e[n]=l&255;e[n+1]=l>>8&255;e[n+2]=l>>16&255;e[n+3]=l>>24&255;n=n+4+l-1;e[n++]=0;return n};var serializeCode=function(e,t,r,n,o,s,i,a,A){if(r.scope&&typeof r.scope==="object"){e[n++]=d.BSON_DATA_CODE_W_SCOPE;var c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;var l=n;var u=typeof r.code==="string"?r.code:r.code.toString();n=n+4;var g=e.write(u,n+4,"utf8")+1;e[n]=g&255;e[n+1]=g>>8&255;e[n+2]=g>>16&255;e[n+3]=g>>24&255;e[n+4+g-1]=0;n=n+g+4;var p=h(e,r.scope,o,n,s+1,i,a);n=p-1;var E=p-l;e[l++]=E&255;e[l++]=E>>8&255;e[l++]=E>>16&255;e[l++]=E>>24&255;e[n++]=0}else{e[n++]=d.BSON_DATA_CODE;c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;u=r.code.toString();var m=e.write(u,n+4,"utf8")+1;e[n]=m&255;e[n+1]=m>>8&255;e[n+2]=m>>16&255;e[n+3]=m>>24&255;n=n+4+m-1;e[n++]=0}return n};var serializeBinary=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var a=r.value(true);var A=r.position;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY)A=A+4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=r.sub_type;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY){A=A-4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255}a.copy(e,n,0,r.position);n=n+r.position;return n};var serializeSymbol=function(e,t,r,n,o){e[n++]=d.BSON_DATA_SYMBOL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=e.write(r.value,n+4,"utf8")+1;e[n]=i&255;e[n+1]=i>>8&255;e[n+2]=i>>16&255;e[n+3]=i>>24&255;n=n+4+i-1;e[n++]=0;return n};var serializeDBRef=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_OBJECT;var a=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+a;e[n++]=0;var A=n;var c;if(null!=r.db){c=h(e,{$ref:r.namespace,$id:r.oid,$db:r.db},false,n,o+1,s)}else{c=h(e,{$ref:r.namespace,$id:r.oid},false,n,o+1,s)}var l=c-A;e[A++]=l&255;e[A++]=l>>8&255;e[A++]=l>>16&255;e[A++]=l>>24&255;return c};var h=function serializeInto(e,t,r,n,o,i,a,h){n=n||0;h=h||[];h.push(t);var d=n+4;if(Array.isArray(t)){for(var g=0;g>8&255;e[n++]=B>>16&255;e[n++]=B>>24&255;return d};var d={};d.BSON_DATA_NUMBER=1;d.BSON_DATA_STRING=2;d.BSON_DATA_OBJECT=3;d.BSON_DATA_ARRAY=4;d.BSON_DATA_BINARY=5;d.BSON_DATA_UNDEFINED=6;d.BSON_DATA_OID=7;d.BSON_DATA_BOOLEAN=8;d.BSON_DATA_DATE=9;d.BSON_DATA_NULL=10;d.BSON_DATA_REGEXP=11;d.BSON_DATA_CODE=13;d.BSON_DATA_SYMBOL=14;d.BSON_DATA_CODE_W_SCOPE=15;d.BSON_DATA_INT=16;d.BSON_DATA_TIMESTAMP=17;d.BSON_DATA_LONG=18;d.BSON_DATA_DECIMAL128=19;d.BSON_DATA_MIN_KEY=255;d.BSON_DATA_MAX_KEY=127;d.BSON_BINARY_SUBTYPE_DEFAULT=0;d.BSON_BINARY_SUBTYPE_FUNCTION=1;d.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;d.BSON_BINARY_SUBTYPE_UUID=3;d.BSON_BINARY_SUBTYPE_MD5=4;d.BSON_BINARY_SUBTYPE_USER_DEFINED=128;d.BSON_INT32_MAX=2147483647;d.BSON_INT32_MIN=-2147483648;d.BSON_INT64_MAX=Math.pow(2,63)-1;d.BSON_INT64_MIN=-Math.pow(2,63);d.JS_INT_MAX=9007199254740992;d.JS_INT_MIN=-9007199254740992;e.exports=h},2863:e=>{"use strict";function normalizedFunctionString(e){return e.toString().replace(/function *\(/,"function (")}function newBuffer(e,t){return new Buffer(e,t)}function allocBuffer(){return Buffer.alloc.apply(Buffer,arguments)}function toBuffer(){return Buffer.from.apply(Buffer,arguments)}e.exports={normalizedFunctionString:normalizedFunctionString,allocBuffer:typeof Buffer.alloc==="function"?allocBuffer:newBuffer,toBuffer:typeof Buffer.from==="function"?toBuffer:newBuffer}},4636:e=>{function BSONRegExp(e,t){if(!(this instanceof BSONRegExp))return new BSONRegExp;this._bsontype="BSONRegExp";this.pattern=e||"";this.options=t||"";for(var r=0;r{var n=Buffer?r(3837).inspect.custom||"inspect":"inspect";function Symbol(e){if(!(this instanceof Symbol))return new Symbol(e);this._bsontype="Symbol";this.value=e}Symbol.prototype.valueOf=function(){return this.value};Symbol.prototype.toString=function(){return this.value};Symbol.prototype[n]=function(){return this.value};Symbol.prototype.toJSON=function(){return this.value};e.exports=Symbol;e.exports.Symbol=Symbol},1031:e=>{function Timestamp(e,t){if(!(this instanceof Timestamp))return new Timestamp(e,t);this._bsontype="Timestamp";this.low_=e|0;this.high_=t|0}Timestamp.prototype.toInt=function(){return this.low_};Timestamp.prototype.toNumber=function(){return this.high_*Timestamp.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Timestamp.prototype.toJSON=function(){return this.toString()};Timestamp.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Timestamp.TWO_PWR_32_DBL_+this.low_};Timestamp.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Timestamp.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Timestamp.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Timestamp.prototype.negate=function(){if(this.equals(Timestamp.MIN_VALUE)){return Timestamp.MIN_VALUE}else{return this.not().add(Timestamp.ONE)}};Timestamp.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.subtract=function(e){return this.add(e.negate())};Timestamp.prototype.multiply=function(e){if(this.isZero()){return Timestamp.ZERO}else if(e.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){return e.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}else if(e.equals(Timestamp.MIN_VALUE)){return this.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Timestamp.TWO_PWR_24_)&&e.lessThan(Timestamp.TWO_PWR_24_)){return Timestamp.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){if(e.equals(Timestamp.ONE)||e.equals(Timestamp.NEG_ONE)){return Timestamp.MIN_VALUE}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Timestamp.ZERO)){return e.isNegative()?Timestamp.ONE:Timestamp.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Timestamp.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Timestamp.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Timestamp.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Timestamp.ONE}s=s.add(A);n=n.subtract(c)}return s};Timestamp.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Timestamp.prototype.not=function(){return Timestamp.fromBits(~this.low_,~this.high_)};Timestamp.prototype.and=function(e){return Timestamp.fromBits(this.low_&e.low_,this.high_&e.high_)};Timestamp.prototype.or=function(e){return Timestamp.fromBits(this.low_|e.low_,this.high_|e.high_)};Timestamp.prototype.xor=function(e){return Timestamp.fromBits(this.low_^e.low_,this.high_^e.high_)};Timestamp.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Timestamp.fromBits(t<>>32-e)}else{return Timestamp.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Timestamp.fromBits(t>>e-32,t>=0?0:-1)}}};Timestamp.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Timestamp.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Timestamp.fromBits(t,0)}else{return Timestamp.fromBits(t>>>e-32,0)}}};Timestamp.fromInt=function(e){if(-128<=e&&e<128){var t=Timestamp.INT_CACHE_[e];if(t){return t}}var r=new Timestamp(e|0,e<0?-1:0);if(-128<=e&&e<128){Timestamp.INT_CACHE_[e]=r}return r};Timestamp.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Timestamp.ZERO}else if(e<=-Timestamp.TWO_PWR_63_DBL_){return Timestamp.MIN_VALUE}else if(e+1>=Timestamp.TWO_PWR_63_DBL_){return Timestamp.MAX_VALUE}else if(e<0){return Timestamp.fromNumber(-e).negate()}else{return new Timestamp(e%Timestamp.TWO_PWR_32_DBL_|0,e/Timestamp.TWO_PWR_32_DBL_|0)}};Timestamp.fromBits=function(e,t){return new Timestamp(e,t)};Timestamp.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Timestamp.fromNumber(Math.pow(r,8));var o=Timestamp.ZERO;for(var s=0;s{var n=r(4300).Buffer;var o=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){o=new Int32Array(o)}function ensureBuffer(e){if(n.isBuffer(e)){return e}var t=typeof n.alloc==="function"&&typeof n.from==="function";if(typeof e==="number"){return t?n.alloc(e):new n(e)}else if(typeof e==="string"){return t?n.from(e):new n(e)}else{throw new Error("input must be buffer, number, or string, received "+typeof e)}}function bufferizeInt(e){var t=ensureBuffer(4);t.writeInt32BE(e,0);return t}function _crc32(e,t){e=ensureBuffer(e);if(n.isBuffer(t)){t=t.readUInt32BE(0)}var r=~~t^-1;for(var s=0;s>>8}return r^-1}function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};e.exports=crc32},1362:e=>{"use strict";const t=/[\p{Lu}]/u;const r=/[\p{Ll}]/u;const n=/^[\p{Lu}](?![\p{Lu}])/gu;const o=/([\p{Alpha}\p{N}_]|$)/u;const s=/[_.\- ]+/;const i=new RegExp("^"+s.source);const a=new RegExp(s.source+o.source,"gu");const A=new RegExp("\\d+"+o.source,"gu");const preserveCamelCase=(e,n,o)=>{let s=false;let i=false;let a=false;for(let A=0;A{n.lastIndex=0;return e.replace(n,(e=>t(e)))};const postProcess=(e,t)=>{a.lastIndex=0;A.lastIndex=0;return e.replace(a,((e,r)=>t(r))).replace(A,(e=>t(e)))};const camelCase=(e,t)=>{if(!(typeof e==="string"||Array.isArray(e))){throw new TypeError("Expected the input to be `string | string[]`")}t={pascalCase:false,preserveConsecutiveUppercase:false,...t};if(Array.isArray(e)){e=e.map((e=>e.trim())).filter((e=>e.length)).join("-")}else{e=e.trim()}if(e.length===0){return""}const r=t.locale===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale);const n=t.locale===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);if(e.length===1){return t.pascalCase?n(e):r(e)}const o=e!==r(e);if(o){e=preserveCamelCase(e,r,n)}e=e.replace(i,"");if(t.preserveConsecutiveUppercase){e=preserveConsecutiveUppercase(e,r)}else{e=r(e)}if(t.pascalCase){e=n(e.charAt(0))+e.slice(1)}return postProcess(e,n)};e.exports=camelCase;e.exports["default"]=camelCase},9930:(e,t,r)=>{var n=r(1017);e.exports=function(e,t){if(t){var r=t.map((function(t){return n.resolve(e,t)}))}else{var r=e}var o=r.slice(1).reduce((function(e,t){if(!t.match(/^([A-Za-z]:)?\/|\\/)){throw new Error("relative path without a basedir")}var r=t.split(/\/+|\\+/);for(var n=0;e[n]===r[n]&&n1?o.join("/"):"/"}},6891:e=>{e.exports=function(e,r){var n=[];for(var o=0;o{t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.storage=localstorage();t.destroy=(()=>{let e=false;return()=>{if(!e){e=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(t){t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff);if(!this.useColors){return}const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0;let o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{if(e==="%%"){return}n++;if(e==="%c"){o=n}}));t.splice(o,0,r)}t.log=console.debug||console.log||(()=>{});function save(e){try{if(e){t.storage.setItem("debug",e)}else{t.storage.removeItem("debug")}}catch(e){}}function load(){let e;try{e=t.storage.getItem("debug")}catch(e){}if(!e&&typeof process!=="undefined"&&"env"in process){e=process.env.DEBUG}return e}function localstorage(){try{return localStorage}catch(e){}}e.exports=r(6243)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},6243:(e,t,r)=>{function setup(e){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=r(900);createDebug.destroy=destroy;Object.keys(e).forEach((t=>{createDebug[t]=e[t]}));createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let t=0;for(let r=0;r{if(t==="%%"){return"%"}s++;const o=createDebug.formatters[n];if(typeof o==="function"){const n=e[s];t=o.call(r,n);e.splice(s,1);s--}return t}));createDebug.formatArgs.call(r,e);const i=r.log||createDebug.log;i.apply(r,e)}debug.namespace=e;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(e);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>r===null?createDebug.enabled(e):r,set:e=>{r=e}});if(typeof createDebug.init==="function"){createDebug.init(debug)}return debug}function extend(e,t){const r=createDebug(this.namespace+(typeof t==="undefined"?":":t)+e);r.log=this.log;return r}function enable(e){createDebug.save(e);createDebug.names=[];createDebug.skips=[];let t;const r=(typeof e==="string"?e:"").split(/[\s,]+/);const n=r.length;for(t=0;t"-"+e))].join(",");createDebug.enable("");return e}function enabled(e){if(e[e.length-1]==="*"){return true}let t;let r;for(t=0,r=createDebug.skips.length;t{if(typeof process==="undefined"||process.type==="renderer"||process.browser===true||process.__nwjs){e.exports=r(8222)}else{e.exports=r(5332)}},5332:(e,t,r)=>{const n=r(6224);const o=r(3837);t.init=init;t.log=log;t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.destroy=o.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");t.colors=[6,2,3,4,5,1];try{const e=r(9318);if(e&&(e.stderr||e).level>=2){t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];if(/^(yes|on|true|enabled)$/i.test(n)){n=true}else if(/^(no|off|false|disabled)$/i.test(n)){n=false}else if(n==="null"){n=null}else{n=Number(n)}e[r]=n;return e}),{});function useColors(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(t){const{namespace:r,useColors:n}=this;if(n){const n=this.color;const o="[3"+(n<8?n:"8;5;"+n);const s=` ${o};1m${r} `;t[0]=s+t[0].split("\n").join("\n"+s);t.push(o+"m+"+e.exports.humanize(this.diff)+"")}else{t[0]=getDate()+r+" "+t[0]}}function getDate(){if(t.inspectOpts.hideDate){return""}return(new Date).toISOString()+" "}function log(...e){return process.stderr.write(o.format(...e)+"\n")}function save(e){if(e){process.env.DEBUG=e}else{delete process.env.DEBUG}}function load(){return process.env.DEBUG}function init(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;ne.trim())).join(" ")};s.O=function(e){this.inspectOpts.colors=this.useColors;return o.inspect(e,this.inspectOpts)}},2342:e=>{"use strict";function Denque(e,t){var t=t||{};this._head=0;this._tail=0;this._capacity=t.capacity;this._capacityMask=3;this._list=new Array(4);if(Array.isArray(e)){this._fromArray(e)}}Denque.prototype.peekAt=function peekAt(e){var t=e;if(t!==(t|0)){return void 0}var r=this.size();if(t>=r||t<-r)return undefined;if(t<0)t+=r;t=this._head+t&this._capacityMask;return this._list[t]};Denque.prototype.get=function get(e){return this.peekAt(e)};Denque.prototype.peek=function peek(){if(this._head===this._tail)return undefined;return this._list[this._head]};Denque.prototype.peekFront=function peekFront(){return this.peek()};Denque.prototype.peekBack=function peekBack(){return this.peekAt(-1)};Object.defineProperty(Denque.prototype,"length",{get:function length(){return this.size()}});Denque.prototype.size=function size(){if(this._head===this._tail)return 0;if(this._headthis._capacity)this.pop();if(this._head1e4&&this._tail<=this._list.length>>>2)this._shrinkArray();return t};Denque.prototype.push=function push(e){if(e===undefined)return this.size();var t=this._tail;this._list[t]=e;this._tail=t+1&this._capacityMask;if(this._tail===this._head){this._growArray()}if(this._capacity&&this.size()>this._capacity){this.shift()}if(this._head1e4&&e<=t>>>2)this._shrinkArray();return r};Denque.prototype.removeOne=function removeOne(e){var t=e;if(t!==(t|0)){return void 0}if(this._head===this._tail)return void 0;var r=this.size();var n=this._list.length;if(t>=r||t<-r)return void 0;if(t<0)t+=r;t=this._head+t&this._capacityMask;var o=this._list[t];var s;if(e0;s--){this._list[t]=this._list[t=t-1+n&this._capacityMask]}this._list[t]=void 0;this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--){this._list[t]=this._list[t=t+1+n&this._capacityMask]}this._list[t]=void 0;this._tail=this._tail-1+n&this._capacityMask}return o};Denque.prototype.remove=function remove(e,t){var r=e;var n;var o=t;if(r!==(r|0)){return void 0}if(this._head===this._tail)return void 0;var s=this.size();var i=this._list.length;if(r>=s||r<-s||t<1)return void 0;if(r<0)r+=s;if(t===1||!t){n=new Array(1);n[0]=this.removeOne(r);return n}if(r===0&&r+t>=s){n=this.toArray();this.clear();return n}if(r+t>s)t=s-r;var a;n=new Array(t);for(a=0;a0;a--){this._list[r=r+1+i&this._capacityMask]=void 0}return n}if(e===0){this._head=this._head+t+i&this._capacityMask;for(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])}r=this._head-1+i&this._capacityMask;while(o>0){this._list[r=r-1+i&this._capacityMask]=void 0;o--}if(e<0)this._tail=r}else{this._tail=r;r=r+t+i&this._capacityMask;for(a=s-(t+e);a>0;a--){this.push(this._list[r++])}r=this._tail;while(o>0){this._list[r=r+1+i&this._capacityMask]=void 0;o--}}if(this._head<2&&this._tail>1e4&&this._tail<=i>>>2)this._shrinkArray();return n};Denque.prototype.splice=function splice(e,t){var r=e;if(r!==(r|0)){return void 0}var n=this.size();if(r<0)r+=n;if(r>n)return void 0;if(arguments.length>2){var o;var s;var i;var a=arguments.length;var A=this._list.length;var c=2;if(!n||r0){this._head=this._head+r+A&this._capacityMask}}else{i=this.remove(r,t);this._head=this._head+r+A&this._capacityMask}while(a>c){this.unshift(arguments[--a])}for(o=r;o>0;o--){this.unshift(s[o-1])}}else{s=new Array(n-(r+t));var l=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1;this._capacityMask>>>=1};e.exports=Denque},1205:(e,t,r)=>{var n=r(1223);var noop=function(){};var isRequest=function(e){return e.setHeader&&typeof e.abort==="function"};var isChildProcess=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3};var eos=function(e,t,r){if(typeof t==="function")return eos(e,null,t);if(!t)t={};r=n(r||noop);var o=e._writableState;var s=e._readableState;var i=t.readable||t.readable!==false&&e.readable;var a=t.writable||t.writable!==false&&e.writable;var A=false;var onlegacyfinish=function(){if(!e.writable)onfinish()};var onfinish=function(){a=false;if(!i)r.call(e)};var onend=function(){i=false;if(!a)r.call(e)};var onexit=function(t){r.call(e,t?new Error("exited with error code: "+t):null)};var onerror=function(t){r.call(e,t)};var onclose=function(){process.nextTick(onclosenexttick)};var onclosenexttick=function(){if(A)return;if(i&&!(s&&(s.ended&&!s.destroyed)))return r.call(e,new Error("premature close"));if(a&&!(o&&(o.ended&&!o.destroyed)))return r.call(e,new Error("premature close"))};var onrequest=function(){e.req.on("finish",onfinish)};if(isRequest(e)){e.on("complete",onfinish);e.on("abort",onclose);if(e.req)onrequest();else e.on("request",onrequest)}else if(a&&!o){e.on("end",onlegacyfinish);e.on("close",onlegacyfinish)}if(isChildProcess(e))e.on("exit",onexit);e.on("end",onend);e.on("finish",onfinish);if(t.error!==false)e.on("error",onerror);e.on("close",onclose);return function(){A=true;e.removeListener("complete",onfinish);e.removeListener("abort",onclose);e.removeListener("request",onrequest);if(e.req)e.req.removeListener("finish",onfinish);e.removeListener("end",onlegacyfinish);e.removeListener("close",onlegacyfinish);e.removeListener("finish",onfinish);e.removeListener("exit",onexit);e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose)}};e.exports=eos},5010:(e,t,r)=>{var n=r(7147);var o=r(3837);var s=r(2781);var i=s.Readable;var a=s.Writable;var A=s.PassThrough;var c=r(4833);var l=r(2361).EventEmitter;t.createFromBuffer=createFromBuffer;t.createFromFd=createFromFd;t.BufferSlicer=BufferSlicer;t.FdSlicer=FdSlicer;o.inherits(FdSlicer,l);function FdSlicer(e,t){t=t||{};l.call(this);this.fd=e;this.pend=new c;this.pend.max=1;this.refCount=0;this.autoClose=!!t.autoClose}FdSlicer.prototype.read=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.read(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.write=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.write(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.createReadStream=function(e){return new ReadStream(this,e)};FdSlicer.prototype.createWriteStream=function(e){return new WriteStream(this,e)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var e=this;e.refCount-=1;if(e.refCount>0)return;if(e.refCount<0)throw new Error("invalid unref");if(e.autoClose){n.close(e.fd,onCloseDone)}function onCloseDone(t){if(t){e.emit("error",t)}else{e.emit("close")}}};o.inherits(ReadStream,i);function ReadStream(e,t){t=t||{};i.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end;this.pos=this.start;this.destroyed=false}ReadStream.prototype._read=function(e){var t=this;if(t.destroyed)return;var r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null){r=Math.min(r,t.endOffset-t.pos)}if(r<=0){t.destroyed=true;t.push(null);t.context.unref();return}t.context.pend.go((function(e){if(t.destroyed)return e();var o=new Buffer(r);n.read(t.context.fd,o,0,r,t.pos,(function(r,n){if(r){t.destroy(r)}else if(n===0){t.destroyed=true;t.push(null);t.context.unref()}else{t.pos+=n;t.push(o.slice(0,n))}e()}))}))};ReadStream.prototype.destroy=function(e){if(this.destroyed)return;e=e||new Error("stream destroyed");this.destroyed=true;this.emit("error",e);this.context.unref()};o.inherits(WriteStream,a);function WriteStream(e,t){t=t||{};a.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end==null?Infinity:+t.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}WriteStream.prototype._write=function(e,t,r){var o=this;if(o.destroyed)return;if(o.pos+e.length>o.endOffset){var s=new Error("maximum file length exceeded");s.code="ETOOBIG";o.destroy();r(s);return}o.context.pend.go((function(t){if(o.destroyed)return t();n.write(o.context.fd,e,0,e.length,o.pos,(function(e,n){if(e){o.destroy();t();r(e)}else{o.bytesWritten+=n;o.pos+=n;o.emit("progress");t();r()}}))}))};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};o.inherits(BufferSlicer,l);function BufferSlicer(e,t){l.call(this);t=t||{};this.refCount=0;this.buffer=e;this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}BufferSlicer.prototype.read=function(e,t,r,n,o){var s=n+r;var i=s-this.buffer.length;var a=i>0?i:r;this.buffer.copy(e,t,n,s);setImmediate((function(){o(null,a)}))};BufferSlicer.prototype.write=function(e,t,r,n,o){e.copy(this.buffer,n,t,t+r);setImmediate((function(){o(null,r,e)}))};BufferSlicer.prototype.createReadStream=function(e){e=e||{};var t=new A(e);t.destroyed=false;t.start=e.start||0;t.endOffset=e.end;t.pos=t.endOffset||this.buffer.length;var r=this.buffer.slice(t.start,t.pos);var n=0;while(true){var o=n+this.maxChunkSize;if(o>=r.length){if(nr.endOffset){var i=new Error("maximum file length exceeded");i.code="ETOOBIG";r.destroyed=true;o(i);return}e.copy(t.buffer,r.pos,0,e.length);r.bytesWritten+=e.length;r.pos=s;r.emit("progress");o()};r.destroy=function(){r.destroyed=true};return r};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(e,t){return new BufferSlicer(e,t)}function createFromFd(e,t){return new FdSlicer(e,t)}},7281:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(9930);const i=r(8098);const a=r(9126);const{env:A,cwd:c}=process;const isWritable=e=>{try{o.accessSync(e,o.constants.W_OK);return true}catch(e){return false}};function useDirectory(e,t){if(t.create){a.sync(e)}if(t.thunk){return(...t)=>n.join(e,...t)}return e}function getNodeModuleDirectory(e){const t=n.join(e,"node_modules");if(!isWritable(t)&&(o.existsSync(t)||!isWritable(n.join(e)))){return}return t}e.exports=(e={})=>{if(A.CACHE_DIR&&!["true","false","1","0"].includes(A.CACHE_DIR)){return useDirectory(n.join(A.CACHE_DIR,e.name),e)}let{cwd:t=c()}=e;if(e.files){t=s(t,e.files)}t=i.sync(t);if(!t){return}const r=getNodeModuleDirectory(t);if(!r){return undefined}return useDirectory(n.join(t,"node_modules",".cache",e.name),e)}},3186:(e,t,r)=>{e.exports=r(7147).constants||r(2057)},6863:(e,t,r)=>{e.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var n=r(7147);var o=n.realpath;var s=n.realpathSync;var i=process.version;var a=/^v[0-5]\./.test(i);var A=r(1734);function newError(e){return e&&e.syscall==="realpath"&&(e.code==="ELOOP"||e.code==="ENOMEM"||e.code==="ENAMETOOLONG")}function realpath(e,t,r){if(a){return o(e,t,r)}if(typeof t==="function"){r=t;t=null}o(e,t,(function(n,o){if(newError(n)){A.realpath(e,t,r)}else{r(n,o)}}))}function realpathSync(e,t){if(a){return s(e,t)}try{return s(e,t)}catch(r){if(newError(r)){return A.realpathSync(e,t)}else{throw r}}}function monkeypatch(){n.realpath=realpath;n.realpathSync=realpathSync}function unmonkeypatch(){n.realpath=o;n.realpathSync=s}},1734:(e,t,r)=>{var n=r(1017);var o=process.platform==="win32";var s=r(7147);var i=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function rethrow(){var e;if(i){var t=new Error;e=debugCallback}else e=missingCallback;return e;function debugCallback(e){if(e){t.message=e.message;e=t;missingCallback(e)}}function missingCallback(e){if(e){if(process.throwDeprecation)throw e;else if(!process.noDeprecation){var t="fs: missing callback "+(e.stack||e.message);if(process.traceDeprecation)console.trace(t);else console.error(t)}}}}function maybeCallback(e){return typeof e==="function"?e:rethrow()}var a=n.normalize;if(o){var A=/(.*?)(?:[\/\\]+|$)/g}else{var A=/(.*?)(?:[\/]+|$)/g}if(o){var c=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/}else{var c=/^[\/]*/}t.realpathSync=function realpathSync(e,t){e=n.resolve(e);if(t&&Object.prototype.hasOwnProperty.call(t,e)){return t[e]}var r=e,i={},a={};var l;var u;var h;var d;start();function start(){var t=c.exec(e);l=t[0].length;u=t[0];h=t[0];d="";if(o&&!a[h]){s.lstatSync(h);a[h]=true}}while(l=e.length){if(t)t[i]=e;return r(null,e)}A.lastIndex=u;var n=A.exec(e);g=h;h+=n[0];d=g+n[1];u=A.lastIndex;if(l[d]||t&&t[d]===d){return process.nextTick(LOOP)}if(t&&Object.prototype.hasOwnProperty.call(t,d)){return gotResolvedLink(t[d])}return s.lstat(d,gotStat)}function gotStat(e,n){if(e)return r(e);if(!n.isSymbolicLink()){l[d]=true;if(t)t[d]=d;return process.nextTick(LOOP)}if(!o){var i=n.dev.toString(32)+":"+n.ino.toString(32);if(a.hasOwnProperty(i)){return gotTarget(null,a[i],d)}}s.stat(d,(function(e){if(e)return r(e);s.readlink(d,(function(e,t){if(!o)a[i]=t;gotTarget(e,t)}))}))}function gotTarget(e,o,s){if(e)return r(e);var i=n.resolve(g,o);if(t)t[s]=i;gotResolvedLink(i)}function gotResolvedLink(t){e=n.resolve(t,e.slice(u));start()}}},3002:(e,t,r)=>{"use strict";const n=r(1808);class Locked extends Error{constructor(e){super(`${e} is locked`)}}const o={old:new Set,young:new Set};const s=1e3*15;let i;const getAvailablePort=e=>new Promise(((t,r)=>{const o=n.createServer();o.unref();o.on("error",r);o.listen(e,(()=>{const{port:e}=o.address();o.close((()=>{t(e)}))}))}));const portCheckSequence=function*(e){if(e){yield*e}yield 0};e.exports=async e=>{let t;if(e){t=typeof e.port==="number"?[e.port]:e.port}if(i===undefined){i=setInterval((()=>{o.old=o.young;o.young=new Set}),s);if(i.unref){i.unref()}}for(const r of portCheckSequence(t)){try{let t=await getAvailablePort({...e,port:r});while(o.old.has(t)||o.young.has(t)){if(r!==0){throw new Locked(r)}t=await getAvailablePort({...e,port:r})}o.young.add(t);return t}catch(e){if(!["EADDRINUSE","EACCES"].includes(e.code)&&!(e instanceof Locked)){throw e}}}throw new Error("No available ports found")};e.exports.makeRange=(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)){throw new TypeError("`from` and `to` must be integer numbers")}if(e<1024||e>65535){throw new RangeError("`from` must be between 1024 and 65535")}if(t<1024||t>65536){throw new RangeError("`to` must be between 1024 and 65536")}if(t{t.setopts=setopts;t.ownProp=ownProp;t.makeAbs=makeAbs;t.finish=finish;t.mark=mark;t.isIgnored=isIgnored;t.childrenIgnored=childrenIgnored;function ownProp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var n=r(1017);var o=r(3973);var s=r(8714);var i=o.Minimatch;function alphasort(e,t){return e.localeCompare(t,"en")}function setupIgnores(e,t){e.ignore=t.ignore||[];if(!Array.isArray(e.ignore))e.ignore=[e.ignore];if(e.ignore.length){e.ignore=e.ignore.map(ignoreMap)}}function ignoreMap(e){var t=null;if(e.slice(-3)==="/**"){var r=e.replace(/(\/\*\*)+$/,"");t=new i(r,{dot:true})}return{matcher:new i(e,{dot:true}),gmatcher:t}}function setopts(e,t,r){if(!r)r={};if(r.matchBase&&-1===t.indexOf("/")){if(r.noglobstar){throw new Error("base matching requires globstar")}t="**/"+t}e.silent=!!r.silent;e.pattern=t;e.strict=r.strict!==false;e.realpath=!!r.realpath;e.realpathCache=r.realpathCache||Object.create(null);e.follow=!!r.follow;e.dot=!!r.dot;e.mark=!!r.mark;e.nodir=!!r.nodir;if(e.nodir)e.mark=true;e.sync=!!r.sync;e.nounique=!!r.nounique;e.nonull=!!r.nonull;e.nosort=!!r.nosort;e.nocase=!!r.nocase;e.stat=!!r.stat;e.noprocess=!!r.noprocess;e.absolute=!!r.absolute;e.maxLength=r.maxLength||Infinity;e.cache=r.cache||Object.create(null);e.statCache=r.statCache||Object.create(null);e.symlinks=r.symlinks||Object.create(null);setupIgnores(e,r);e.changedCwd=false;var o=process.cwd();if(!ownProp(r,"cwd"))e.cwd=o;else{e.cwd=n.resolve(r.cwd);e.changedCwd=e.cwd!==o}e.root=r.root||n.resolve(e.cwd,"/");e.root=n.resolve(e.root);if(process.platform==="win32")e.root=e.root.replace(/\\/g,"/");e.cwdAbs=s(e.cwd)?e.cwd:makeAbs(e,e.cwd);if(process.platform==="win32")e.cwdAbs=e.cwdAbs.replace(/\\/g,"/");e.nomount=!!r.nomount;r.nonegate=true;r.nocomment=true;e.minimatch=new i(t,r);e.options=e.minimatch.options}function finish(e){var t=e.nounique;var r=t?[]:Object.create(null);for(var n=0,o=e.matches.length;n{e.exports=glob;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(4124);var A=r(2361).EventEmitter;var c=r(1017);var l=r(9491);var u=r(8714);var h=r(9010);var d=r(7625);var g=d.setopts;var p=d.ownProp;var E=r(2492);var m=r(3837);var C=d.childrenIgnored;var I=d.isIgnored;var y=r(1223);function glob(e,t,r){if(typeof t==="function")r=t,t={};if(!t)t={};if(t.sync){if(r)throw new TypeError("callback provided to sync glob");return h(e,t)}return new Glob(e,t,r)}glob.sync=h;var B=glob.GlobSync=h.GlobSync;glob.glob=glob;function extend(e,t){if(t===null||typeof t!=="object"){return e}var r=Object.keys(t);var n=r.length;while(n--){e[r[n]]=t[r[n]]}return e}glob.hasMagic=function(e,t){var r=extend({},t);r.noprocess=true;var n=new Glob(e,r);var o=n.minimatch.set;if(!e)return false;if(o.length>1)return true;for(var s=0;sthis.maxLength)return t();if(!this.stat&&p(this.cache,r)){var s=this.cache[r];if(Array.isArray(s))s="DIR";if(!o||s==="DIR")return t(null,s);if(o&&s==="FILE")return t()}var i;var a=this.statCache[r];if(a!==undefined){if(a===false)return t(null,a);else{var A=a.isDirectory()?"DIR":"FILE";if(o&&A==="FILE")return t();else return t(null,A,a)}}var c=this;var l=E("stat\0"+r,lstatcb_);if(l)n.lstat(r,l);function lstatcb_(o,s){if(s&&s.isSymbolicLink()){return n.stat(r,(function(n,o){if(n)c._stat2(e,r,null,s,t);else c._stat2(e,r,n,o,t)}))}else{c._stat2(e,r,o,s,t)}}};Glob.prototype._stat2=function(e,t,r,n,o){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR")){this.statCache[t]=false;return o()}var s=e.slice(-1)==="/";this.statCache[t]=n;if(t.slice(-1)==="/"&&n&&!n.isDirectory())return o(null,false,n);var i=true;if(n)i=n.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||i;if(s&&i==="FILE")return o();return o(null,i,n)}},9010:(e,t,r)=>{e.exports=globSync;globSync.GlobSync=GlobSync;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(1957).Glob;var A=r(3837);var c=r(1017);var l=r(9491);var u=r(8714);var h=r(7625);var d=h.setopts;var g=h.ownProp;var p=h.childrenIgnored;var E=h.isIgnored;function globSync(e,t){if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(e,t).found}function GlobSync(e,t){if(!e)throw new Error("must provide pattern");if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(e,t);d(this,e,t);if(this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;nthis.maxLength)return false;if(!this.stat&&g(this.cache,t)){var o=this.cache[t];if(Array.isArray(o))o="DIR";if(!r||o==="DIR")return o;if(r&&o==="FILE")return false}var s;var i=this.statCache[t];if(!i){var a;try{a=n.lstatSync(t)}catch(e){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[t]=false;return false}}if(a&&a.isSymbolicLink()){try{i=n.statSync(t)}catch(e){i=a}}else{i=a}}this.statCache[t]=i;var o=true;if(i)o=i.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||o;if(r&&o==="FILE")return false;return o};GlobSync.prototype._mark=function(e){return h.mark(this,e)};GlobSync.prototype._makeAbs=function(e){return h.makeAbs(this,e)}},1621:e=>{"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":e.length===1?"-":"--";const n=t.indexOf(r+e);const o=t.indexOf("--");return n!==-1&&(o===-1||n{h("replaying proxy buffer for failed request");A.default(e.listenerCount("data")>0);e.push(C);e.push(null)}));return I}))}}t["default"]=HttpsProxyAgent;function resume(e){e.resume()}function isDefaultPort(e,t){return Boolean(!t&&e===80||t&&e===443)}function isHTTPS(e){return typeof e==="string"?/^https:?$/i.test(e):false}function omit(e,...t){const r={};let n;for(n in e){if(!t.includes(n)){r[n]=e[n]}}return r}},7219:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(3734));function createHttpsProxyAgent(e){return new o.default(e)}(function(e){e.HttpsProxyAgent=o.default;e.prototype=o.default.prototype})(createHttpsProxyAgent||(createHttpsProxyAgent={}));e.exports=createHttpsProxyAgent},595:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=n(r(8237));const s=o.default("https-proxy-agent:parse-proxy-response");function parseProxyResponse(e){return new Promise(((t,r)=>{let n=0;const o=[];function read(){const t=e.read();if(t)ondata(t);else e.once("readable",read)}function cleanup(){e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose);e.removeListener("readable",read)}function onclose(e){s("onclose had error %o",e)}function onend(){s("onend")}function onerror(e){cleanup();s("onerror %o",e);r(e)}function ondata(e){o.push(e);n+=e.length;const r=Buffer.concat(o,n);const i=r.indexOf("\r\n\r\n");if(i===-1){s("have not received end of HTTP headers yet...");read();return}const a=r.toString("ascii",0,r.indexOf("\r\n"));const A=+a.split(" ")[1];s("got proxy server response: %o",a);t({statusCode:A,buffered:r})}e.on("error",onerror);e.on("close",onclose);e.on("end",onend);read()}))}t["default"]=parseProxyResponse},2492:(e,t,r)=>{var n=r(2940);var o=Object.create(null);var s=r(1223);e.exports=n(inflight);function inflight(e,t){if(o[e]){o[e].push(t);return null}else{o[e]=[t];return makeres(e)}}function makeres(e){return s((function RES(){var t=o[e];var r=t.length;var n=slice(arguments);try{for(var s=0;sr){t.splice(0,r);process.nextTick((function(){RES.apply(null,n)}))}else{delete o[e]}}}))}function slice(e){var t=e.length;var r=[];for(var n=0;n{try{var n=r(3837);if(typeof n.inherits!=="function")throw"";e.exports=n.inherits}catch(t){e.exports=r(8544)}},8544:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9126:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const{promisify:s}=r(3837);const i=r(1383);const a=i.satisfies(process.version,">=10.12.0");const checkPath=e=>{if(process.platform==="win32"){const t=/[<>:"|?*]/.test(e.replace(o.parse(e).root,""));if(t){const t=new Error(`Path contains invalid characters: ${e}`);t.code="EINVAL";throw t}}};const processOptions=e=>{const t={mode:511,fs:n};return{...t,...e}};const permissionError=e=>{const t=new Error(`operation not permitted, mkdir '${e}'`);t.code="EPERM";t.errno=-4048;t.path=e;t.syscall="mkdir";return t};const makeDir=async(e,t)=>{checkPath(e);t=processOptions(t);const r=s(t.fs.mkdir);const i=s(t.fs.stat);if(a&&t.fs.mkdir===n.mkdir){const n=o.resolve(e);await r(n,{mode:t.mode,recursive:true});return n}const make=async e=>{try{await r(e,t.mode);return e}catch(t){if(t.code==="EPERM"){throw t}if(t.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(t.message.includes("null bytes")){throw t}await make(o.dirname(e));return make(e)}try{const t=await i(e);if(!t.isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw t}return e}};return make(o.resolve(e))};e.exports=makeDir;e.exports.sync=(e,t)=>{checkPath(e);t=processOptions(t);if(a&&t.fs.mkdirSync===n.mkdirSync){const r=o.resolve(e);n.mkdirSync(r,{mode:t.mode,recursive:true});return r}const make=e=>{try{t.fs.mkdirSync(e,t.mode)}catch(r){if(r.code==="EPERM"){throw r}if(r.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(r.message.includes("null bytes")){throw r}make(o.dirname(e));return make(e)}try{if(!t.fs.statSync(e).isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw r}}return e};return make(o.resolve(e))}},1446:(e,t,r)=>{const n=r(6113);const o=r(7147);const s=8192;function md5FileSync(e){const t=o.openSync(e,"r");const r=n.createHash("md5");const i=Buffer.alloc(s);try{let e;do{e=o.readSync(t,i,0,s);r.update(i.slice(0,e))}while(e===s)}finally{o.closeSync(t)}return r.digest("hex")}function md5File(e){return new Promise(((t,r)=>{const s=n.createHash("md5");const i=o.createReadStream(e);i.on("error",(e=>{r(e)}));s.once("readable",(()=>{t(s.read().toString("hex"))}));i.pipe(s)}))}e.exports=md5File;e.exports.sync=md5FileSync},1529:e=>{e.exports=Pager;function Pager(e,t){if(!(this instanceof Pager))return new Pager(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?alloc(this.deduplicate.length):null}Pager.prototype.updated=function(e){while(this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate]){e.deduplicate++;if(e.deduplicate===this.deduplicate.length){e.deduplicate=0;if(e.buffer.equals&&e.buffer.equals(this.deduplicate))e.buffer=this.deduplicate;break}}if(e.updated||!this.updates)return;e.updated=true;this.updates.push(e)};Pager.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();e.updated=false;return e};Pager.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;grow(this,e)}factor(e,this.path);var r=this.pages;for(var n=this.level;n>0;n--){var o=this.path[n];var s=r[o];if(!s){if(t)return;s=r[o]=new Array(32768)}r=s}return r};Pager.prototype.get=function(e,t){var r=this._array(e,t);var n=this.path[0];var o=r&&r[n];if(!o&&!t){o=r[n]=new Page(e,alloc(this.pageSize));if(e>=this.length)this.length=e+1}if(o&&o.buffer===this.deduplicate&&this.deduplicate&&!t){o.buffer=copy(o.buffer);o.deduplicate=0}return o};Pager.prototype.set=function(e,t){var r=this._array(e,false);var n=this.path[0];if(e>=this.length)this.length=e+1;if(!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=undefined;return}if(this.deduplicate&&t.equals&&t.equals(this.deduplicate)){t=this.deduplicate}var o=r[n];var s=truncate(t,this.pageSize);if(o)o.buffer=s;else r[n]=new Page(e,s)};Pager.prototype.toBuffer=function(){var e=new Array(this.length);var t=alloc(this.pageSize);var r=0;while(rt)return e.slice(0,t);var r=alloc(t);e.copy(r);return r}function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function copy(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);e.copy(t);return t}function Page(e,t){this.offset=e*t.length;this.buffer=t;this.updated=false;this.deduplicate=0}function factor(e,t){e=(e-(t[0]=e&32767))/32768;e=(e-(t[1]=e&32767))/32768;t[3]=(e-(t[2]=e&32767))/32768&32767}},3973:(e,t,r)=>{e.exports=minimatch;minimatch.Minimatch=Minimatch;var n=function(){try{return r(1017)}catch(e){}}()||{sep:"/"};minimatch.sep=n.sep;var o=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={};var s=r(3717);var i={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};var a="[^/]";var A=a+"*?";var c="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var l="(?:(?!(?:\\/|^)\\.).)*?";var u=charSet("().*{}+?[]^$\\!");function charSet(e){return e.split("").reduce((function(e,t){e[t]=true;return e}),{})}var h=/\/+/;minimatch.filter=filter;function filter(e,t){t=t||{};return function(r,n,o){return minimatch(r,e,t)}}function ext(e,t){t=t||{};var r={};Object.keys(e).forEach((function(t){r[t]=e[t]}));Object.keys(t).forEach((function(e){r[e]=t[e]}));return r}minimatch.defaults=function(e){if(!e||typeof e!=="object"||!Object.keys(e).length){return minimatch}var t=minimatch;var r=function minimatch(r,n,o){return t(r,n,ext(e,o))};r.Minimatch=function Minimatch(r,n){return new t.Minimatch(r,ext(e,n))};r.Minimatch.defaults=function defaults(r){return t.defaults(ext(e,r)).Minimatch};r.filter=function filter(r,n){return t.filter(r,ext(e,n))};r.defaults=function defaults(r){return t.defaults(ext(e,r))};r.makeRe=function makeRe(r,n){return t.makeRe(r,ext(e,n))};r.braceExpand=function braceExpand(r,n){return t.braceExpand(r,ext(e,n))};r.match=function(r,n,o){return t.match(r,n,ext(e,o))};return r};Minimatch.defaults=function(e){return minimatch.defaults(e).Minimatch};function minimatch(e,t,r){assertValidPattern(t);if(!r)r={};if(!r.nocomment&&t.charAt(0)==="#"){return false}return new Minimatch(t,r).match(e)}function Minimatch(e,t){if(!(this instanceof Minimatch)){return new Minimatch(e,t)}assertValidPattern(e);if(!t)t={};e=e.trim();if(!t.allowWindowsEscape&&n.sep!=="/"){e=e.split(n.sep).join("/")}this.options=t;this.set=[];this.pattern=e;this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.partial=!!t.partial;this.make()}Minimatch.prototype.debug=function(){};Minimatch.prototype.make=make;function make(){var e=this.pattern;var t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate();var r=this.globSet=this.braceExpand();if(t.debug)this.debug=function debug(){console.error.apply(console,arguments)};this.debug(this.pattern,r);r=this.globParts=r.map((function(e){return e.split(h)}));this.debug(this.pattern,r);r=r.map((function(e,t,r){return e.map(this.parse,this)}),this);this.debug(this.pattern,r);r=r.filter((function(e){return e.indexOf(false)===-1}));this.debug(this.pattern,r);this.set=r}Minimatch.prototype.parseNegate=parseNegate;function parseNegate(){var e=this.pattern;var t=false;var r=this.options;var n=0;if(r.nonegate)return;for(var o=0,s=e.length;od){throw new TypeError("pattern is too long")}};Minimatch.prototype.parse=parse;var g={};function parse(e,t){assertValidPattern(e);var r=this.options;if(e==="**"){if(!r.noglobstar)return o;else e="*"}if(e==="")return"";var n="";var s=!!r.nocase;var c=false;var l=[];var h=[];var d;var p=false;var E=-1;var m=-1;var C=e.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var I=this;function clearStateChar(){if(d){switch(d){case"*":n+=A;s=true;break;case"?":n+=a;s=true;break;default:n+="\\"+d;break}I.debug("clearStateChar %j %j",d,n);d=false}}for(var y=0,B=e.length,Q;y-1;D--){var N=h[D];var T=n.slice(0,N.reStart);var O=n.slice(N.reStart,N.reEnd-8);var _=n.slice(N.reEnd-8,N.reEnd);var M=n.slice(N.reEnd);_+=M;var L=T.split("(").length-1;var F=M;for(y=0;y=0;i--){s=e[i];if(s)break}for(i=0;i>> no match, partial?",e,u,t,h);if(u===a)return true}return false}var g;if(typeof c==="string"){g=l===c;this.debug("string match",c,l,g)}else{g=l.match(c);this.debug("pattern match",c,l,g)}if(!g)return false}if(s===a&&i===A){return true}else if(s===a){return r}else if(i===A){return s===a-1&&e[s]===""}throw new Error("wtf?")};function globUnescape(e){return e.replace(/\\(.)/g,"$1")}function regExpEscape(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},1257:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoMemoryServer=t.MongoMemoryServerStates=t.MongoMemoryServerEvents=void 0;const n=r(4351);const o=(0,n.__importStar)(r(8517));const s=(0,n.__importDefault)(r(3002));const i=r(1978);const a=r(843);const A=(0,n.__importDefault)(r(8237));const c=r(2361);const l=r(7147);const u=r(5517);const h=r(1383);const d=r(3386);const g=(0,A.default)("MongoMS:MongoMemoryServer");o.setGracefulCleanup();var p;(function(e){e["stateChange"]="stateChange"})(p=t.MongoMemoryServerEvents||(t.MongoMemoryServerEvents={}));var E;(function(e){e["new"]="new";e["starting"]="starting";e["running"]="running";e["stopped"]="stopped"})(E=t.MongoMemoryServerStates||(t.MongoMemoryServerStates={}));class MongoMemoryServer extends c.EventEmitter{constructor(e){super();this._state=E.new;this.opts=Object.assign({},e);if(!(0,i.isNullOrUndefined)(this.opts.auth)){this.auth=(0,i.authDefault)(this.opts.auth)}}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("create: Called .create() method");const t=new MongoMemoryServer(Object.assign({},e));yield t.start();return t}))}start(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start: Called .start() method");switch(this._state){case E.new:case E.stopped:break;case E.running:case E.starting:default:throw new d.StateError([E.new,E.stopped],this.state)}(0,i.assertion)((0,i.isNullOrUndefined)((t=this._instanceInfo)===null||t===void 0?void 0:t.instance.mongodProcess),new Error('Cannot start because "instance.mongodProcess" is already defined!'));this.stateChange(E.starting);yield this._startUpInstance(e).catch((e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!A.default.enabled("MongoMS:MongoMemoryServer")){console.warn("Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n",e)}this.debug("_startUpInstance threw a Error: ",e);yield this.stop({doCleanup:false,force:false});this.stateChange(E.stopped);throw e}))));this.stateChange(E.running);this.debug("start: Instance fully Started")}))}stateChange(e){this._state=e;this.emit(p.stateChange,e)}debug(e,...t){var r,n;const o=(n=(r=this._instanceInfo)===null||r===void 0?void 0:r.port)!==null&&n!==void 0?n:"unknown";g(`Mongo[${o}]: ${e}`,...t)}getNewPort(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield(0,s.default)({port:e});if(e!=t&&typeof e==="number"){this.debug(`getNewPort: starting with port "${t}", since "${e}" was locked`)}return t}))}getStartOptions(e=false){var t,r,s;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`getStartOptions: forceSamePort: ${e}`);const n=(t=this.opts.instance)!==null&&t!==void 0?t:{};let a=true;let A=typeof n.port==="number"?n.port:undefined;if(!e||(0,i.isNullOrUndefined)(A)){A=yield this.getNewPort(A)}const c={port:A,dbName:(0,i.generateDbName)(n.dbName),ip:(r=n.ip)!==null&&r!==void 0?r:"127.0.0.1",storageEngine:(s=n.storageEngine)!==null&&s!==void 0?s:"ephemeralForTest",replSet:n.replSet,dbPath:n.dbPath,tmpDir:undefined};if((0,i.isNullOrUndefined)(this._instanceInfo)){if(!c.dbPath){c.tmpDir=o.dirSync({mode:493,prefix:"mongo-mem-",unsafeCleanup:true});c.dbPath=c.tmpDir.name;a=true}else{this.debug(`getStartOptions: Checking if "${c.dbPath}}" (no new tmpDir) already has data`);const e=yield l.promises.readdir(c.dbPath);a=e.length===0}}else{a=false}const u=(typeof n.auth==="boolean"?n.auth:true)&&!(0,i.isNullOrUndefined)(this.auth)&&!this.auth.disable&&(this.auth.force||a)&&!n.replSet;return{data:c,createAuth:u,mongodOptions:{instance:Object.assign(Object.assign({},c),{args:n.args,auth:u?false:n.auth}),binary:this.opts.binary,spawn:this.opts.spawn}}}))}_startUpInstance(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("_startUpInstance: Called MongoMemoryServer._startUpInstance() method");if(!(0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');if(!e){const e=yield this.getNewPort(this._instanceInfo.port);this._instanceInfo.instance.instanceOpts.port=e;this._instanceInfo.port=e}yield this._instanceInfo.instance.start();return}const{mongodOptions:r,createAuth:n,data:o}=yield this.getStartOptions(e);this.debug(`_startUpInstance: Creating new MongoDB instance with options:`,r);const s=yield a.MongoInstance.create(r);this.debug(`_startUpInstance: Instance Started, createAuth: "${n}"`);if(!(0,i.isNullOrUndefined)(this.auth)&&n){this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);yield this.createAuth(o);if(o.storageEngine!=="ephemeralForTest"){this.debug("_startUpInstance: Killing No-Auth instance");yield s.stop();this.debug("_startUpInstance: Starting Auth Instance");s.instanceOpts.auth=true;yield s.start()}else{console.warn("Not Restarting MongoInstance for Auth\n"+'Storage engine is "ephemeralForTest", which does not write data on shutdown, and mongodb does not allow changing "auth" runtime')}}else{if((t=this.opts.auth)===null||t===void 0?void 0:t.disable){this.debug('_startUpInstance: AutomaticAuth.disable is set to "true" skipping "createAuth"')}}this._instanceInfo=Object.assign(Object.assign({},o),{dbPath:o.dbPath,instance:s})}))}stop(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop: Called .stop() method");let n={doCleanup:true,force:false};if(typeof e==="boolean"){n.doCleanup=e}if(typeof e==="object"){n=e}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('stop: "instanceInfo" is not defined (never ran?)');return false}if(this._state===E.stopped){this.debug('stop: state is "stopped", trying to stop / kill anyway')}this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${(r=(t=this._instanceInfo.instance)===null||t===void 0?void 0:t.mongodProcess)===null||r===void 0?void 0:r.pid}`);yield this._instanceInfo.instance.stop();this.stateChange(E.stopped);if(n.doCleanup){yield this.cleanup(n)}return true}))}cleanup(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){assertionIsMMSState(E.stopped,this.state);let t={doCleanup:true,force:false};if(typeof e==="boolean"){t.force=e}if(typeof e==="object"){t=e}this.debug(`cleanup:`,t);if(!t.doCleanup){this.debug('cleanup: "doCleanup" is set to false');return}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('cleanup: "instanceInfo" is undefined');return}(0,i.assertion)((0,i.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess),new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));const r=this._instanceInfo.tmpDir;if(!(0,i.isNullOrUndefined)(r)){this.debug(`cleanup: removing tmpDir at ${r.name}`);r.removeCallback()}if(t.force){const e=this._instanceInfo.dbPath;const t=yield(0,i.statPath)(e);if((0,i.isNullOrUndefined)(t)){this.debug(`cleanup: force is true, but path "${e}" dosnt exist anymore`)}else{(0,i.assertion)(t.isDirectory(),new Error("Defined dbPath is not an directory"));if((0,h.lt)(process.version,"14.14.0")){yield l.promises.rmdir(e,{recursive:true,maxRetries:1})}else{yield l.promises.rm(e,{recursive:true,maxRetries:1})}}}this.stateChange(E.new);this._instanceInfo=undefined}))}get instanceInfo(){return this._instanceInfo}get state(){return this._state}ensureInstance(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("ensureInstance: Called .ensureInstance() method");switch(this._state){case E.running:if(this._instanceInfo){return this._instanceInfo}throw new d.EnsureInstanceError(true);case E.new:case E.stopped:break;case E.starting:return new Promise(((e,t)=>this.once(p.stateChange,(r=>{if(r!=E.running){t(new Error(`"ensureInstance" waited for "running" but got an different state: "${r}"`));return}(0,i.assertion)(!(0,i.isNullOrUndefined)(this._instanceInfo),new Error("InstanceInfo is undefined!"));e(this._instanceInfo)}))));default:throw new d.StateError([E.running,E.new,E.stopped,E.starting],this.state)}this.debug('ensureInstance: no running instance, calling "start()" command');yield this.start();this.debug('ensureInstance: "start()" command was succesfully resolved');if(!this._instanceInfo){throw new d.EnsureInstanceError(false)}return this._instanceInfo}))}getUri(e,t){this.debug("getUri:",this.state,e,t);switch(this.state){case E.running:case E.starting:break;case E.stopped:default:throw new d.StateError([E.running,E.starting],this.state)}assertionInstanceInfo(this._instanceInfo);return(0,i.uriTemplate)(t||"127.0.0.1",this._instanceInfo.port,(0,i.generateDbName)(e))}createAuth(e){var t,r,o;return(0,n.__awaiter)(this,void 0,void 0,(function*(){(0,i.assertion)(!(0,i.isNullOrUndefined)(this.auth),new Error('"createAuth" got called, but "this.auth" is undefined!'));this.debug("createAuth: options:",this.auth);const n=yield u.MongoClient.connect((0,i.uriTemplate)(e.ip,e.port,"admin"),{});try{let e=n.db("admin");this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);yield e.command({createUser:this.auth.customRootName,pwd:this.auth.customRootPwd,mechanisms:["SCRAM-SHA-256"],customData:{createdBy:"mongodb-memory-server",as:"ROOTUSER"},roles:["root"],writeConcern:{w:"majority"}});if(this.auth.extraUsers.length>0){this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);this.auth.extraUsers.sort(((e,t)=>{if(e.database==="admin"){return-1}return e.database===t.database?0:1}));for(const s of this.auth.extraUsers){s.database=(0,i.isNullOrUndefined)(s.database)?"admin":s.database;if(s.database!==e.databaseName){e=n.db(s.database)}this.debug("createAuth: Creating User: ",s);yield e.command({createUser:s.createUser,pwd:s.pwd,customData:Object.assign(Object.assign({},s.customData),{createdBy:"mongodb-memory-server",as:"EXTRAUSER"}),roles:s.roles,authenticationRestrictions:(t=s.authenticationRestrictions)!==null&&t!==void 0?t:[],mechanisms:(r=s.mechanisms)!==null&&r!==void 0?r:["SCRAM-SHA-256"],digestPassword:(o=s.digestPassword)!==null&&o!==void 0?o:true})}}}finally{yield n.close()}}))}}t.MongoMemoryServer=MongoMemoryServer;t["default"]=MongoMemoryServer;function assertionInstanceInfo(e){(0,i.assertion)(!(0,i.isNullOrUndefined)(e),new Error('"instanceInfo" is undefined'))}function assertionIsMMSState(e,t){(0,i.assertion)(t===e,new d.StateError([e],t))}},8919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.DryMongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(8730);const i=r(1978);const a=(0,n.__importStar)(r(1017));const A=r(2037);const c=(0,n.__importDefault)(r(7281));const l=r(8278);const u=r(3386);const h=r(1);const d=(0,o.default)("MongoMS:DryMongoBinary");class DryMongoBinary{static locateBinary(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d(`locateBinary: Trying to locate Binary for version "${e.version}"`);const t=yield this.generateOptions(e);if(!!t.systemBinary){d(`locateBinary: env "SYSTEM_BINARY" was provided with value: "${t.systemBinary}"`);const e=yield this.getSystemPath(t.systemBinary);if((0,i.isNullOrUndefined)(e)){throw new u.NoSystemBinaryFoundError(t.systemBinary)}return e}if(this.binaryCache.has(e.version)){const t=this.binaryCache.get(e.version);d(`locateBinary: Requested Version found in cache: "[${e.version}, ${t}]"`);return t}d("locateBinary: running generateDownloadPath");const r=yield this.generateDownloadPath(t);if(!r[0]){d("locateBinary: could not find a existing binary");return undefined}d(`locateBinary: found binary at "${r[1]}"`);this.binaryCache.set(e.version,r[1]);return r[1]}))}static generateOptions(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generateOptions");const n=(t=(0,s.resolveConfig)(s.ResolveConfigVariables.VERSION))!==null&&t!==void 0?t:s.DEFAULT_VERSION;const o=(0,i.isNullOrUndefined)(e)?{version:n}:e;const c={version:o.version||n,downloadDir:(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR)||o.downloadDir||"",os:(r=o.os)!==null&&r!==void 0?r:yield(0,l.getOS)(),platform:o.platform||(0,A.platform)(),arch:o.arch||(0,A.arch)(),systemBinary:(0,s.resolveConfig)(s.ResolveConfigVariables.SYSTEM_BINARY)||o.systemBinary||""};c.downloadDir=a.dirname((yield this.generateDownloadPath(c))[1]);if((0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME)||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)||(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);d(`generateOptions: ARCHIVE_NAME or DOWNLOAD_URL defined, generating options based on that (input: "${e}")`);return this.parseArchiveNameRegex(e,c)}return c}))}static parseArchiveNameRegex(e,t){d(`parseArchiveNameRegex (input: "${e}")`);const r=/mongodb-(?linux|win32|osx|macos)(?:-ssl-|-)(?\w{4,})(?:-(?\w+)|)(?:-ssl-|-)(?:v|)(?[\d.]+(?:-latest|))\./gim.exec(e);(0,i.assertion)(!(0,i.isNullOrUndefined)(r),new u.NoRegexMatchError("input"));(0,i.assertion)(!(0,i.isNullOrUndefined)(r.groups),new u.NoRegexMatchError("input","groups"));const n=r.groups;(0,i.assertion)(typeof n.version==="string"&&n.version.length>1,new u.ParseArchiveRegexError("version"));(0,i.assertion)(typeof n.platform==="string"&&n.platform.length>1,new u.ParseArchiveRegexError("platform"));(0,i.assertion)(typeof n.arch==="string"&&n.arch.length>=4,new u.ParseArchiveRegexError("arch"));t.version=n.version;t.arch=n.arch;if(n.platform==="linux"){const e=!!n.dist?/([a-z]+)(\d*)/gim.exec(n.dist):null;t.os={os:"linux",dist:typeof(e===null||e===void 0?void 0:e[1])==="string"?e[1]:"unknown",release:""}}else{t.os={os:n.platform}}return t}static getBinaryName(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getBinaryName");let t;if((0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.USE_ARCHIVE_NAME_FOR_BINARY_NAME))){const r=yield new h.MongoBinaryDownloadUrl(e).getArchiveName();t=a.parse(r).name}else{const r=e.platform==="win32"?".exe":"";const n=(0,l.isLinuxOS)(e.os)?e.os.dist:e.os.os;t=`mongod-${e.arch}-${n}-${e.version}${r}`}return t}))}static combineBinaryName(e,t){d("combineBinaryName");return a.resolve(e,t)}static getSystemPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getSystempath");try{yield(0,i.checkBinaryPermissions)(e);d(`getSystemPath: found system binary path at "${e}"`);return e}catch(t){d(`getSystemPath: can't find system binary at "${e}".\n${t instanceof Error?t.message:t}`)}return undefined}))}static generatePaths(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generatePaths",e);const t={legacyHomeCache:"",modulesCache:"",relative:"",resolveConfig:""};const r=yield this.getBinaryName(e);let n=process.env["INIT_CWD"]||process.cwd();while(n.includes(`node_modules${a.sep}mongodb-memory-server`)){n=a.resolve(n,"..","..")}const o=(0,c.default)({name:"mongodb-memory-server",cwd:n});if(!(0,i.isNullOrUndefined)(o)){t.modulesCache=this.combineBinaryName(a.resolve(o),r)}const A=a.resolve(this.homedir(),".cache/mongodb-binaries");t.legacyHomeCache=this.combineBinaryName(A,r);const l=e.downloadDir||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR);if(!(0,i.isNullOrUndefined)(l)&&l.length>0){d(`generatePaths: resolveConfigValue is not empty`);t.resolveConfig=this.combineBinaryName(l,r)}t.relative=this.combineBinaryName(a.resolve(process.cwd(),"mongodb-binaries"),r);return t}))}static generateDownloadPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.PREFER_GLOBAL_PATH));d(`generateDownloadPath: Generating Download Path, preferGlobal: "${t}"`);const r=yield this.generatePaths(e);d("generateDownloadPath: Paths:",r,e.systemBinary);if(!!e.systemBinary&&(yield(0,i.pathExists)(e.systemBinary))){const t=yield this.getSystemPath(e.systemBinary);if(!(0,i.isNullOrUndefined)(t)){return[true,t]}}if(yield(0,i.pathExists)(r.resolveConfig)){d(`generateDownloadPath: Found binary in resolveConfig (DOWNLOAD_DIR): "${r.resolveConfig}"`);return[true,r.resolveConfig]}if(yield(0,i.pathExists)(r.legacyHomeCache)){d(`generateDownloadPath: Found binary in legacyHomeCache: "${r.legacyHomeCache}"`);return[true,r.legacyHomeCache]}if(yield(0,i.pathExists)(r.modulesCache)){d(`generateDownloadPath: Found binary in modulesCache: "${r.modulesCache}"`);return[true,r.modulesCache]}if(yield(0,i.pathExists)(r.relative)){d(`generateDownloadPath: Found binary in relative: "${r.relative}"`);return[true,r.relative]}d(`generateDownloadPath: no existing binary for version "${e.version}" was found`);if(r.resolveConfig.length>0){d(`generateDownloadPath: using resolveConfig (DOWNLOAD_DIR) "${r.resolveConfig}"`);return[false,r.resolveConfig]}if(t&&!!r.legacyHomeCache){d(`generateDownloadPath: using global (preferGlobal) "${r.legacyHomeCache}"`);return[false,r.legacyHomeCache]}if(r.modulesCache.length>0){d(`generateDownloadPath: using modulesCache "${r.modulesCache}"`);return[false,r.modulesCache]}d(`generateDownloadPath: using relative "${r.relative}"`);return[false,r.relative]}))}static homedir(){return(0,A.homedir)()}}t.DryMongoBinary=DryMongoBinary;DryMongoBinary.binaryCache=new Map},9125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=(0,n.__importDefault)(r(1017));const i=(0,n.__importDefault)(r(229));const a=(0,n.__importStar)(r(8730));const A=(0,n.__importDefault)(r(8237));const c=(0,n.__importStar)(r(1383));const l=r(1978);const u=r(2081);const h=r(4908);const d=r(8919);const g=(0,A.default)("MongoMS:MongoBinary");class MongoBinary{static download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("download");const{downloadDir:t,version:r}=e;yield(0,l.mkdir)(t);const n=s.default.resolve(t,`${r}.lock`);g(`download: Waiting to acquire Download lock for file "${n}"`);const o=yield h.LockFile.lock(n);g("download: Download lock acquired");try{if(!d.DryMongoBinary.binaryCache.has(r)){g(`download: Adding version ${r} to cache`);const t=new i.default(e);d.DryMongoBinary.binaryCache.set(r,yield t.getMongodPath())}}finally{g("download: Removing Download lock");yield o.unlock();g("download: Download lock removed")}const a=d.DryMongoBinary.binaryCache.get(r);(0,l.assertion)(typeof a==="string",new Error(`No Cache Path for version "${r}" found (and download failed silently?)`));return a}))}static getPath(e={}){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("getPath");const t=Object.assign(Object.assign({},yield d.DryMongoBinary.generateOptions(e)),{platform:e.platform||(0,a.default)(a.ResolveConfigVariables.PLATFORM)||o.default.platform(),checkMD5:e.checkMD5||(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.MD5_CHECK))});g(`getPath: MongoBinary options:`,JSON.stringify(t,null,2));let r=yield d.DryMongoBinary.locateBinary(t);if(!!t.systemBinary){if(!(0,l.isNullOrUndefined)(r)){g(`getPath: Spawning binaryPath "${r}" to get version`);const e=(0,u.spawnSync)(r,["--version"]).stdout.toString().match(/^\s*db\s+version\s+v?(\d+\.\d+\.\d+)(-\d*)?(-[a-zA-Z0-9].*)?\s*$/im);(0,l.assertion)(!(0,l.isNullOrUndefined)(e),new Error("Couldnt find an version from system binary output!"));if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.SYSTEM_BINARY_VERSION_CHECK))){g("getPath: Checking & Warning about version conflicts");const r=e[1];if(c.neq(t.version,r)){console.warn("getPath: MongoMemoryServer: Possible version conflict\n"+` SystemBinary version: "${r}"\n`+` Requested version: "${t.version}"\n\n`+" Using SystemBinary!")}}}else{throw new Error('Option "SYSTEM_BINARY" was set, but binaryPath was empty! (system binary could not be found?) [This Error should normally not be thrown, please report this]')}}(0,l.assertion)(typeof t.version==="string",new Error('"MongoBinary.options.version" is not an string!'));if(!r){if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD))){g('getPath: "RUNTIME_DOWNLOAD" is "true", trying to download');r=yield this.download(t)}else{g('getPath: "RUNTIME_DOWNLOAD" is "false", not downloading')}}if(!r){const e=(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD));throw new Error(`MongoBinary.getPath: could not find an valid binary path! (Got: "${r}", RUNTIME_DOWNLOAD: "${e}")`)}g(`getPath: Mongod binary path: "${r}"`);return r}))}}t.MongoBinary=MongoBinary;t["default"]=MongoBinary},229:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownload=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=r(7310);const i=(0,n.__importDefault)(r(1017));const a=r(7147);const A=(0,n.__importDefault)(r(1446));const c=(0,n.__importDefault)(r(5687));const l=r(9796);const u=(0,n.__importDefault)(r(2283));const h=(0,n.__importDefault)(r(8781));const d=(0,n.__importDefault)(r(1));const g=r(7219);const p=(0,n.__importStar)(r(8730));const E=(0,n.__importDefault)(r(8237));const m=r(1978);const C=r(8919);const I=r(4521);const y=r(3386);const B=(0,E.default)("MongoMS:MongoBinaryDownload");class MongoBinaryDownload{constructor(e){var t,r,n,s,i,a;(0,m.assertion)(typeof e.downloadDir==="string",new Error("An DownloadDir must be specified!"));const A=(t=e.version)!==null&&t!==void 0?t:(0,p.default)(p.ResolveConfigVariables.VERSION);(0,m.assertion)(typeof A==="string",new Error("An MongoDB Binary version must be specified!"));this.binaryOpts={platform:(r=e.platform)!==null&&r!==void 0?r:o.default.platform(),arch:(n=e.arch)!==null&&n!==void 0?n:o.default.arch(),version:A,downloadDir:e.downloadDir,checkMD5:(s=e.checkMD5)!==null&&s!==void 0?s:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.MD5_CHECK)),systemBinary:(i=e.systemBinary)!==null&&i!==void 0?i:"",os:(a=e.os)!==null&&a!==void 0?a:{os:"unknown"}};this.dlProgress={current:0,length:0,totalMb:0,lastPrintedAt:0}}get checkMD5(){return this.binaryOpts.checkMD5}set checkMD5(e){this.binaryOpts.checkMD5=e}get downloadDir(){return this.binaryOpts.downloadDir}set downloadDir(e){this.binaryOpts.downloadDir=e}get arch(){return this.binaryOpts.arch}set arch(e){this.binaryOpts.arch=e}get version(){return this.binaryOpts.version}set version(e){this.binaryOpts.version=e}get platform(){return this.binaryOpts.platform}set platform(e){this.binaryOpts.platform=e}getPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield C.DryMongoBinary.generateOptions(this.binaryOpts);return C.DryMongoBinary.combineBinaryName(this.downloadDir,yield C.DryMongoBinary.getBinaryName(e))}))}getMongodPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("getMongodPath");const e=yield this.getPath();if(yield(0,m.pathExists)(e)){B(`getMongodPath: mongod path "${e}" already exists, using this`);return e}const t=yield this.startDownload();yield this.extract(t);yield a.promises.unlink(t);if(yield(0,m.pathExists)(e)){return e}throw new Error(`Cannot find downloaded mongod binary by path "${e}"`)}))}startDownload(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("startDownload");const e=new d.default(this.binaryOpts);yield(0,m.mkdir)(this.downloadDir);try{yield a.promises.access(this.downloadDir,a.constants.X_OK|a.constants.W_OK)}catch(e){console.error(`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n`+"Needed Permissions: Write & Execute (-wx)\n");throw e}const t=yield e.getDownloadUrl();const r=yield this.download(t);yield this.makeMD5check(`${t}.md5`,r);return r}))}makeMD5check(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("makeMD5check: Checking MD5 of downloaded binary...");if(!this.checkMD5){B("makeMD5check: checkMD5 is disabled");return undefined}const r=yield this.download(e);const n=(yield a.promises.readFile(r)).toString("utf-8");const o=n.match(/^\s*([\w\d]+)\s*/i);const s=o?o[1]:null;const i=A.default.sync(t);B(`makeMD5check: Local MD5: ${i}, Remote MD5: ${s}`);if(s!==i){throw new y.Md5CheckFailedError(i,s||"unknown")}yield a.promises.unlink(r);return true}))}download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("download");const t=process.env["yarn_https-proxy"]||process.env.yarn_proxy||process.env["npm_config_https-proxy"]||process.env.npm_config_proxy||process.env.https_proxy||process.env.http_proxy||process.env.HTTPS_PROXY||process.env.HTTP_PROXY;const r=process.env.npm_config_strict_ssl==="true";const n=new s.URL(e);n.port=n.port||"443";const o={method:"GET",rejectUnauthorized:r,protocol:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.USE_HTTP))?"http:":"https:",agent:t?new g.HttpsProxyAgent(t):undefined};const a=n.pathname.split("/").pop();if(!a){throw new Error(`MongoBinaryDownload: missing filename for url "${e}"`)}const A=i.default.resolve(this.downloadDir,a);const c=i.default.resolve(this.downloadDir,`${a}.downloading`);B(`download: Downloading${t?` via proxy "${t}"`:""}: "${e}"`);if(yield(0,m.pathExists)(A)){B("download: Already downloaded archive found, skipping download");return A}this.assignDownloadingURL(n);const l=yield this.httpDownload(n,o,A,c);return l}))}extract(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extract");const n=yield this.getPath();B(`extract: archive: "${e}" final: "${n}"`);yield(0,m.mkdir)(i.default.dirname(n));const filter=e=>/(?:bin\/(?:mongod(?:\.exe)?)|(?:.*\.dll))$/i.test(e);if(/(.tar.gz|.tgz)$/.test(e)){yield this.extractTarGz(e,n,filter)}else if(/.zip$/.test(e)){yield this.extractZip(e,n,filter)}else{throw new Error(`MongoBinaryDownload: unsupported archive "${e}" (downloaded from "${(t=this._downloadingUrl)!==null&&t!==void 0?t:"unknown"}"). Broken archive from MongoDB Provider?`)}if(!(yield(0,m.pathExists)(n))){throw new Error(`MongoBinaryDownload: missing mongod binary in "${e}" (downloaded from "${(r=this._downloadingUrl)!==null&&r!==void 0?r:"unknown"}"). Broken archive from MongoDB Provider?`)}return n}))}extractTarGz(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractTarGz");const n=u.default.extract();n.on("entry",((e,n,o)=>{if(r(e.name)){n.pipe((0,a.createWriteStream)(t,{mode:509}))}n.on("end",(()=>o()));n.resume()}));return new Promise(((t,r)=>{(0,a.createReadStream)(e).on("error",(t=>{r("Unable to open tarball "+e+": "+t)})).pipe((0,l.createUnzip)()).on("error",(t=>{r("Error during unzip for "+e+": "+t)})).pipe(n).on("error",(t=>{r("Error during untar for "+e+": "+t)})).on("finish",(e=>{t(e)}))}))}))}extractZip(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractZip");return new Promise(((n,o)=>{h.default.open(e,{lazyEntries:true},((e,s)=>{if(e||!s){return o(e)}s.readEntry();s.on("end",(()=>n()));s.on("entry",(e=>{if(!r(e.fileName)){return s.readEntry()}s.openReadStream(e,((e,r)=>{if(e||!r){return o(e)}r.on("end",(()=>s.readEntry()));r.pipe((0,a.createWriteStream)(t,{mode:509}))}))}))}))}))}))}httpDownload(e,t,r,o){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("httpDownload");const s=this.assignDownloadingURL(e);return new Promise(((i,A)=>{B(`httpDownload: trying to download "${s}"`);c.default.get(e,t,(e=>{if(e.statusCode!=200){if(e.statusCode===403){A(new Error("Status Code is 403 (MongoDB's 404)\n"+"This means that the requested version-platform combination doesn't exist\n"+` Used Url: "${s}"\n`+"Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n"+"List of available versions can be found here:\n"+" https://www.mongodb.org/dl/linux for Linux\n"+" https://www.mongodb.org/dl/osx for OSX\n"+" https://www.mongodb.org/dl/win32 for Windows"));return}A(new Error("Status Code isnt 200!"));return}if(typeof e.headers["content-length"]!="string"){A(new Error('Response header "content-length" is empty!'));return}this.dlProgress.current=0;this.dlProgress.length=parseInt(e.headers["content-length"],10);this.dlProgress.totalMb=Math.round(this.dlProgress.length/1048576*10)/10;const c=(0,a.createWriteStream)(o);e.pipe(c);c.on("finish",(()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){var e;if(this.dlProgress.current{this.printDownloadProgress(e)}))})).on("error",(e=>{console.error(`Couldnt download "${s}"!`,e.message);A(e)}))}))}))}printDownloadProgress(e,t=false){this.dlProgress.current+=e.length;const r=Date.now();if(r-this.dlProgress.lastPrintedAt<2e3&&!t){return}this.dlProgress.lastPrintedAt=r;const n=Math.round(100*this.dlProgress.current/this.dlProgress.length*10)/10;const o=Math.round(this.dlProgress.current/1048576*10)/10;const s=this.platform==="win32"?"":"\r";const i=`Downloading MongoDB "${this.version}": ${n}% (${o}mb / ${this.dlProgress.totalMb}mb)${s}`;if(process.stdout.isTTY){(0,I.clearLine)(process.stdout,0);process.stdout.write(i)}else{console.log(i)}}assignDownloadingURL(e){this._downloadingUrl=e.href;return this._downloadingUrl}}t.MongoBinaryDownload=MongoBinaryDownload;t["default"]=MongoBinaryDownload},1:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownloadUrl=void 0;const n=r(4351);const o=r(8278);const s=r(8730);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1383));const A=r(1978);const c=r(7310);const l=r(3386);const u=r(3837);const h=(0,i.default)("MongoMS:MongoBinaryDownloadUrl");class MongoBinaryDownloadUrl{constructor(e){this.version=e.version;this.platform=this.translatePlatform(e.platform);this.arch=MongoBinaryDownloadUrl.translateArch(e.arch,this.platform);this.os=e.os}getDownloadUrl(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL);if(t){h(`Using "${t}" as the Download-URL`);const e=new c.URL(t);return e.toString()}const r=yield this.getArchiveName();h(`Using "${r}" as the Archive String`);const n=(e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_MIRROR))!==null&&e!==void 0?e:"https://fastdl.mongodb.org";h(`Using "${n}" as the mirror`);const o=new c.URL(n);if(!o.pathname.endsWith("/")){o.pathname=o.pathname+"/"}o.pathname=`${o.pathname}${this.platform}/${r}`;return o.toString()}))}getArchiveName(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);if(!!e){return e}switch(this.platform){case"osx":return this.getArchiveNameOsx();case"win32":case"windows":return this.getArchiveNameWin();case"linux":return this.getArchiveNameLinux();default:throw new l.UnknownPlatformError(this.platform)}}))}getArchiveNameWin(){let e=`mongodb-${this.platform}-${this.arch}`;if(!(0,A.isNullOrUndefined)(a.coerce(this.version))){if(a.satisfies(this.version,"4.2.x")){e+="-2012plus"}else if(a.lt(this.version,"4.1.0")){e+="-2008plus-ssl"}}e+=`-${this.version}.zip`;return e}getArchiveNameOsx(){let e=`mongodb-osx`;const t=a.coerce(this.version);if(!(0,A.isNullOrUndefined)(t)&&a.gte(t,"3.2.0")){e+="-ssl"}if((0,A.isNullOrUndefined)(t)||a.gte(t,"4.2.0")){e=`mongodb-macos`}if(this.arch==="arm64"){h('getArchiveNameOsx: Arch is "arm64", using x64 binary');this.arch="x86_64"}e+=`-${this.arch}-${this.version}.tgz`;return e}getArchiveNameLinux(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){let e;if(this.arch!=="i686"){if(!this.os){this.os=yield(0,o.getOS)()}e=this.getLinuxOSVersionString(this.os)}let t=`mongodb-linux-${this.arch}`;if(!!e){t+=`-${e}`}t+=`-${this.version}.tgz`;return t}))}getLinuxOSVersionString(e){var t;if(regexHelper(/ubuntu/i,e)){return this.getUbuntuVersionString(e)}else if(regexHelper(/amzn/i,e)){return this.getAmazonVersionString(e)}else if(regexHelper(/suse/i,e)){return this.getSuseVersionString(e)}else if(regexHelper(/(rhel|centos|scientific)/i,e)){return this.getRhelVersionString(e)}else if(regexHelper(/fedora/i,e)){return this.getFedoraVersionString(e)}else if(regexHelper(/debian/i,e)){return this.getDebianVersionString(e)}else if(regexHelper(/alpine/i,e)){console.warn("There is no offical build of MongoDB for Alpine!")}else if(regexHelper(/(arch|manjaro|arco)(?:linux)?$/i,e)){console.warn(`There is no official build of MongoDB for ArchLinux (${e.dist}). Falling back to Ubuntu 20.04 release.`);return this.getUbuntuVersionString({os:"linux",dist:"Ubuntu Linux",release:"20.04"})}else if(regexHelper(/gentoo/i,e)){console.warn(`There is no official build of MongoDB for Gentoo (${e.dist}). Falling back to Debian.`);return this.getDebianVersionString({os:"linux",dist:"Debian",release:"11"})}else if(regexHelper(/unknown/i,e)){console.warn("Couldnt parse dist information, please report this to https://github.com/nodkz/mongodb-memory-server/issues")}console.warn(`Unknown/unsupported linux "${e.dist}(${(t=e.id_like)===null||t===void 0?void 0:t.join(", ")})". Falling back to legacy MongoDB build!`);return this.getLegacyVersionString()}getDebianVersionString(e){let t="debian";const r=parseFloat(e.release);if(r>=11||["unstable","testing"].includes(e.release)){if(a.lt(this.version,"5.0.8")){h("debian11 detected, but version below 5.0.8 requested, using debian10");t+="10"}else{t+="11"}}else if(r>=10){t+="10"}else if(r>=9){t+="92"}else if(r>=8.1){t+="81"}else if(r>=7.1){t+="71"}if(r>=10){if(a.lt(this.version,"4.2.1")){throw new l.KnownVersionIncompatibilityError(`Debian ${r}`,this.version,">=4.2.1","Mongodb does not provide binaries for versions before 4.2.1 for Debian 10+ and also cannot be mapped to a previous Debian release")}}return t}getFedoraVersionString(e){let t="rhel";const r=parseInt(e.release,10);if(r>=34){t+="80"}if(r<34&&r>=19){t+="70"}if(r<19&&r>=12){t+="62"}if(r<12&&r>=6){t+="55"}return t}getRhelVersionString(e){let t="rhel";const{release:r}=e;if(r){if(/^8/.test(r)){t+="80"}else if(/^7/.test(r)){t+="70"}else if(/^6/.test(r)){t+="62"}else if(/^5/.test(r)){t+="55"}}if(t==="rhel"){h('getRhelVersionString: falling back to "70"');t+="70"}return t}getAmazonVersionString(e){let t="amazon";const r=parseInt(e.release,10);if(r>=2&&r<=3){t+="2"}return t}getLegacyVersionString(){return""}getSuseVersionString(e){const t=e.release.match(/(^11|^12|^15)/);return t?`suse${t[0]}`:""}getUbuntuVersionString(e){let t=undefined;{if(/^linux\s?mint\s*$/i.test(e.dist)){const r={17:"14.04",18:"16.04",19:"18.04",20:"20.04"};t={os:"linux",dist:"ubuntu",release:r[parseInt(e.release.split(".")[0])]||r[20]}}if(/^elementary\s?os\s*$/i.test(e.dist)){const r={3:"14.04",4:"16.04",5:"18.04",6:"20.04"};const[n,o]=e.release.split(".").map((e=>parseInt(e)));const s=n||o;t={os:"linux",dist:"ubuntu",release:r[s]||r[6]}}}if((0,A.isNullOrUndefined)(t)){if(!/^ubuntu(?:| linux)\s*$/i.test(e.dist)){console.warn(`Unmapped distro "${e.dist}" with ID_LIKE "ubuntu", defaulting to highest ubuntu version!\n`+'This means that your distro does not have a internal mapping in MMS or does not have a upstream release file (like "/etc/upstream-release/lsb-release"), but has set a ID_LIKE');t={os:"linux",dist:"ubuntu",release:"20.04"}}else{t=e}}const r=parseInt(t.release.split(".")[0],10);if(this.arch==="arm64"){if(a.satisfies(this.version,"<4.1.10")){this.arch="arm64";return"ubuntu1604"}if(a.satisfies(this.version,">=4.1.10")){this.arch="aarch64";if(a.satisfies(this.version,"<4.4.0")){return"ubuntu1804"}return`ubuntu${r||18}04`}}if(t.release==="14.10"){return"ubuntu1410-clang"}if(r>=18&&a.satisfies(this.version,"3.x.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an 3.x.x version, defaulting to "1604"`);return"ubuntu1604"}if(r>18&&a.satisfies(this.version,"<=4.3.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an "<=4.3.x" version, defaulting to "1804"`);return"ubuntu1804"}if(r>=21){return"ubuntu2004"}return`ubuntu${r||14}04`}translatePlatform(e){switch(e){case"darwin":return"osx";case"win32":const t=a.coerce(this.version);if((0,A.isNullOrUndefined)(t)){return"windows"}return a.gte(t,"4.3.0")?"windows":"win32";case"linux":case"elementary OS":return"linux";case"sunos":return"sunos5";default:throw new l.UnknownPlatformError(e)}}static translateArch(e,t){switch(e){case"ia32":(0,u.deprecate)((()=>{}),"mongodb-memory-server will fully drop support for ia32 in 9.0","MMS001")();if(t==="linux"){return"i686"}else if(t==="win32"){return"i386"}throw new l.UnknownArchitectureError(e,t);case"x86_64":case"x64":return"x86_64";case"arm64":return"arm64";case"aarch64":return"aarch64";default:throw new l.UnknownArchitectureError(e)}}}t.MongoBinaryDownloadUrl=MongoBinaryDownloadUrl;t["default"]=MongoBinaryDownloadUrl;function regexHelper(e,t){return e.test(t.dist)||(!(0,A.isNullOrUndefined)(t.id_like)?t.id_like.filter((t=>e.test(t))).length>=1:false)}},843:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoInstance=t.MongoInstanceEvents=void 0;const n=r(4351);const o=r(2081);const s=(0,n.__importStar)(r(1017));const i=r(9125);const a=(0,n.__importDefault)(r(8237));const A=r(1978);const c=r(1383);const l=r(2361);const u=r(5517);const h=r(3386);if((0,c.lt)(process.version,"12.22.0")){console.warn("Using NodeJS below 12.22.0")}const d=(0,a.default)("MongoMS:MongoInstance");var g;(function(e){e["instanceReplState"]="instanceReplState";e["instancePrimary"]="instancePrimary";e["instanceReady"]="instanceReady";e["instanceSTDOUT"]="instanceSTDOUT";e["instanceSTDERR"]="instanceSTDERR";e["instanceClosed"]="instanceClosed";e["instanceRawError"]="instanceRawError";e["instanceError"]="instanceError";e["killerLaunched"]="killerLaunched";e["instanceLaunched"]="instanceLaunched";e["instanceStarted"]="instanceStarted"})(g=t.MongoInstanceEvents||(t.MongoInstanceEvents={}));class MongoInstance extends l.EventEmitter{constructor(e){super();this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;this.instanceOpts=Object.assign({},e.instance);this.binaryOpts=Object.assign({},e.binary);this.spawnOpts=Object.assign({},e.spawn);this.on(g.instanceReady,(()=>{this.isInstanceReady=true;this.debug("constructor: Instance is ready!")}));this.on(g.instanceError,(e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`constructor: Instance has thrown an Error: ${e.toString()}`);this.isInstanceReady=false;this.isInstancePrimary=false;yield this.stop()}))))}debug(e,...t){var r;const n=(r=this.instanceOpts.port)!==null&&r!==void 0?r:"unknown";d(`Mongo[${n}]: ${e}`,...t)}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("create: Called .create() method");const t=new this(e);yield t.start();return t}))}prepareCommandArgs(){var e;this.debug("prepareCommandArgs");(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.port),new Error('"instanceOpts.port" is required to be set!'));(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.dbPath),new Error('"instanceOpts.dbPath" is required to be set!'));const t=[];t.push("--port",this.instanceOpts.port.toString());t.push("--dbpath",this.instanceOpts.dbPath);if(!!this.instanceOpts.replSet){this.isReplSet=true;t.push("--replSet",this.instanceOpts.replSet)}if(!!this.instanceOpts.storageEngine){t.push("--storageEngine",this.instanceOpts.storageEngine)}if(!!this.instanceOpts.ip){t.push("--bind_ip",this.instanceOpts.ip)}if(this.instanceOpts.auth){t.push("--auth");if(this.isReplSet){(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.keyfileLocation),new h.KeyFileMissingError);t.push("--keyFile",this.instanceOpts.keyfileLocation)}}else{t.push("--noauth")}const r=t.concat((e=this.instanceOpts.args)!==null&&e!==void 0?e:[]);this.debug("prepareCommandArgs: final argument array:"+JSON.stringify(r));return r}start(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start");this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;const e=new Promise(((e,t)=>{this.once(g.instanceReady,e);this.once(g.instanceError,t);this.once(g.instanceClosed,(()=>{t(new Error("Instance Exited before being ready and without throwing an error!"))}))}));const t=yield i.MongoBinary.getPath(this.binaryOpts);yield(0,A.checkBinaryPermissions)(t);this.debug("start: Starting Processes");this.mongodProcess=this._launchMongod(t);(0,A.assertion)(!(0,A.isNullOrUndefined)(this.mongodProcess.pid),new Error("MongoD Process failed to spawn"));this.killerProcess=this._launchKiller(process.pid,this.mongodProcess.pid);yield e;this.emit(g.instanceStarted);this.debug("start: Processes Started")}))}stop(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop");if(!this.mongodProcess&&!this.killerProcess){this.debug("stop: nothing to shutdown, returning");return false}if(!(0,A.isNullOrUndefined)(this.mongodProcess)){if(this.isReplSet){let e;try{this.debug("stop: trying shutdownServer");const t=this.instanceOpts.port;const r=this.instanceOpts.ip;(0,A.assertion)(!(0,A.isNullOrUndefined)(t),new Error('Cannot shutdown replset gracefully, no "port" is provided'));(0,A.assertion)(!(0,A.isNullOrUndefined)(r),new Error('Cannot shutdown replset gracefully, no "ip" is provided'));e=yield u.MongoClient.connect((0,A.uriTemplate)(r,t,"admin"),Object.assign(Object.assign({},this.extraConnectionOptions),{directConnection:true}));const n=e.db("admin");yield n.command({shutdown:1,force:true,timeoutSecs:1});this.debug("stop: after admin shutdown command")}catch(e){if(!(e instanceof u.MongoNetworkError&&/^connection \d+ to [\d.]+:\d+ closed$/i.test(e.message))){console.warn(e)}}finally{if(!(0,A.isNullOrUndefined)(e)){yield e.close()}}}yield(0,A.killProcess)(this.mongodProcess,"mongodProcess",this.instanceOpts.port);this.mongodProcess=undefined}else{this.debug("stop: mongodProcess: nothing to shutdown, skipping")}if(!(0,A.isNullOrUndefined)(this.killerProcess)){yield(0,A.killProcess)(this.killerProcess,"killerProcess",this.instanceOpts.port);this.killerProcess=undefined}else{this.debug("stop: killerProcess: nothing to shutdown, skipping")}this.debug("stop: Instance Finished Shutdown");return true}))}_launchMongod(e){var t,r;this.debug("_launchMongod: Launching Mongod Process");const n=(0,o.spawn)(s.resolve(e),this.prepareCommandArgs(),Object.assign(Object.assign({},this.spawnOpts),{stdio:"pipe"}));(t=n.stderr)===null||t===void 0?void 0:t.on("data",this.stderrHandler.bind(this));(r=n.stdout)===null||r===void 0?void 0:r.on("data",this.stdoutHandler.bind(this));n.on("close",this.closeHandler.bind(this));n.on("error",this.errorHandler.bind(this));if((0,A.isNullOrUndefined)(n.pid)){throw new h.StartBinaryFailedError(s.resolve(e))}this.emit(g.instanceLaunched);return n}_launchKiller(e,t){this.debug(`_launchKiller: Launching Killer Process (parent: ${e}, child: ${t})`);const r=(0,o.fork)(s.resolve(__dirname,"../../scripts/mongo_killer.js"),[e.toString(),t.toString()],{detached:true,stdio:"ignore"});r.unref();this.emit(g.killerLaunched);return r}errorHandler(e){this.emit(g.instanceRawError,e);this.emit(g.instanceError,e)}closeHandler(e,t){if(process.platform==="win32"&&e!=12&&e!=0||e!=0){this.debug("closeHandler: Mongod instance closed with an non-0 (or non 12 on windows) code!")}this.debug(`closeHandler: "${e}" "${t}"`);this.emit(g.instanceClosed,e,t)}stderrHandler(e){const t=e.toString().trim();this.debug(`stderrHandler: ""${t}""`);this.emit(g.instanceSTDERR,t);this.checkErrorInLine(t)}stdoutHandler(e){var t,r;const n=e.toString().trim();this.debug(`stdoutHandler: ""${n}""`);this.emit(g.instanceSTDOUT,n);if(/waiting for connections/i.test(n)){this.emit(g.instanceReady)}this.checkErrorInLine(n);if(/transition to \w+ from \w+/i.test(n)){const e=(r=(t=/transition to (\w+) from \w+/i.exec(n))===null||t===void 0?void 0:t[1])!==null&&r!==void 0?r:"UNKNOWN";this.emit(g.instanceReplState,e);if(e!=="PRIMARY"){this.isInstancePrimary=false}}if(/transition to primary complete; database writes are now permitted/i.test(n)){this.isInstancePrimary=true;this.debug('stdoutHandler: emitting "instancePrimary"');this.emit(g.instancePrimary)}}checkErrorInLine(e){var t,r;if(/address already in use/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError(`Port "${this.instanceOpts.port}" already in use`))}if(/exception in initAndListen: \w+[^:]: .+[^,], terminating/i.test(e)){const t=/exception in initAndListen: (\w+[^:]): (.+[^,]), terminating/i.exec(e);const{1:r,2:n}=t||[];this.emit(g.instanceError,new h.StdoutInstanceError(`Instance Failed to start with "${r}". Original Error:\n`+n))}if(/CURL_OPENSSL_3['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You should manually install libcurl3 or try to use an newer version of MongoDB"))}if(/CURL_OPENSSL_4['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl4 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You need to manually install libcurl4"))}if(/lib[^:]+(?=: cannot open shared object)/i.test(e)){const n=(r=(t=e.match(/(lib[^:]+)(?=: cannot open shared object)/i))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown";this.emit(g.instanceError,new h.StdoutInstanceError(`Instance failed to start because a library is missing or cannot be opened: "${n}"`))}if(/\*\*\*aborting after/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("Mongod internal error"))}}}t.MongoInstance=MongoInstance;t["default"]=MongoInstance},3386:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.StdoutInstanceError=t.KnownVersionIncompatibilityError=t.NoRegexMatchError=t.ParseArchiveRegexError=t.ReplsetCountLowError=t.AssertionFallbackError=t.BinaryNotFoundError=t.InsufficientPermissionsError=t.AuthNotObjectError=t.KeyFileMissingError=t.InstanceInfoError=t.StartBinaryFailedError=t.Md5CheckFailedError=t.NoSystemBinaryFoundError=t.EnsureInstanceError=t.WaitForPrimaryTimeoutError=t.UnknownArchitectureError=t.UnknownPlatformError=t.UnableToUnlockLockfileError=t.UnknownLockfileStatusError=t.StateError=void 0;const n=r(1978);class StateError extends Error{constructor(e,t){super(`Incorrect State for operation: "${t}", allowed States: "[${e.join(",")}]"\n`+"This may be because of using a v6.x way of calling functions, look at the following guide if anything applies:\n"+"https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7#no-function-other-than-start-create-ensureinstance-will-be-starting-anything");this.wantedStates=e;this.gotState=t}}t.StateError=StateError;class UnknownLockfileStatusError extends Error{constructor(e){super(`Unknown LockFile Status: "${e}"`);this.status=e}}t.UnknownLockfileStatusError=UnknownLockfileStatusError;class UnableToUnlockLockfileError extends Error{constructor(e,t){super(`Cannot unlock file "${t}", because it is not locked by this ${e?"instance":"process"}`);this.thisInstance=e;this.file=t}}t.UnableToUnlockLockfileError=UnableToUnlockLockfileError;class UnknownPlatformError extends Error{constructor(e){super(`Unknown Platform: "${e}"`);this.platform=e}}t.UnknownPlatformError=UnknownPlatformError;class UnknownArchitectureError extends Error{constructor(e,t){super();this.arch=e;this.platform=t;if(!(0,n.isNullOrUndefined)(t)){this.message=`Unsupported Architecture-Platform combination: arch: "${e}", platform: "${t}"`}else{this.message=`Unsupported Architecture: "${e}"`}}}t.UnknownArchitectureError=UnknownArchitectureError;class WaitForPrimaryTimeoutError extends Error{constructor(e,t){super(`Timed out after ${e}ms while waiting for a Primary (where: "${t}")`);this.timeout=e;this.where=t}}t.WaitForPrimaryTimeoutError=WaitForPrimaryTimeoutError;class EnsureInstanceError extends Error{constructor(e){super();this.isRunning=e;const t='"ensureInstance" failed, because';if(e){this.message=`${t} state was "running" but "instanceInfo" was undefined!`}else{this.message=`${t} "instanceInfo" was undefined after running "start"`}}}t.EnsureInstanceError=EnsureInstanceError;class NoSystemBinaryFoundError extends Error{constructor(e){super(`Config option "SYSTEM_BINARY" was provided with value "${e}", but no binary could be found!`);this.binaryPath=e}}t.NoSystemBinaryFoundError=NoSystemBinaryFoundError;class Md5CheckFailedError extends Error{constructor(e,t){super(`MD5 check failed! Binary MD5 is "${e}", Checkfile MD5 is "${t}"`);this.binarymd5=e;this.checkfilemd5=t}}t.Md5CheckFailedError=Md5CheckFailedError;class StartBinaryFailedError extends Error{constructor(e){super(`Starting the Binary Failed (PID is undefined)! Binary: "${e}"`);this.binary=e}}t.StartBinaryFailedError=StartBinaryFailedError;class InstanceInfoError extends Error{constructor(e){super(`"instanceInfo" was undefined when expected to be defined! (where: "${e}")`);this.where=e}}t.InstanceInfoError=InstanceInfoError;class KeyFileMissingError extends Error{constructor(){super(`"keyfileLocation" was undefined when expected!`)}}t.KeyFileMissingError=KeyFileMissingError;class AuthNotObjectError extends Error{constructor(){super('"auth" was not a object when it was expected!')}}t.AuthNotObjectError=AuthNotObjectError;class InsufficientPermissionsError extends Error{constructor(e){super(`File "${e}" does not have the required Permissions, required Permissions: "--x"`);this.path=e}}t.InsufficientPermissionsError=InsufficientPermissionsError;class BinaryNotFoundError extends Error{constructor(e){super(`No Binary at path "${e}" was found! (ENOENT)`);this.path=e}}t.BinaryNotFoundError=BinaryNotFoundError;class AssertionFallbackError extends Error{constructor(){super("Assert failed - no custom error")}}t.AssertionFallbackError=AssertionFallbackError;class ReplsetCountLowError extends Error{constructor(e){super(`ReplSet Count needs to be 1 or higher! (specified count: "${e}")`);this.count=e}}t.ReplsetCountLowError=ReplsetCountLowError;class ParseArchiveRegexError extends Error{constructor(e){super(`Expected "${e}" to be found in regex groups`);this.key=e}}t.ParseArchiveRegexError=ParseArchiveRegexError;class NoRegexMatchError extends Error{constructor(e,t){super();this.name=e;this.extra=t;const r=!!t?`(${t})`:"";this.message=`Expected "${e}" to have Regex Matches${r}`}}t.NoRegexMatchError=NoRegexMatchError;class KnownVersionIncompatibilityError extends Error{constructor(e,t,r,n){super();this.dist=e;this.requested_version=t;this.available_versions=r;this.extra=n;const o=!!n?`\n${n}`:"";this.message=`Requested Version "${t}" is not available for "${e}"! Available Versions: "${r}"${o}`}}t.KnownVersionIncompatibilityError=KnownVersionIncompatibilityError;class StdoutInstanceError extends Error{constructor(e){super(e)}}t.StdoutInstanceError=StdoutInstanceError},8278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.parseOS=t.parseLSB=t.getOS=t.isLinuxOS=void 0;const n=r(4351);const o=r(2037);const s=(0,n.__importDefault)(r(8237));const i=r(1978);const a=(0,s.default)("MongoMS:getos");const A={name:/^(?:distributor id:|DISTRIB_ID=)\s*(.*)$/im,codename:/^(?:codename:|DISTRIB_CODENAME=)\s*(.*)$/im,release:/^(?:release:|DISTRIB_RELEASE=)\s*(.*)$/im};const c={name:/^id\s*=\s*"?(\w*)"?$/im,codename:/^version_codename\s*=\s*(.*)$/im,release:/^version_id\s*=\s*"?(\d*(?:\.\d*)?)"?$/im,id_like:/^id_like\s*=\s*"?([\w\s]*)"?$/im};function isLinuxOS(e){return e.os==="linux"}t.isLinuxOS=isLinuxOS;let l;function getOS(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!l){const e=(0,o.platform)();if(e==="linux"){l=yield getLinuxInformation()}else{l={os:e}}}return l}))}t.getOS=getOS;function getLinuxInformation(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield(0,i.tryReleaseFile)("/etc/upstream-release/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(e)){a("getLinuxInformation: Using UpstreamLSB");return e}const t=yield(0,i.tryReleaseFile)("/etc/os-release",parseOS);if(!(0,i.isNullOrUndefined)(t)){a("getLinuxInformation: Using etcOsRelease");return t}const r=yield(0,i.tryReleaseFile)("/usr/lib/os-release",parseOS);if(!(0,i.isNullOrUndefined)(r)){a("getLinuxInformation: Using usrOsRelease");return r}const n=yield(0,i.tryReleaseFile)("/etc/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(n)){a("getLinuxInformation: Using etcLSBRelease");return n}console.warn("Could not find any Release File, using fallback binary");return{os:"linux",dist:"unknown",release:""}}))}function parseLSB(e){var t,r,n,o,s;return{os:"linux",dist:(r=(t=e.match(A.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(A.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(A.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:""}}t.parseLSB=parseLSB;function parseOS(e){var t,r,n,o,s,i;return{os:"linux",dist:(r=(t=e.match(c.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(c.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(c.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:"",id_like:(i=e.match(c.id_like))===null||i===void 0?void 0:i[1].toLocaleLowerCase().split(" ")}}t.parseOS=parseOS},4908:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.LockFile=t.LockFileEvents=t.LockFileStatus=void 0;const n=r(4351);const o=r(2361);const s=(0,n.__importStar)(r(1978));const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(4038);const l=r(5840);const u=r(3386);const h=(0,i.default)("MongoMS:LockFile");class RepeatError extends Error{constructor(e){super();this.repeat=e}}var d;(function(e){e[e["available"]=0]="available";e[e["availableInstance"]=1]="availableInstance";e[e["lockedSelf"]=2]="lockedSelf";e[e["lockedDifferent"]=3]="lockedDifferent"})(d=t.LockFileStatus||(t.LockFileStatus={}));var g;(function(e){e["lock"]="lock";e["unlock"]="unlock"})(g=t.LockFileEvents||(t.LockFileEvents={}));class LockFileEventsClass extends o.EventEmitter{}class LockFile{constructor(e,t){this.file=e;this.uuid=t}static lock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`lock: Locking file "${e}"`);const t=a.resolve(e.trim());s.assertion(t.length>0,new Error("Provided Path for lock file is length of 0"));const r=yield this.checkLock(t);switch(r){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(t);case d.available:return this.createLock(t);default:throw new u.UnknownLockfileStatusError(r)}}))}static checkLock(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`checkLock: for file "${e}" with uuid: "${t}"`);if(!(yield s.pathExists(e))){return d.available}try{const r=(yield A.promises.readFile(e)).toString().trim().split(" ");const n=parseInt(r[0]);if(n===process.pid){h(`checkLock: Lock File Already exists, and is for *this* process, with uuid: "${r[1]}"`);if(!this.files.has(e)){return d.available}if(!s.isNullOrUndefined(t)){return t===r[1]?d.availableInstance:d.lockedSelf}return d.lockedSelf}h(`checkLock: Lock File Aready exists, for a different process: "${n}"`);return s.isAlive(n)?d.lockedDifferent:d.available}catch(e){if(s.errorWithCode(e)&&e.code==="ENOENT"){h("checkLock: reading file failed with ENOENT");return d.available}throw e}}))}static waitForLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`waitForLock: Starting to wait for file "${e}"`);let t=undefined;let r=undefined;yield new Promise((o=>{r=t=>{if(t===e){o()}};t=setInterval((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.checkLock(e);h(`waitForLock: Interval for file "${e}" with status "${t}"`);if(t===d.available){o()}}))),1e3*3);this.events.on(g.unlock,r)}));if(t){clearInterval(t)}if(r){this.events.removeListener(g.unlock,r)}h(`waitForLock: File became available "${e}"`);yield s.ensureAsync();const o=yield this.checkLock(e);h(`waitForLock: Lock File Status reassessment for file "${e}": ${o}`);switch(o){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(e);case d.available:return this.createLock(e);default:throw new u.UnknownLockfileStatusError(o)}}))}static createLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`createLock: trying to create a lock file for "${e}"`);const t=(0,l.v4)();try{yield this.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(this.files.has(e)){h(`createLock: Map already has file "${e}"`);throw new RepeatError(true)}yield s.mkdir(a.dirname(e));yield A.promises.writeFile(e,`${process.pid.toString()} ${t}`);this.files.add(e);this.events.emit(g.lock,e)}))))}catch(t){if(t instanceof RepeatError&&t.repeat){return this.waitForLock(e)}}h(`createLock: Lock File Created for file "${e}"`);return new this(e,t)}))}unlock(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`unlock: Unlocking file "${this.file}"`);if(s.isNullOrUndefined(this.file)||((e=this.file)===null||e===void 0?void 0:e.length)<=0){h("unlock: invalid file, returning");return}switch(yield LockFile.checkLock(this.file,this.uuid)){case d.available:h(`unlock: Lock Status was already "available" for file "${this.file}"`);yield this.unlockCleanup(false);return;case d.availableInstance:h(`unlock: Lock Status was "availableInstance" for file "${this.file}"`);yield this.unlockCleanup(true);return;case d.lockedSelf:throw new u.UnableToUnlockLockfileError(true,this.file);default:throw new u.UnableToUnlockLockfileError(false,this.file)}}))}unlockCleanup(e=true){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return yield LockFile.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`unlockCleanup: for file "${this.file}"`);if(s.isNullOrUndefined(this.file)){return}if(e){yield A.promises.unlink(this.file).catch((e=>{h(`unlockCleanup: lock file unlink failed: "${e}"`)}))}LockFile.files.delete(this.file);LockFile.events.emit(g.unlock,this.file);this.file=undefined;this.uuid=undefined}))))}))}}t.LockFile=LockFile;LockFile.files=new Set;LockFile.events=new LockFileEventsClass;LockFile.mutex=new c.Mutex},8730:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.envToBool=t.envName=t.resolveConfig=t.processConfigOption=t.findPackageJson=t.setDefaultValue=t.defaultValues=t.DEFAULT_VERSION=t.ENV_CONFIG_PREFIX=t.ResolveConfigVariables=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(1362));const s=r(1156);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(1978);const l=(0,i.default)("MongoMS:ResolveConfig");var u;(function(e){e["DOWNLOAD_DIR"]="DOWNLOAD_DIR";e["PLATFORM"]="PLATFORM";e["ARCH"]="ARCH";e["VERSION"]="VERSION";e["DEBUG"]="DEBUG";e["DOWNLOAD_MIRROR"]="DOWNLOAD_MIRROR";e["DOWNLOAD_URL"]="DOWNLOAD_URL";e["PREFER_GLOBAL_PATH"]="PREFER_GLOBAL_PATH";e["DISABLE_POSTINSTALL"]="DISABLE_POSTINSTALL";e["SYSTEM_BINARY"]="SYSTEM_BINARY";e["MD5_CHECK"]="MD5_CHECK";e["ARCHIVE_NAME"]="ARCHIVE_NAME";e["RUNTIME_DOWNLOAD"]="RUNTIME_DOWNLOAD";e["USE_HTTP"]="USE_HTTP";e["SYSTEM_BINARY_VERSION_CHECK"]="SYSTEM_BINARY_VERSION_CHECK";e["USE_ARCHIVE_NAME_FOR_BINARY_NAME"]="USE_ARCHIVE_NAME_FOR_BINARY_NAME"})(u=t.ResolveConfigVariables||(t.ResolveConfigVariables={}));t.ENV_CONFIG_PREFIX="MONGOMS_";t.DEFAULT_VERSION="5.0.8";t.defaultValues=new Map([[u.VERSION,t.DEFAULT_VERSION],[u.PREFER_GLOBAL_PATH,"true"],[u.RUNTIME_DOWNLOAD,"true"],[u.USE_HTTP,"false"],[u.SYSTEM_BINARY_VERSION_CHECK,"true"],[u.USE_ARCHIVE_NAME_FOR_BINARY_NAME,"false"]]);function setDefaultValue(e,r){t.defaultValues.set(e,r)}t.setDefaultValue=setDefaultValue;let h=undefined;function findPackageJson(e){var t;for(const r of(0,s.findSync)(e||process.cwd())){l(`findPackageJson: Found package.json at "${r}"`);const e=JSON.parse((0,A.readFileSync)(r).toString());const n=(t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.mongodbMemoryServer;if(!(0,c.isNullOrUndefined)(n)&&Object.keys(n!==null&&n!==void 0?n:{}).length>0){l(`findPackageJson: Found package with non-empty config field at "${r}"`);const e=a.dirname(r);h={filePath:e,config:processConfigOption(n,e)};break}}return h}t.findPackageJson=findPackageJson;function processConfigOption(e,t){l("processConfigOption",e,t);if(typeof e!=="object"){l("processConfigOptions: input was not a object");return{}}const r=e;const n=(0,o.default)(u.DOWNLOAD_DIR);const s=(0,o.default)(u.SYSTEM_BINARY);if(n in r){r[n]=a.resolve(t,r[n])}if(s in r){r[s]=a.resolve(t,r[s])}return r}t.processConfigOption=processConfigOption;function resolveConfig(e){var r,n,s;return(s=(n=(r=process.env[envName(e)])!==null&&r!==void 0?r:h===null||h===void 0?void 0:h.config[(0,o.default)(e)])!==null&&n!==void 0?n:t.defaultValues.get(e))===null||s===void 0?void 0:s.toString()}t.resolveConfig=resolveConfig;t["default"]=resolveConfig;function envName(e){return`${t.ENV_CONFIG_PREFIX}${e}`}t.envName=envName;function envToBool(e=""){if(typeof e!=="string"){l("envToBool: input was not a string!");return false}return["1","on","yes","true"].indexOf(e.toLowerCase())!==-1}t.envToBool=envToBool;if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through Environment Variable")}findPackageJson();if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through package.json")}},1978:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mkdir=t.checkBinaryPermissions=t.ManagerAdvanced=t.ManagerBase=t.tryReleaseFile=t.pathExists=t.statPath=t.authDefault=t.ensureAsync=t.isAlive=t.killProcess=t.assertion=t.isNullOrUndefined=t.uriTemplate=t.getHost=t.generateDbName=t.errorWithCode=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(7147);const i=r(3386);const a=(0,o.default)("MongoMS:utils");function errorWithCode(e){return e instanceof Error&&"code"in e}t.errorWithCode=errorWithCode;function generateDbName(e){return e||""}t.generateDbName=generateDbName;function getHost(e){return e.replace(/(?:^mongodb:\/{2})|(?:\/.*$)|(?:.*@)/gim,"")}t.getHost=getHost;function uriTemplate(e,t,r,n){const o=!isNullOrUndefined(t)?`${e}:${t}`:e;return`mongodb://${o}/${r}`+(!isNullOrUndefined(n)?`?${n.join("&")}`:"")}t.uriTemplate=uriTemplate;function isNullOrUndefined(e){return e===null||e===undefined}t.isNullOrUndefined=isNullOrUndefined;function assertion(e,t){if(!e){throw t!==null&&t!==void 0?t:new i.AssertionFallbackError}}t.assertion=assertion;function killProcess(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){function ilog(e){a(`Mongo[${r||"unknown"}] killProcess: ${e}`)}if(!isAlive(e.pid)){ilog("given childProcess's PID was not alive anymore");return}const n=1e3*10;yield new Promise(((r,s)=>{let i=setTimeout((()=>{ilog("killProcess: timeout triggered, trying SIGKILL");if(!o.default.enabled("MongoMS:utils")){console.warn('An Process didnt exit with signal "SIGINT" within 10 seconds, using "SIGKILL"!\n'+"Enable debug logs for more information")}e.kill("SIGKILL");i=setTimeout((()=>{ilog("killProcess: timeout triggered again, rejecting");s(new Error(`Process "${t}" didnt exit, enable debug for more information.`))}),n)}),n);e.once(`exit`,((e,n)=>{ilog(`killProcess: ${t}: got exit signal, Code: ${e}, Signal: ${n}`);clearTimeout(i);r()}));ilog(`killProcess: ${t}: sending "SIGINT"`);e.kill("SIGINT")}))}))}t.killProcess=killProcess;function isAlive(e){if(isNullOrUndefined(e)){return false}try{process.kill(e,0);return true}catch(e){return false}}t.isAlive=isAlive;function ensureAsync(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return new Promise((e=>process.nextTick(e)))}))}t.ensureAsync=ensureAsync;function authDefault(e){return Object.assign({force:false,disable:false,customRootName:"mongodb-memory-server-root",customRootPwd:"rootuser",extraUsers:[],keyfileContent:"0123456789"},e)}t.authDefault=authDefault;function statPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(["ENOENT","EACCES"].includes(e.code)){return undefined}throw e}))}))}t.statPath=statPath;function pathExists(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return!isNullOrUndefined(yield statPath(e))}))}t.pathExists=pathExists;function tryReleaseFile(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{const r=yield s.promises.readFile(e);return t(r.toString())}catch(t){if(errorWithCode(t)&&!["ENOENT","EACCES"].includes(t.code)){throw t}a(`tryReleaseFile: "${e}" does not exist`);return undefined}}))}t.tryReleaseFile=tryReleaseFile;class ManagerBase{}t.ManagerBase=ManagerBase;class ManagerAdvanced extends ManagerBase{}t.ManagerAdvanced=ManagerAdvanced;function checkBinaryPermissions(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{yield s.promises.access(e,s.constants.X_OK)}catch(t){if(errorWithCode(t)){if(t.code==="EACCES"){throw new i.InsufficientPermissionsError(e)}if(t.code==="ENOENT"){throw new i.BinaryNotFoundError(e)}}throw t}}))}t.checkBinaryPermissions=checkBinaryPermissions;function mkdir(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.promises.mkdir(e,{recursive:true})}))}t.mkdir=mkdir},5517:(e,t,r)=>{"use strict";const n=r(3994);const o=r(2138);const s=r(1545).connect;s.MongoError=n.MongoError;s.MongoNetworkError=n.MongoNetworkError;s.MongoTimeoutError=n.MongoTimeoutError;s.MongoServerSelectionError=n.MongoServerSelectionError;s.MongoParseError=n.MongoParseError;s.MongoWriteConcernError=n.MongoWriteConcernError;s.MongoBulkWriteError=r(4239).BulkWriteError;s.BulkWriteError=s.MongoBulkWriteError;s.ServerApiVersion=n.ServerApiVersion;s.Admin=r(3238);s.MongoClient=r(1545);s.Db=r(6662);s.Collection=r(5193);s.Server=r(8421);s.ReplSet=r(382);s.Mongos=r(2048);s.ReadPreference=n.ReadPreference;s.GridStore=r(9406);s.Chunk=r(3890);s.Logger=n.Logger;s.AggregationCursor=r(7429);s.CommandCursor=r(538);s.Cursor=r(7159);s.GridFSBucket=r(2573);s.CoreServer=n.Server;s.CoreConnection=n.Connection;s.Binary=n.BSON.Binary;s.Code=n.BSON.Code;s.Map=n.BSON.Map;s.DBRef=n.BSON.DBRef;s.Double=n.BSON.Double;s.Int32=n.BSON.Int32;s.Long=n.BSON.Long;s.MinKey=n.BSON.MinKey;s.MaxKey=n.BSON.MaxKey;s.ObjectID=n.BSON.ObjectID;s.ObjectId=n.BSON.ObjectID;s.Symbol=n.BSON.Symbol;s.Timestamp=n.BSON.Timestamp;s.BSONRegExp=n.BSON.BSONRegExp;s.Decimal128=n.BSON.Decimal128;s.connect=s;s.instrument=function(e,t){if(typeof e==="function"){t=e;e={}}const r=new o;r.instrument(s.MongoClient,t);return r};e.exports=s},3238:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(7057);const s=r(1681);const i=r(1969);const a=r(9263);const A=r(9929);const c=r(2548);function Admin(e,t,r){if(!(this instanceof Admin))return new Admin(e,t);this.s={db:e,topology:t,promiseLibrary:r}}Admin.prototype.command=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():{};const o=new s(this.s.db,e,t);return c(this.s.db.s.topology,o,r)};Admin.prototype.buildInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{serverStatus:1},e);return c(this.s.db.s.topology,r,t)};Admin.prototype.ping=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={ping:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.addUser=function(e,t,r,s){const i=Array.prototype.slice.call(arguments,2);s=typeof i[i.length-1]==="function"?i.pop():undefined;if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}r=i.length?i.shift():{};r=Object.assign({},r);r=n(r,{db:this.s.db});r.dbName="admin";const a=new o(this.s.db,e,t,r);return c(this.s.db.s.topology,a,s)};Admin.prototype.removeUser=function(e,t,r){const o=Array.prototype.slice.call(arguments,1);r=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():{};t=Object.assign({},t);t=n(t,{db:this.s.db});t.dbName="admin";const s=new i(this.s.db,e,t);return c(this.s.db.s.topology,s,r)};Admin.prototype.validateCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new a(this,e,t);return c(this.s.db.s.topology,n,r)};Admin.prototype.listDatabases=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return c(this.s.db.s.topology,new A(this.s.db,e),t)};Admin.prototype.replSetGetStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{replSetGetStatus:1},e);return c(this.s.db.s.topology,r,t)};e.exports=Admin},7429:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(7159);const s=r(4847).CursorState;class AggregationCursor extends o{constructor(e,t,r){super(e,t,r)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead()){throw n.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw n.create({message:"batchSize requires an integer",driver:true})}this.operation.options.batchSize=e;this.setCursorBatchSize(e);return this}geoNear(e){this.operation.addToPipeline({$geoNear:e});return this}group(e){this.operation.addToPipeline({$group:e});return this}limit(e){this.operation.addToPipeline({$limit:e});return this}match(e){this.operation.addToPipeline({$match:e});return this}maxTimeMS(e){this.operation.options.maxTimeMS=e;return this}out(e){this.operation.addToPipeline({$out:e});return this}project(e){this.operation.addToPipeline({$project:e});return this}lookup(e){this.operation.addToPipeline({$lookup:e});return this}redact(e){this.operation.addToPipeline({$redact:e});return this}skip(e){this.operation.addToPipeline({$skip:e});return this}sort(e){this.operation.addToPipeline({$sort:e});return this}unwind(e){this.operation.addToPipeline({$unwind:e});return this}getLogger(){return this.logger}}AggregationCursor.prototype.get=AggregationCursor.prototype.toArray;e.exports=AggregationCursor},2138:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;class Instrumentation extends n{constructor(){super()}instrument(e,t){this.$MongoClient=e;const r=this.$prototypeConnect=e.prototype.connect;const n=this;e.prototype.connect=function(e){this.s.options.monitorCommands=true;this.on("commandStarted",(e=>n.emit("started",e)));this.on("commandSucceeded",(e=>n.emit("succeeded",e)));this.on("commandFailed",(e=>n.emit("failed",e)));return r.call(this,e)};if(typeof t==="function")t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}e.exports=Instrumentation},1749:(e,t)=>{"use strict";function asyncIterator(){const e=this;return{next:function(){return Promise.resolve().then((()=>e.next())).then((t=>{if(!t){return e.close().then((()=>({value:t,done:true})))}return{value:t,done:false}}))}}}t.asyncIterator=asyncIterator},4239:(e,t,r)=>{"use strict";const n=r(3994).BSON.Long;const o=r(3994).MongoError;const s=r(3994).BSON.ObjectID;const i=r(3994).BSON;const a=r(3994).MongoWriteConcernError;const A=r(1371).emitWarningOnce;const c=r(1371).toError;const l=r(1371).handleCallback;const u=r(1371).applyRetryableWrites;const h=r(1371).applyWriteConcern;const d=r(1371).executeLegacyOperation;const g=r(1371).isPromiseLike;const p=r(1371).hasAtomicOperators;const E=r(1178).maxWireVersion;const m=64;const C=1;const I=2;const y=3;const B=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 Batch{constructor(e,t){this.originalZeroIndex=t;this.currentIndex=0;this.originalIndexes=[];this.batchType=e;this.operations=[];this.size=0;this.sizeBytes=0}}const Q=Symbol("upsertedIds");const b=Symbol("insertedIds");class BulkWriteResult{constructor(e){this.result=e;this[Q]=undefined;this[b]=undefined}get insertedCount(){return typeof this.result.nInserted!=="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!=="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!=="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!=="number"?0:this.result.nRemoved}get upsertedCount(){return!this.result.upserted?0:this.result.upserted.length}get upsertedIds(){if(this[Q]){return this[Q]}this[Q]={};for(const e of this.result.upserted||[]){this[Q][e.index]=e._id}return this[Q]}get insertedIds(){if(this[b]){return this[b]}this[b]={};for(const e of this.result.insertedIds||[]){this[b][e.index]=e._id}return this[b]}get n(){return this.result.insertedCount}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){if(ee.multi))}if(e.batch.batchType===y){r.retryWrites=r.retryWrites&&!e.batch.operations.some((e=>e.limit===0))}}try{if(e.batch.batchType===C){this.s.topology.insert(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===I){this.s.topology.update(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===y){this.s.topology.remove(this.s.namespace,e.batch.operations,r,e.resultHandler)}}catch(r){r.ok=0;l(t,null,mergeBatchResults(e.batch,this.s.bulkResult,r,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const r=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";l(e,new BulkWriteError(c({message:r,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null);return true}if(t.getWriteConcernError()){l(e,new BulkWriteError(c(t.getWriteConcernError()),t),null);return true}}}Object.defineProperty(BulkOperationBase.prototype,"length",{enumerable:true,get:function(){return this.s.currentIndex}});e.exports={Batch:Batch,BulkOperationBase:BulkOperationBase,mergeBatchResults:mergeBatchResults,bson:B,INSERT:C,UPDATE:I,REMOVE:y,BulkWriteError:BulkWriteError,BulkWriteResult:BulkWriteResult}},5035:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);const a=e.s.maxKeySize;if(e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+a+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}if(t===n.INSERT){e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id})}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentBatch.operations.push(r);e.s.currentBatchSize+=1;e.s.currentBatchSizeBytes+=a+o;e.s.currentIndex+=1;return e}class OrderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,true)}}function initializeOrderedBulkOp(e,t,r){return new OrderedBulkOperation(e,t,r)}initializeOrderedBulkOp.OrderedBulkOperation=OrderedBulkOperation;e.exports=initializeOrderedBulkOp;e.exports.Bulk=OrderedBulkOperation},325:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null;if(t===n.INSERT){e.s.currentBatch=e.s.currentInsertBatch}else if(t===n.UPDATE){e.s.currentBatch=e.s.currentUpdateBatch}else if(t===n.REMOVE){e.s.currentBatch=e.s.currentRemoveBatch}const a=e.s.maxKeySize;if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);if(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+a+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)}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.operations.push(r);e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentIndex=e.s.currentIndex+1;if(t===n.INSERT){e.s.currentInsertBatch=e.s.currentBatch;e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})}else if(t===n.UPDATE){e.s.currentUpdateBatch=e.s.currentBatch}else if(t===n.REMOVE){e.s.currentRemoveBatch=e.s.currentBatch}e.s.currentBatch.size+=1;e.s.currentBatch.sizeBytes+=a+o;return e}class UnorderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,false)}handleWriteError(e,t){if(this.s.batches.length){return false}return super.handleWriteError(e,t)}}function initializeUnorderedBulkOp(e,t,r){return new UnorderedBulkOperation(e,t,r)}initializeUnorderedBulkOp.UnorderedBulkOperation=UnorderedBulkOperation;e.exports=initializeUnorderedBulkOp;e.exports.Bulk=UnorderedBulkOperation},1117:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(9386).isResumableError;const i=r(3994).MongoError;const a=r(7159);const A=r(1178).relayEvents;const c=r(1178).maxWireVersion;const l=r(1371).maybePromise;const u=r(1371).now;const h=r(1371).calculateDurationInMs;const d=r(1554);const g=Symbol("resumeQueue");const p=["resumeAfter","startAfter","startAtOperationTime","fullDocument"];const E=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(p);const m={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class ChangeStream extends o{constructor(e,t,o){super();const s=r(5193);const i=r(6662);const a=r(1545);this.pipeline=t||[];this.options=o||{};this.parent=e;this.namespace=e.s.namespace;if(e instanceof s){this.type=m.COLLECTION;this.topology=e.s.db.serverConfig}else if(e instanceof i){this.type=m.DATABASE;this.topology=e.serverConfig}else if(e instanceof a){this.type=m.CLUSTER;this.topology=e.topology}else{throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient")}this.promiseLibrary=e.s.promiseLibrary;if(!this.options.readPreference&&e.s.readPreference){this.options.readPreference=e.s.readPreference}this[g]=new n;this.cursor=createChangeStreamCursor(this,o);this.closed=false;this.on("newListener",(e=>{if(e==="change"&&this.cursor&&this.listenerCount("change")===0){this.cursor.on("data",(e=>processNewChange(this,e)))}}));this.on("removeListener",(e=>{if(e==="change"&&this.listenerCount("change")===0&&this.cursor){this.cursor.removeAllListeners("data")}}))}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.hasNext(e)}))}))}next(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.next(((t,r)=>{if(t){this[g].push((()=>this.next(e)));processError(this,t,e);return}processNewChange(this,r,e)}))}))}))}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,(e=>{if(this.closed)return e();this.closed=true;if(!this.cursor)return e();const t=this.cursor;return t.close((r=>{["data","close","end","error"].forEach((e=>t.removeAllListeners(e)));this.cursor=undefined;return e(r)}))}))}pipe(e,t){if(!this.pipeDestinations){this.pipeDestinations=[]}this.pipeDestinations.push(e);return this.cursor.pipe(e,t)}unpipe(e){if(this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1){this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1)}return this.cursor.unpipe(e)}stream(e){this.streamOptions=e;return this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}class ChangeStreamCursor extends a{constructor(e,t,r){super(e,t,r);r=r||{};this._resumeToken=null;this.startAtOperationTime=r.startAtOperationTime;if(r.startAfter){this.resumeToken=r.startAfter}else if(r.resumeAfter){this.resumeToken=r.resumeAfter}}set resumeToken(e){this._resumeToken=e;this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of E){if(this.options[t])e[t]=this.options[t]}if(this.resumeToken||this.startAtOperationTime){["resumeAfter","startAfter","startAtOperationTime"].forEach((t=>delete e[t]));if(this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else if(this.startAtOperationTime&&c(this.server)>=7){e.startAtOperationTime=this.startAtOperationTime}}return e}cacheResumeToken(e){if(this.bufferedCount()===0&&this.cursorState.postBatchResumeToken){this.resumeToken=this.cursorState.postBatchResumeToken}else{this.resumeToken=e}this.hasReceived=true}_processBatch(e,t){const r=t.cursor;if(r.postBatchResumeToken){this.cursorState.postBatchResumeToken=r.postBatchResumeToken;if(r[e].length===0){this.resumeToken=r.postBatchResumeToken}}}_initializeCursor(e){super._initializeCursor(((t,r)=>{if(t||r==null){e(t,r);return}const n=r.documents[0];if(this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&c(this.server)>=7){this.startAtOperationTime=n.operationTime}this._processBatch("firstBatch",n);this.emit("init",r);this.emit("response");e(t,r)}))}_getMore(e){super._getMore(((t,r)=>{if(t){e(t);return}this._processBatch("nextBatch",r);this.emit("more",r);this.emit("response");e(t,r)}))}}function createChangeStreamCursor(e,t){const r={fullDocument:t.fullDocument||"default"};applyKnownOptions(r,t,p);if(e.type===m.CLUSTER){r.allChangesForCluster=true}const n=[{$changeStream:r}].concat(e.pipeline);const o=applyKnownOptions({},t,E);const s=new ChangeStreamCursor(e.topology,new d(e.parent,n,t),o);A(s,e,["resumeTokenChanged","end","close"]);if(e.listenerCount("change")>0){s.on("data",(function(t){processNewChange(e,t)}))}s.on("error",(function(t){processError(e,t)}));if(e.pipeDestinations){const t=s.stream(e.streamOptions);for(let r of e.pipeDestinations){t.pipe(r)}}return s}function applyKnownOptions(e,t,r){r.forEach((r=>{if(t[r]){e[r]=t[r]}}));return e}const C=3e4;function waitForTopologyConnected(e,t,r){setTimeout((()=>{if(t&&t.start==null){t.start=u()}const n=t.start||u();const o=t.timeout||C;const s=t.readPreference;if(e.isConnected({readPreference:s})){return r()}if(h(n)>o){return r(new i("Timed out waiting for connection"))}waitForTopologyConnected(e,t,r)}),500)}function processNewChange(e,t,r){const n=e.cursor;if(t==null){e.closed=true}if(e.closed){if(r)r(new i("ChangeStream is closed"));return}if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");if(!r)return e.emit("error",t);return r(t)}n.cacheResumeToken(t._id);e.options.startAtOperationTime=undefined;if(!r)return e.emit("change",t);return r(undefined,t)}function processError(e,t,r){const n=e.topology;const o=e.cursor;if(e.closed){if(r)r(new i("ChangeStream is closed"));return}function resumeWithCursor(t){e.cursor=t;processResumeQueue(e)}function unresumableError(t){if(!r){e.emit("error",t);e.emit("close")}processResumeQueue(e,t);e.closed=true}if(o&&s(t,c(o.server))){e.cursor=undefined;["data","close","end","error"].forEach((e=>o.removeAllListeners(e)));o.close();waitForTopologyConnected(n,{readPreference:o.options.readPreference},(t=>{if(t)return unresumableError(t);const n=createChangeStreamCursor(e,o.resumeOptions);if(!r)return resumeWithCursor(n);n.hasNext((e=>{if(e)return unresumableError(e);resumeWithCursor(n)}))}));return}if(!r)return e.emit("error",t);return r(t)}function getCursor(e,t){if(e.isClosed()){t(new i("ChangeStream is closed."));return}if(e.cursor){t(undefined,e.cursor);return}e[g].push(t)}function processResumeQueue(e,t){while(e[g].length){const r=e[g].pop();if(e.isClosed()&&!t){r(new i("Change Stream is not open."));return}r(t,e.cursor)}}e.exports=ChangeStream},9820:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2425);const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(3111).MongoNetworkTimeoutError;const A=r(3111).MongoWriteConcernError;const c=r(2337);const l=r(6292).StreamDescription;const u=r(9206);const h=r(9815);const d=r(5474).updateSessionFromResponse;const g=r(1178).uuidV4;const p=r(1371).now;const E=r(1371).calculateDurationInMs;const m=Symbol("stream");const C=Symbol("queue");const I=Symbol("messageStream");const y=Symbol("generation");const B=Symbol("lastUseTime");const Q=Symbol("clusterTime");const b=Symbol("description");const w=Symbol("ismaster");const S=Symbol("autoEncrypter");class Connection extends n{constructor(e,t){super(t);this.id=t.id;this.address=streamIdentifier(e);this.bson=t.bson;this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.host=t.host||"localhost";this.port=t.port||27017;this.monitorCommands=typeof t.monitorCommands==="boolean"?t.monitorCommands:false;this.serverApi=t.serverApi;this.closed=false;this.destroyed=false;this[b]=new l(this.address,t);this[y]=t.generation;this[B]=p();if(t.autoEncrypter){this[S]=t.autoEncrypter}this[C]=new Map;this[I]=new o(t);this[I].on("message",messageHandler(this));this[m]=e;e.on("error",(()=>{}));this[I].on("error",(e=>this.handleIssue({destroy:e})));e.on("close",(()=>this.handleIssue({isClose:true})));e.on("timeout",(()=>this.handleIssue({isTimeout:true,destroy:true})));e.pipe(this[I]);this[I].pipe(e)}get description(){return this[b]}get ismaster(){return this[w]}set ismaster(e){this[b].receiveResponse(e);this[w]=e}get generation(){return this[y]||0}get idleTime(){return E(this[B])}get clusterTime(){return this[Q]}get stream(){return this[m]}markAvailable(){this[B]=p()}handleIssue(e){if(this.closed){return}if(e.destroy){this[m].destroy(typeof e.destroy==="boolean"?undefined:e.destroy)}this.closed=true;for(const t of this[C]){const r=t[1];if(e.isTimeout){r.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null}))}else if(e.isClose){r.cb(new i(`connection ${this.id} to ${this.address} closed`))}else{r.cb(typeof e.destroy==="boolean"?undefined:e.destroy)}}this[C].clear();this.emit("close")}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(this[m]==null||this.destroyed){this.destroyed=true;if(typeof t==="function"){t()}return}if(e.force){this[m].destroy();this.destroyed=true;if(typeof t==="function"){t()}return}this[m].end((e=>{this.destroyed=true;if(typeof t==="function"){t(e)}}))}applyApiVersion(e){if(this.serverApi){e.serverApi=this.serverApi}return e}command(e,t,r,n){if(typeof r==="function"){n=r;r={}}u.command(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}query(e,t,r,n,o){u.query(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}getMore(e,t,r,n,o){u.getMore(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}killCursors(e,t,r){u.killCursors(makeServerTrampoline(this),e,t,this.applyApiVersion({}),r)}insert(e,t,r,n){u.insert(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}update(e,t,r,n){u.update(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}remove(e,t,r,n){u.remove(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}}function makeServerTrampoline(e){const t={description:e.description,clusterTime:e[Q],s:{bson:e.bson,pool:{write:write.bind(e),isConnected:()=>true}}};if(e[S]){t.autoEncrypter=e[S]}return t}function messageHandler(e){return function messageHandler(t){e.emit("message",t);if(!e[C].has(t.responseTo)){return}const r=e[C].get(t.responseTo);const n=r.cb;e[C].delete(t.responseTo);if(t.moreToCome){e[C].set(t.requestId,r)}else if(r.socketTimeoutOverride){e[m].setTimeout(e.socketTimeout)}try{t.parse(r)}catch(e){n(new s(e));return}if(t.documents[0]){const o=t.documents[0];const i=r.session;if(i){d(i,o)}if(o.$clusterTime){e[Q]=o.$clusterTime;e.emit("clusterTimeReceived",o.$clusterTime)}if(r.command){if(o.writeConcernError){n(new A(o.writeConcernError,o));return}if(o.ok===0||o.$err||o.errmsg||o.code){n(new s(o));return}}}n(undefined,new c(r.fullResult?t:t.documents[0],e,t))}}function streamIdentifier(e){if(typeof e.address==="function"){return`${e.remoteAddress}:${e.remotePort}`}return g().toString("hex")}function write(e,t,r){if(typeof t==="function"){r=t}t=t||{};const n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false,noResponse:typeof t.noResponse==="boolean"?t.noResponse:false,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,raw:typeof t.raw==="boolean"?t.raw:false};if(this[b]&&this[b].compressor){n.agreedCompressor=this[b].compressor;if(this[b].zlibCompressionLevel){n.zlibCompressionLevel=this[b].zlibCompressionLevel}}if(typeof t.socketTimeout==="number"){n.socketTimeoutOverride=true;this[m].setTimeout(t.socketTimeout)}if(this.monitorCommands){this.emit("commandStarted",new h.CommandStartedEvent(this,e));n.started=p();n.cb=(t,o)=>{if(t){this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,n.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,n.started))}else{this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,n.started))}}if(typeof r==="function"){r(t,o)}}}if(!n.noResponse){this[C].set(n.requestId,n)}try{this[I].writeCommand(e,n)}catch(e){if(!n.noResponse){this[C].delete(n.requestId);n.cb(e);return}}if(n.noResponse){n.cb()}}e.exports={Connection:Connection}},2529:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361).EventEmitter;const s=r(104);const i=r(1371).makeCounter;const a=r(3111).MongoError;const A=r(9820).Connection;const c=r(1178).eachAsync;const l=r(6573);const u=r(1178).relayEvents;const h=r(2926);const d=h.PoolClosedError;const g=h.WaitQueueTimeoutError;const p=r(897);const E=p.ConnectionPoolCreatedEvent;const m=p.ConnectionPoolClosedEvent;const C=p.ConnectionCreatedEvent;const I=p.ConnectionReadyEvent;const y=p.ConnectionClosedEvent;const B=p.ConnectionCheckOutStartedEvent;const Q=p.ConnectionCheckOutFailedEvent;const b=p.ConnectionCheckedOutEvent;const w=p.ConnectionCheckedInEvent;const S=p.ConnectionPoolClearedEvent;const v=Symbol("logger");const R=Symbol("connections");const k=Symbol("permits");const D=Symbol("minPoolSizeTimer");const N=Symbol("generation");const T=Symbol("connectionCounter");const O=Symbol("cancellationToken");const _=Symbol("waitQueue");const M=Symbol("cancelled");const L=new Set(["ssl","bson","connectionType","serverApi","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 resolveOptions(e,t){const r=Array.from(L).reduce(((t,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){t[r]=e[r]}return t}),{});return Object.freeze(Object.assign({},t,r))}class ConnectionPool extends o{constructor(e){super();e=e||{};this.closed=false;this.options=resolveOptions(e,{connectionType:A,maxPoolSize:typeof e.maxPoolSize==="number"?e.maxPoolSize:100,minPoolSize:typeof e.minPoolSize==="number"?e.minPoolSize:0,maxIdleTimeMS:typeof e.maxIdleTimeMS==="number"?e.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof e.waitQueueTimeoutMS==="number"?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata,useUnifiedTopology:e.useUnifiedTopology});if(e.minSize>e.maxSize){throw new TypeError("Connection pool minimum size must not be greater than maximum pool size")}this[v]=s("ConnectionPool",e);this[R]=new n;this[k]=this.options.maxPoolSize;this[D]=undefined;this[N]=0;this[T]=i(1);this[O]=new o;this[O].setMaxListeners(Infinity);this[_]=new n;process.nextTick((()=>{this.emit("connectionPoolCreated",new E(this));ensureMinPoolSize(this)}))}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[N]}get totalConnectionCount(){return this[R].length+(this.options.maxPoolSize-this[k])}get availableConnectionCount(){return this[R].length}get waitQueueSize(){return this[_].length}checkOut(e){this.emit("connectionCheckOutStarted",new B(this));if(this.closed){this.emit("connectionCheckOutFailed",new Q(this,"poolClosed"));e(new d(this));return}const t={callback:e};const r=this;const n=this.options.waitQueueTimeoutMS;if(n){t.timer=setTimeout((()=>{t[M]=true;t.timer=undefined;r.emit("connectionCheckOutFailed",new Q(r,"timeout"));t.callback(new g(r))}),n)}this[_].push(t);process.nextTick((()=>processWaitQueue(this)))}checkIn(e){const t=this.closed;const r=connectionIsStale(this,e);const n=!!(t||r||e.closed);if(!n){e.markAvailable();this[R].push(e)}this.emit("connectionCheckedIn",new w(this,e));if(n){const r=e.closed?"error":t?"poolClosed":"stale";destroyConnection(this,e,r)}process.nextTick((()=>processWaitQueue(this)))}clear(){this[N]+=1;this.emit("connectionPoolCleared",new S(this))}close(e,t){if(typeof e==="function"){t=e}e=Object.assign({force:false},e);if(this.closed){return t()}this[O].emit("cancel");while(this.waitQueueSize){const e=this[_].pop();clearTimeout(e.timer);if(!e[M]){e.callback(new a("connection pool closed"))}}if(this[D]){clearTimeout(this[D])}if(typeof this[T].return==="function"){this[T].return()}this.closed=true;c(this[R].toArray(),((t,r)=>{this.emit("connectionClosed",new y(this,t,"poolClosed"));t.destroy(e,r)}),(e=>{this[R].clear();this.emit("connectionPoolClosed",new m(this));t(e)}))}withConnection(e,t){this.checkOut(((r,n)=>{e(r,n,((e,r)=>{if(typeof t==="function"){if(e){t(e)}else{t(undefined,r)}}if(n){this.checkIn(n)}}))}))}}function ensureMinPoolSize(e){if(e.closed||e.options.minPoolSize===0){return}const t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rensureMinPoolSize(e)),10)}function connectionIsStale(e,t){return t.generation!==e[N]}function connectionIsIdle(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function createConnection(e,t){const r=Object.assign({id:e[T].next().value,generation:e[N]},e.options);e[k]--;l(r,e[O],((r,n)=>{if(r){e[k]++;e[v].debug(`connection attempt failed with error [${JSON.stringify(r)}]`);if(typeof t==="function"){t(r)}return}if(e.closed){n.destroy({force:true});return}u(n,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]);e.emit("connectionCreated",new C(e,n));n.markAvailable();e.emit("connectionReady",new I(e,n));if(typeof t==="function"){t(undefined,n);return}e[R].push(n);process.nextTick((()=>processWaitQueue(e)))}))}function destroyConnection(e,t,r){e.emit("connectionClosed",new y(e,t,r));e[k]++;process.nextTick((()=>t.destroy()))}function processWaitQueue(e){if(e.closed){return}while(e.waitQueueSize){const t=e[_].peekFront();if(t[M]){e[_].shift();continue}if(!e.availableConnectionCount){break}const r=e[R].shift();const n=connectionIsStale(e,r);const o=connectionIsIdle(e,r);if(!n&&!o&&!r.closed){e.emit("connectionCheckedOut",new b(e,r));clearTimeout(t.timer);e[_].shift();t.callback(undefined,r);return}const s=r.closed?"error":n?"stale":"idle";destroyConnection(e,r,s)}const t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{const n=e[_].shift();if(n==null||n[M]){if(t==null){e[R].push(r)}return}if(t){e.emit("connectionCheckOutFailed",new Q(e,t))}else{e.emit("connectionCheckedOut",new b(e,r))}clearTimeout(n.timer);n.callback(t,r)}));return}}e.exports={ConnectionPool:ConnectionPool}},2926:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class PoolClosedError extends n{constructor(e){super("Attempted to check out a connection from closed connection pool");this.name="MongoPoolClosedError";this.address=e.address}}class WaitQueueTimeoutError extends n{constructor(e){super("Timed out while checking out a connection from connection pool");this.name="MongoWaitQueueTimeoutError";this.address=e.address}}e.exports={PoolClosedError:PoolClosedError,WaitQueueTimeoutError:WaitQueueTimeoutError}},897:e=>{"use strict";class ConnectionPoolMonitoringEvent{constructor(e){this.time=new Date;this.address=e.address}}class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e);this.options=e.options}}class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t,r){super(e);this.connectionId=t.id;this.reason=r||"unknown"}}class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.reason=t}}class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}const t=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];e.exports={CMAP_EVENT_NAMES:t,ConnectionPoolCreatedEvent:ConnectionPoolCreatedEvent,ConnectionPoolClosedEvent:ConnectionPoolClosedEvent,ConnectionCreatedEvent:ConnectionCreatedEvent,ConnectionReadyEvent:ConnectionReadyEvent,ConnectionClosedEvent:ConnectionClosedEvent,ConnectionCheckOutStartedEvent:ConnectionCheckOutStartedEvent,ConnectionCheckOutFailedEvent:ConnectionCheckOutFailedEvent,ConnectionCheckedOutEvent:ConnectionCheckedOutEvent,ConnectionCheckedInEvent:ConnectionCheckedInEvent,ConnectionPoolClearedEvent:ConnectionPoolClearedEvent}},2425:(e,t,r)=>{"use strict";const n=r(2781).Duplex;const o=r(336);const s=r(3111).MongoParseError;const i=r(7793).decompress;const a=r(9814).Response;const A=r(8988).BinMsg;const c=r(3111).MongoError;const l=r(7272).opcodes.OP_COMPRESSED;const u=r(7272).opcodes.OP_MSG;const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(8988).Msg;const I=1024*1024*16*4;const y=Symbol("buffer");class MessageStream extends n{constructor(e){e=e||{};super(e);this.bson=e.bson;this.maxBsonMessageSize=e.maxBsonMessageSize||I;this[y]=new o}_write(e,t,r){const n=this[y];n.append(e);processIncomingData(this,r)}_read(){return}writeCommand(e,t){const r=t&&!!t.agreedCompressor;if(!r||!canCompress(e)){const t=e.toBin();this.push(Array.isArray(t)?Buffer.concat(t):t);return}const n=Buffer.concat(e.toBin());const o=n.slice(h);const s=n.readInt32LE(12);p({options:t},o,((r,n)=>{if(r){t.cb(r,null);return}const i=Buffer.alloc(h);i.writeInt32LE(h+d+n.length,0);i.writeInt32LE(e.requestId,4);i.writeInt32LE(0,8);i.writeInt32LE(g.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(s,0);a.writeInt32LE(o.length,4);a.writeUInt8(E[t.agreedCompressor],8);this.push(Buffer.concat([i,a,n]))}))}}function canCompress(e){const t=e instanceof C?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function processIncomingData(e,t){const r=e[y];if(r.length<4){t();return}const n=r.readInt32LE(0);if(n<0){t(new s(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new s(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}const o=r.slice(0,n);r.consume(n);const d={length:o.readInt32LE(0),requestId:o.readInt32LE(4),responseTo:o.readInt32LE(8),opCode:o.readInt32LE(12)};let g=d.opCode===u?A:a;const p=e.responseOptions;if(d.opCode!==l){const n=o.slice(h);e.emit("message",new g(e.bson,o,d,n,p));if(r.length>=4){processIncomingData(e,t)}else{t()}return}d.fromCompressed=true;d.opCode=o.readInt32LE(h);d.length=o.readInt32LE(h+4);const E=o[h+8];const m=o.slice(h+9);g=d.opCode===u?A:a;i(E,m,((n,s)=>{if(n){t(n);return}if(s.length!==d.length){t(new c("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new g(e.bson,o,d,s,p));if(r.length>=4){processIncomingData(e,t)}else{t()}}))}e.exports=MessageStream},6292:(e,t,r)=>{"use strict";const n=r(750).parseServerType;const o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];class StreamDescription{constructor(e,t){this.address=e;this.type=n(null);this.minWireVersion=undefined;this.maxWireVersion=undefined;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=n(e);o.forEach((t=>{if(typeof e[t]!=="undefined"){this[t]=e[t]}}));if(e.compression){this.compressor=this.compressors.filter((t=>e.compression.indexOf(t)!==-1))[0]}}}e.exports={StreamDescription:StreamDescription}},5193:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(1371).deprecateOptions;const s=r(1371).emitWarningOnce;const i=r(1371).checkCollectionName;const a=r(3994).BSON.ObjectID;const A=r(3994).MongoError;const c=r(1371).normalizeHintField;const l=r(1371).decorateCommand;const u=r(1371).decorateWithCollation;const h=r(1371).decorateWithReadConcern;const d=r(1371).formattedOrderClause;const g=r(3994).ReadPreference;const p=r(325);const E=r(5035);const m=r(1117);const C=r(1371).executeLegacyOperation;const I=r(2481);const y=r(7289);const B=r(1371).MongoDBNamespace;const Q=r(7429);const b=r(538);const w=r(6716).ensureIndex;const S=r(6716).group;const v=r(6716).parallelCollectionScan;const R=r(2296).removeDocuments;const k=r(6716).save;const D=r(2296).updateDocuments;const N=r(1554);const T=r(6976);const O=r(5131);const _=r(6394);const M=r(323);const L=r(6352);const F=r(6469);const U=r(2360).DropCollectionOperation;const P=r(3560);const G=r(5328);const Y=r(4451);const V=r(9961);const W=r(4497);const J=r(711);const q=r(5841);const j=r(4316);const z=r(1925);const $=r(8169);const K=r(4218);const X=r(7809);const Z=r(4245);const ee=r(3592);const te=r(9915);const re=r(4956);const ne=r(28);const oe=r(2779);const se=r(43);const ie=r(2808);const ae=r(6331);const Ae=r(2508);const ce=r(968);const le=r(9350);const ue=r(9068);const fe=r(2548);const he=["ignoreUndefined"];function Collection(e,t,r,n,o,s){i(n);const A=null;const c=s==null||s.slaveOk==null?e.slaveOk:s.slaveOk;const l=s==null||s.serializeFunctions==null?e.s.options.serializeFunctions:s.serializeFunctions;const u=s==null||s.raw==null?e.s.options.raw:s.raw;const h=s==null||s.promoteLongs==null?e.s.options.promoteLongs:s.promoteLongs;const d=s==null||s.promoteValues==null?e.s.options.promoteValues:s.promoteValues;const p=s==null||s.promoteBuffers==null?e.s.options.promoteBuffers:s.promoteBuffers;const E=s==null||s.bsonRegExp==null?e.s.options.bsonRegExp:s.bsonRegExp;const m=null;const C=new B(r,n);const Q=s.promiseLibrary||Promise;o=o==null?a:o;this.s={pkFactory:o,db:e,topology:t,options:s,namespace:C,readPreference:g.fromOptions(s),slaveOk:c,serializeFunctions:l,raw:u,promoteLongs:h,promoteValues:d,promoteBuffers:p,bsonRegExp:E,internalHint:A,collectionHint:m,promiseLibrary:Q,readConcern:y.fromOptions(s),writeConcern:I.fromOptions(s)}}Object.defineProperty(Collection.prototype,"dbName",{enumerable:true,get:function(){return this.s.namespace.db}});Object.defineProperty(Collection.prototype,"collectionName",{enumerable:true,get:function(){return this.s.namespace.collection}});Object.defineProperty(Collection.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Object.defineProperty(Collection.prototype,"readConcern",{enumerable:true,get:function(){if(this.s.readConcern==null){return this.s.db.readConcern}return this.s.readConcern}});Object.defineProperty(Collection.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return this.s.db.readPreference}return this.s.readPreference}});Object.defineProperty(Collection.prototype,"writeConcern",{enumerable:true,get:function(){if(this.s.writeConcern==null){return this.s.db.writeConcern}return this.s.writeConcern}});Object.defineProperty(Collection.prototype,"hint",{enumerable:true,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const de=["maxScan","fields","snapshot","oplogReplay"];Collection.prototype.find=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `find()` must be a callback or undefined")}let n=e;if(typeof r!=="function"){if(typeof t==="function"){r=t;t=undefined}else if(t==null){r=typeof n==="function"?n:undefined;n=typeof n==="object"?n:undefined}}n=n==null?{}:n;const o=n;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+"]");t.name="MongoError";throw t}}if(n!=null&&n._bsontype==="ObjectID"){n={_id:n}}if(!t)t={};let i=t.projection||t.fields;if(i&&!Buffer.isBuffer(i)&&Array.isArray(i)){i=i.length?i.reduce(((e,t)=>{e[t]=1;return e}),{}):{_id:1}}let a=Object.assign({},t);for(let e in this.s.options){if(he.indexOf(e)!==-1){a[e]=this.s.options[e]}}a.skip=t.skip?t.skip:0;a.limit=t.limit?t.limit:0;a.raw=typeof t.raw==="boolean"?t.raw:this.s.raw;a.hint=t.hint!=null?c(t.hint):this.s.collectionHint;a.timeout=typeof t.timeout==="undefined"?undefined:t.timeout;a.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk;a.readPreference=g.resolve(this,a);if(a.readPreference!=null&&(a.readPreference!=="primary"||a.readPreference.mode!=="primary")){a.slaveOk=true}if(n!=null&&typeof n!=="object"){throw A.create({message:"query selector must be an object",driver:true})}const p={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:n};if(typeof t.allowDiskUse==="boolean"){p.allowDiskUse=t.allowDiskUse}if(typeof a.awaitdata==="boolean"){a.awaitData=a.awaitdata}if(typeof a.timeout==="boolean")a.noCursorTimeout=!a.timeout;l(p,a,["session","collation"]);if(i)p.fields=i;a.db=this.s.db;a.promiseLibrary=this.s.promiseLibrary;if(a.raw==null&&typeof this.s.raw==="boolean")a.raw=this.s.raw;if(a.promoteLongs==null&&typeof this.s.promoteLongs==="boolean")a.promoteLongs=this.s.promoteLongs;if(a.promoteValues==null&&typeof this.s.promoteValues==="boolean")a.promoteValues=this.s.promoteValues;if(a.promoteBuffers==null&&typeof this.s.promoteBuffers==="boolean")a.promoteBuffers=this.s.promoteBuffers;if(a.bsonRegExp==null&&typeof this.s.bsonRegExp==="boolean")a.bsonRegExp=this.s.bsonRegExp;if(p.sort){p.sort=d(p.sort)}h(p,this,t);try{u(p,this,t)}catch(e){if(typeof r==="function")return r(e,null);throw e}const E=this.s.topology.cursor(new V(this,this.s.namespace,p,a),a);if(typeof r==="function"){r(null,E);return}return E}));Collection.prototype.insertOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new te(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insertMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{ordered:true};const n=new ee(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.bulkWrite=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:true};if(!Array.isArray(e)){throw A.create({message:"operations must be an array of documents",driver:true})}const n=new T(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insert=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:false};e=!Array.isArray(e)?[e]:e;if(t.keepGoing===true){t.ordered=false}return this.insertMany(e,t,r)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");Collection.prototype.updateOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new ue(this,e,t,r),n)};Collection.prototype.replaceOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new Ae(this,e,t,r),n)};Collection.prototype.updateMany=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new le(this,e,t,r),n)};Collection.prototype.update=n((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,D,[this,e,t,r,n])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");Collection.prototype.deleteOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new L(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeOne=Collection.prototype.deleteOne;Collection.prototype.deleteMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new M(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeMany=Collection.prototype.deleteMany;Collection.prototype.remove=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,R,[this,e,t,r])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");Collection.prototype.save=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,k,[this,e,t,r])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");Collection.prototype.findOne=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `findOne()` must be a callback or undefined")}if(typeof e==="function")r=e,e={},t={};if(typeof t==="function")r=t,t={};e=e||{};t=t||{};const n=new W(this,e,t);return fe(this.s.topology,n,r)}));Collection.prototype.rename=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t,{readPreference:g.PRIMARY});const n=new ie(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.drop=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new U(this.s.db,this.collectionName,e);return fe(this.s.topology,r,t)};Collection.prototype.options=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new se(this,e);return fe(this.s.topology,r,t)};Collection.prototype.isCapped=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new re(this,e);return fe(this.s.topology,r,t)};Collection.prototype.createIndex=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.createIndexes=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{};if(typeof t.maxTimeMS!=="number")delete t.maxTimeMS;const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.dropIndex=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift()||{}:{};t.readPreference=g.PRIMARY;const o=new P(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.dropIndexes=function(e,t){if(typeof e==="function")t=e,e={};e=e?Object.assign({},e):{};if(typeof e.maxTimeMS!=="number")delete e.maxTimeMS;const r=new G(this,e);return fe(this.s.topology,r,t)};Collection.prototype.dropAllIndexes=n(Collection.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");Collection.prototype.reIndex=n((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new ae(this,e);return fe(this.s.topology,r,t)}),"collection.reIndex is deprecated. Use db.command instead.");Collection.prototype.listIndexes=function(e){const t=new b(this.s.topology,new ne(this,e),e);return t};Collection.prototype.ensureIndex=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return C(this.s.topology,w,[this,e,t,r])}),"collection.ensureIndex is deprecated. Use createIndexes instead.");Collection.prototype.indexExists=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new X(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.indexInformation=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new Z(this.s.db,this.collectionName,e);return fe(this.s.topology,n,t)};Collection.prototype.count=n((function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};if(typeof t==="function")r=t,t={};t=t||{};return fe(this.s.topology,new Y(this,Object.assign({query:e},t)),r)}),"collection.count is deprecated, and will be removed in a future version."+" Use Collection.countDocuments or Collection.estimatedDocumentCount instead");Collection.prototype.estimatedDocumentCount=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new Y(this,e);return fe(this.s.topology,r,t)};Collection.prototype.countDocuments=function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};const o=new O(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.distinct=function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;const s=o.length?o.shift()||{}:{};const i=o.length?o.shift()||{}:{};const a=new F(this,e,s,i);return fe(this.s.topology,a,n)};Collection.prototype.indexes=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new K(this,e);return fe(this.s.topology,r,t)};Collection.prototype.stats=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new ce(this,e);return fe(this.s.topology,n,t)};Collection.prototype.findOneAndDelete=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new q(this,e,t),r)};Collection.prototype.findOneAndReplace=o({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new j(this,e,t,r),n)}));Collection.prototype.findOneAndUpdate=o({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new z(this,e,t,r),n)}));Collection.prototype.findAndModify=n(_findAndModify,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");Collection.prototype._findAndModify=_findAndModify;function _findAndModify(e,t,r,n,o){const s=Array.prototype.slice.call(arguments,1);o=typeof s[s.length-1]==="function"?s.pop():undefined;t=s.length?s.shift()||[]:[];r=s.length?s.shift():null;n=s.length?s.shift()||{}:{};n=Object.assign({},n);n.readPreference=g.PRIMARY;return fe(this.s.topology,new J(this,e,t,r,n),o)}Collection.prototype.findAndRemove=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift()||[]:[];r=o.length?o.shift()||{}:{};r.remove=true;return fe(this.s.topology,new J(this,e,t,null,r),n)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");Collection.prototype.aggregate=function(e,t,r){if(Array.isArray(e)){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}}else{const n=Array.prototype.slice.call(arguments,0);r=n.pop();const o=n[n.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?n.pop():{};e=n}const n=new Q(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Collection.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Collection.prototype.parallelCollectionScan=n((function(e,t){if(typeof e==="function")t=e,e={numCursors:1};e.numCursors=e.numCursors||1;e.batchSize=e.batchSize||1e3;e=Object.assign({},e);e.readPreference=g.resolve(this,e);e.promiseLibrary=this.s.promiseLibrary;if(e.session){e.session=undefined}return C(this.s.topology,v,[this,e,t],{skipSessions:true})}),"parallelCollectionScan is deprecated in MongoDB v4.1");Collection.prototype.geoHaystackSearch=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift()||{}:{};const s=new $(this,e,t,r);return fe(this.s.topology,s,n)}),"geoHaystackSearch is deprecated, and will be removed in a future version.");Collection.prototype.group=n((function(e,t,r,n,o,s,i,a){const A=Array.prototype.slice.call(arguments,3);a=typeof A[A.length-1]==="function"?A.pop():undefined;n=A.length?A.shift():null;o=A.length?A.shift():null;s=A.length?A.shift():null;i=A.length?A.shift()||{}:{};if(!(typeof o==="function")){s=o;o=null}if(!Array.isArray(e)&&e instanceof Object&&typeof e!=="function"&&!(e._bsontype==="Code")){e=Object.keys(e)}if(typeof n==="function"){n=n.toString()}if(typeof o==="function"){o=o.toString()}s=s==null?true:s;return C(this.s.topology,S,[this,e,t,r,n,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");Collection.prototype.mapReduce=function(e,t,r,n){if("function"===typeof r)n=r,r={};if(null==r.out){throw new Error("the out option parameter must be defined, see mongodb docs for possible values")}if("function"===typeof e){e=e.toString()}if("function"===typeof t){t=t.toString()}if("function"===typeof r.finalize){r.finalize=r.finalize.toString()}const o=new oe(this,e,t,r);return fe(this.s.topology,o,n)};Collection.prototype.initializeUnorderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return p(this.s.topology,this,e)};Collection.prototype.initializeOrderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return E(this.s.topology,this,e)};Collection.prototype.getLogger=function(){return this.s.db.s.logger};e.exports=Collection},538:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(3994).MongoError;const s=r(7159);const i=r(4847).CursorState;class CommandCursor extends s{constructor(e,t,r,n){super(e,t,r,n)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(this.s.state!==i.INIT){throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof n){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new n(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw o.create({message:"batchSize requires an integer",driver:true})}if(this.cmd.cursor){this.cmd.cursor.batchSize=e}this.setCursorBatchSize(e);return this}maxTimeMS(e){if(this.topology.lastIsMaster().minWireVersion>2){this.cmd.maxTimeMS=e}return this}getLogger(){return this.logger}}CommandCursor.prototype.get=CommandCursor.prototype.toArray;e.exports=CommandCursor},7703:(e,t,r)=>{"use strict";const n=r(8988).Msg;const o=r(9814).KillCursor;const s=r(9814).GetMore;const i=r(1371).deepCopy;const a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const A=new Set(["hello","ismaster","isMaster"]);const c={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"};const l={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"};const u=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"];const collectionName=e=>e.ns.split(".")[1];const shouldRedactCommand=(e,t)=>a.has(e)||A.has(e)&&!!t.speculativeAuthenticate;const extractCommand=e=>{let t;if(e instanceof s){t={getMore:i(e.cursorId),collection:collectionName(e),batchSize:e.numberToReturn}}else if(e instanceof o){t={killCursors:collectionName(e),cursors:i(e.cursorIds)}}else if(e instanceof n){t=i(e.command)}else if(e.query&&e.query.$query){let r;if(e.ns==="admin.$cmd"){r=Object.assign({},e.query.$query)}else{r={find:collectionName(e)};Object.keys(c).forEach((t=>{if(typeof e.query[t]!=="undefined")r[c[t]]=i(e.query[t])}))}Object.keys(l).forEach((t=>{if(typeof e[t]!=="undefined")r[l[t]]=i(e[t])}));u.forEach((t=>{if(e[t])r[t]=e[t]}));if(typeof e.pre32Limit!=="undefined"){r.limit=e.pre32Limit}if(e.query.$explain){t={explain:r}}else{t=r}}else{t=i(e.query||e)}const r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:shouldRedactCommand(r,t)}};e.exports={extractCommand:extractCommand}},147:e=>{"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"}},557:e=>{"use strict";class AuthContext{constructor(e,t,r){this.connection=e;this.credentials=t;this.options=r}}class AuthProvider{constructor(e){this.bson=e}prepare(e,t,r){r(undefined,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}e.exports={AuthContext:AuthContext,AuthProvider:AuthProvider}},2192:(e,t,r)=>{"use strict";const n=r(4228);const o=r(7324);const s=r(8728);const i=r(2640);const a=r(864).ScramSHA1;const A=r(864).ScramSHA256;const c=r(8857);function defaultAuthProviders(e){return{"mongodb-aws":new c(e),mongocr:new n(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new A(e)}}e.exports={defaultAuthProviders:defaultAuthProviders}},2640:(e,t,r)=>{"use strict";const n=r(7578);const o=r(557).AuthProvider;const s=r(1178).retrieveKerberos;const i=r(3111).MongoError;let a;class GSSAPI extends o{auth(e,t){const r=e.connection;const n=e.credentials;if(n==null)return t(new i("credentials required"));const o=n.username;function externalCommand(e,t){return r.command("$external.$cmd",e,t)}makeKerberosClient(e,((e,r)=>{if(e)return t(e);if(r==null)return t(new i("gssapi client missing"));r.step("",((e,n)=>{if(e)return t(e);externalCommand(saslStart(n),((e,n)=>{if(e)return t(e);const s=n.result;negotiate(r,10,s.payload,((e,n)=>{if(e)return t(e);externalCommand(saslContinue(n,s.conversationId),((e,n)=>{if(e)return t(e);const s=n.result;finalize(r,o,s.payload,((e,r)=>{if(e)return t(e);externalCommand({saslContinue:1,conversationId:s.conversationId,payload:r},((e,r)=>{if(e)return t(e);t(undefined,r)}))}))}))}))}))}))}))}}e.exports=GSSAPI;function makeKerberosClient(e,t){const r=e.options.host;const n=e.options.port;const o=e.credentials;if(!r||!n||!o){return t(new i(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${o?"host":"credentials"}.`))}if(a==null){try{a=s()}catch(e){return t(e)}}const A=o.username;const c=o.password;const l=o.mechanismProperties;const u=l["gssapiservicename"]||l["gssapiServiceName"]||"mongodb";performGssapiCanonicalizeHostName(r,l,((e,r)=>{if(e)return t(e);const n={};if(c!=null){Object.assign(n,{user:A,password:c})}a.initializeClient(`${u}${process.platform==="win32"?"/":"@"}${r}`,n,((e,r)=>{if(e)return t(new i(e));t(null,r)}))}))}function saslStart(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}function saslContinue(e,t){return{saslContinue:1,conversationId:t,payload:e}}function negotiate(e,t,r,n){e.step(r,((o,s)=>{if(o&&t===0)return n(o);if(o)return negotiate(e,t-1,r,n);n(undefined,s||"")}))}function finalize(e,t,r,n){e.unwrap(r,((r,o)=>{if(r)return n(r);e.wrap(o||"",{user:t},((e,t)=>{if(e)return n(e);n(undefined,t)}))}))}function performGssapiCanonicalizeHostName(e,t,r){const o=typeof t.gssapiCanonicalizeHostName==="boolean"?t.gssapiCanonicalizeHostName:false;if(!o)return r(undefined,e);n.resolveCname(e,((t,n)=>{if(t)return r(t);if(Array.isArray(n)&&n.length>0){return r(undefined,n[0])}r(undefined,e)}))}},2222:e=>{"use strict";function getDefaultAuthMechanism(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 MongoCredentials{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||{};if(/MONGODB-AWS/i.test(this.mechanism)){if(!this.username&&process.env.AWS_ACCESS_KEY_ID){this.username=process.env.AWS_ACCESS_KEY_ID}if(!this.password&&process.env.AWS_SECRET_ACCESS_KEY){this.password=process.env.AWS_SECRET_ACCESS_KEY}if(this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null){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){if(/DEFAULT/i.test(this.mechanism)){return new MongoCredentials({username:this.username,password:this.password,source:this.source,mechanism:getDefaultAuthMechanism(e),mechanismProperties:this.mechanismProperties})}return this}}e.exports={MongoCredentials:MongoCredentials}},4228:(e,t,r)=>{"use strict";const n=r(6113);const o=r(557).AuthProvider;class MongoCR extends o{auth(e,t){const r=e.connection;const o=e.credentials;const s=o.username;const i=o.password;const a=o.source;r.command(`${a}.$cmd`,{getnonce:1},((e,o)=>{let A=null;let c=null;if(e==null){const e=o.result;A=e.nonce;let t=n.createHash("md5");t.update(s+":mongo:"+i,"utf8");const r=t.digest("hex");t=n.createHash("md5");t.update(A+s+r,"utf8");c=t.digest("hex")}const l={authenticate:1,user:s,nonce:A,key:c};r.command(`${a}.$cmd`,l,t)}))}}e.exports=MongoCR},8857:(e,t,r)=>{"use strict";const n=r(557).AuthProvider;const o=r(2222).MongoCredentials;const s=r(3111).MongoError;const i=r(6113);const a=r(3685);const A=r(1178).maxWireVersion;const c=r(7310);let l;try{l=r(3847)}catch(e){}const u=110;const h="http://169.254.170.2";const d="http://169.254.169.254";const g="/latest/meta-data/iam/security-credentials";class MongoDBAWS extends n{auth(e,t){const r=e.connection;const n=e.credentials;if(A(r)<9){t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(l==null){t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(n.username==null){makeTempCredentials(n,((r,n)=>{if(r)return t(r);e.credentials=n;this.auth(e,t)}));return}const o=n.source;const a=this.bson;const c=n.username;const h=n.password;const d=n.mechanismProperties.AWS_SESSION_TOKEN;const g=c&&h&&d?{accessKeyId:c,secretAccessKey:h,sessionToken:d}:c&&h?{accessKeyId:c,secretAccessKey:h}:undefined;i.randomBytes(32,((e,n)=>{if(e){t(e);return}const i={saslStart:1,mechanism:"MONGODB-AWS",payload:a.serialize({r:n,p:u})};r.command(`${o}.$cmd`,i,((e,i)=>{if(e)return t(e);const A=i.result;const c=a.deserialize(A.payload.buffer);const u=c.h;const h=c.s.buffer;if(h.length!==64){t(new s(`Invalid server nonce length ${h.length}, expected 64`));return}if(h.compare(n,0,n.length,0,n.length)!==0){t(new s("Server nonce does not begin with client nonce"));return}if(u.length<1||u.length>255||u.indexOf("..")!==-1){t(new s(`Server returned an invalid host: "${u}"`));return}const p="Action=GetCallerIdentity&Version=2011-06-15";const E=l.sign({method:"POST",host:u,region:deriveRegion(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":p.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:p},g);const m=E.headers.Authorization;const C=E.headers["X-Amz-Date"];const I={a:m,d:C};if(d){I.t=d}const y={saslContinue:1,conversationId:1,payload:a.serialize(I)};r.command(`${o}.$cmd`,y,(e=>{if(e)return t(e);t()}))}))}))}}function makeTempCredentials(e,t){function done(r){if(r.AccessKeyId==null||r.SecretAccessKey==null||r.Token==null){t(new s("Could not obtain temporary MONGODB-AWS credentials"));return}t(undefined,new o({username:r.AccessKeyId,password:r.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:r.Token}}))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){request(`${h}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,undefined,((e,r)=>{if(e)return t(e);done(r)}));return}request(`${d}/latest/api/token`,{method:"PUT",json:false,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},((e,r)=>{if(e)return t(e);request(`${d}/${g}`,{json:false,headers:{"X-aws-ec2-metadata-token":r}},((e,n)=>{if(e)return t(e);request(`${d}/${g}/${n}`,{headers:{"X-aws-ec2-metadata-token":r}},((e,r)=>{if(e)return t(e);done(r)}))}))}))}function deriveRegion(e){const t=e.split(".");if(t.length===1||t[1]==="amazonaws"){return"us-east-1"}return t[1]}function request(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:true},c.parse(e),t);const n=a.request(t,(e=>{e.setEncoding("utf8");let n="";e.on("data",(e=>n+=e));e.on("end",(()=>{if(t.json===false){r(undefined,n);return}try{const e=JSON.parse(n);r(undefined,e)}catch(e){r(new s(`Invalid JSON response: "${n}"`))}}))}));n.on("error",(e=>r(e)));n.end()}e.exports=MongoDBAWS},8728:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(557).AuthProvider;const s=n();const i=s.Binary;class Plain extends o{auth(e,t){const r=e.connection;const n=e.credentials;const o=n.username;const s=n.password;const a=new i(`\0${o}\0${s}`);const A={saslStart:1,mechanism:"PLAIN",payload:a,autoAuthorize:1};r.command("$external.$cmd",A,t)}}e.exports=Plain},864:(e,t,r)=>{"use strict";const n=r(6113);const o=r(1867).Buffer;const s=r(7746).retrieveBSON;const i=r(3111).MongoError;const a=r(557).AuthProvider;const A=r(1371).emitWarning;const c=s();const l=c.Binary;let u;try{u=r(9178)}catch(e){}class ScramSHA extends a{constructor(e,t){super(e);this.cryptoMethod=t||"sha1"}prepare(e,t,r){const o=this.cryptoMethod;if(o==="sha256"&&typeof u!=="function"){A("Warning: no saslprep library specified. Passwords will not be sanitized")}n.randomBytes(24,((n,s)=>{if(n){return r(n)}Object.assign(t,{nonce:s});const i=t.credentials;const a=Object.assign({},e,{speculativeAuthenticate:Object.assign(makeFirstMessage(o,i,s),{db:i.source})});r(undefined,a)}))}auth(e,t){const r=e.response;if(r&&r.speculativeAuthenticate){continueScramConversation(this.cryptoMethod,r.speculativeAuthenticate,e,t);return}executeScram(this.cryptoMethod,e,t)}}function cleanUsername(e){return e.replace("=","=3D").replace(",","=2C")}function clientFirstMessageBare(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function makeFirstMessage(e,t,r){const n=cleanUsername(t.username);const s=e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256";return{saslStart:1,mechanism:s,payload:new l(o.concat([o.from("n,,","utf8"),clientFirstMessageBare(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:true}}}function executeScram(e,t,r){const n=t.connection;const o=t.credentials;const s=t.nonce;const i=o.source;const a=makeFirstMessage(e,o,s);n.command(`${i}.$cmd`,a,((n,o)=>{const s=resolveError(n,o);if(s){return r(s)}continueScramConversation(e,o.result,t,r)}))}function continueScramConversation(e,t,r,n){const s=r.connection;const a=r.credentials;const A=r.nonce;const c=a.source;const h=cleanUsername(a.username);const d=a.password;let g;if(e==="sha256"){g=typeof u==="function"?u(d):d}else{try{g=passwordDigest(h,d)}catch(e){return n(e)}}const p=o.isBuffer(t.payload)?new l(t.payload):t.payload;const E=parsePayload(p.value());const m=parseInt(E.i,10);if(m&&m<4096){n(new i(`Server returned an invalid iteration count ${m}`),false);return}const C=E.s;const I=E.r;if(I.startsWith("nonce")){n(new i(`Server returned an invalid nonce: ${I}`),false);return}const y=`c=biws,r=${I}`;const B=HI(g,o.from(C,"base64"),m,e);const Q=HMAC(e,B,"Client Key");const b=HMAC(e,B,"Server Key");const w=H(e,Q);const S=[clientFirstMessageBare(h,A),p.value().toString("base64"),y].join(",");const v=HMAC(e,w,S);const R=`p=${xor(Q,v)}`;const k=[y,R].join(",");const D=HMAC(e,b,S);const N={saslContinue:1,conversationId:t.conversationId,payload:new l(o.from(k))};s.command(`${c}.$cmd`,N,((e,t)=>{const r=resolveError(e,t);if(r){return n(r)}const a=t.result;const A=parsePayload(a.payload.value());if(!compareDigest(o.from(A.v,"base64"),D)){n(new i("Server returned an invalid signature"));return}if(!a||a.done!==false){return n(r,a)}const l={saslContinue:1,conversationId:a.conversationId,payload:o.alloc(0)};s.command(`${c}.$cmd`,l,n)}))}function parsePayload(e){const t={};const r=e.split(",");for(let e=0;e=200){_hiCachePurge()}h[s]=i;d+=1;return i}function compareDigest(e,t){if(e.length!==t.length){return false}if(typeof n.timingSafeEqual==="function"){return n.timingSafeEqual(e,t)}let r=0;for(let n=0;n{"use strict";const n=r(557).AuthProvider;class X509 extends n{prepare(e,t,r){const n=t.credentials;Object.assign(e,{speculativeAuthenticate:x509AuthenticateCommand(n)});r(undefined,e)}auth(e,t){const r=e.connection;const n=e.credentials;const o=e.response;if(o.speculativeAuthenticate){return t()}r.command("$external.$cmd",x509AuthenticateCommand(n),t)}}function x509AuthenticateCommand(e){const t={authenticate:1,mechanism:"MONGODB-X509"};if(e.username){Object.assign(t,{user:e.username})}return t}e.exports=X509},9815:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(9814).GetMore;const s=r(1371).calculateDurationInMs;const i=r(7703).extractCommand;const namespace=e=>e.ns;const databaseName=e=>e.ns.split(".")[0];const generateConnectionId=e=>e.options?`${e.options.host}:${e.options.port}`:e.address;const isLegacyPool=e=>e.s&&e.queue;const extractReply=(e,t)=>{if(e instanceof o){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),nextBatch:t.message.documents}}}if(e instanceof n){return{ok:1,cursorsUnknown:e.cursorIds}}if(e.query&&typeof e.query.$query!=="undefined"){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),firstBatch:t.message.documents}}}return t&&t.result?t.result:t};const extractConnectionDetails=e=>{if(isLegacyPool(e)){return{connectionId:generateConnectionId(e)}}const t=e;return{address:t.address,connectionId:t.id}};class CommandStartedEvent{constructor(e,t){const r=i(t);const n=r.name;const o=extractConnectionDetails(e);Object.assign(this,o,{requestId:t.requestId,databaseName:databaseName(t),commandName:n,command:r.shouldRedact?{}:r.cmd})}}class CommandSucceededEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),reply:o.shouldRedact?{}:extractReply(t,r)})}}class CommandFailedEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),failure:o.shouldRedact?{}:r})}}e.exports={CommandStartedEvent:CommandStartedEvent,CommandSucceededEvent:CommandSucceededEvent,CommandFailedEvent:CommandFailedEvent}},2337:e=>{"use strict";var CommandResult=function(e,t,r){this.result=e;this.connection=t;this.message=r};CommandResult.prototype.toJSON=function(){let e=Object.assign({},this,this.result);delete e.message;return e};CommandResult.prototype.toString=function(){return JSON.stringify(this.toJSON())};e.exports=CommandResult},9814:(e,t,r)=>{"use strict";var n=r(7746).retrieveBSON;var o=n();var s=o.Long;const i=r(1867).Buffer;var a=0;var A=r(7272).opcodes;var c=2;var l=4;var u=8;var h=16;var d=32;var g=64;var p=128;var E=1;var m=2;var C=4;var I=8;var Query=function(e,t,r,n){var o=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1){throw new Error("namespace cannot contain a null character")}this.bson=e;this.ns=t;this.query=r;this.numberToSkip=n.numberToSkip||0;this.numberToReturn=n.numberToReturn||0;this.returnFieldSelector=n.returnFieldSelector||null;this.requestId=Query.getRequestId();this.pre32Limit=n.pre32Limit;this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:true;this.batchSize=o.numberToReturn;this.tailable=false;this.slaveOk=typeof n.slaveOk==="boolean"?n.slaveOk:false;this.oplogReplay=false;this.noCursorTimeout=false;this.awaitData=false;this.exhaust=false;this.partial=false};Query.prototype.incRequestId=function(){this.requestId=a++};Query.nextRequestId=function(){return a+1};Query.prototype.toBin=function(){var e=this;var t=[];var r=null;var n=0;if(this.tailable){n|=c}if(this.slaveOk){n|=l}if(this.oplogReplay){n|=u}if(this.noCursorTimeout){n|=h}if(this.awaitData){n|=d}if(this.exhaust){n|=g}if(this.partial){n|=p}if(e.batchSize!==e.numberToReturn)e.numberToReturn=e.batchSize;var o=i.alloc(4*4+4+i.byteLength(e.ns)+1+4+4);t.push(o);var s=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(s);if(e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0){r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(r)}var a=o.length+s.length+(r?r.length:0);var E=4;o[3]=a>>24&255;o[2]=a>>16&255;o[1]=a>>8&255;o[0]=a&255;o[E+3]=this.requestId>>24&255;o[E+2]=this.requestId>>16&255;o[E+1]=this.requestId>>8&255;o[E]=this.requestId&255;E=E+4;o[E+3]=0>>24&255;o[E+2]=0>>16&255;o[E+1]=0>>8&255;o[E]=0&255;E=E+4;o[E+3]=A.OP_QUERY>>24&255;o[E+2]=A.OP_QUERY>>16&255;o[E+1]=A.OP_QUERY>>8&255;o[E]=A.OP_QUERY&255;E=E+4;o[E+3]=n>>24&255;o[E+2]=n>>16&255;o[E+1]=n>>8&255;o[E]=n&255;E=E+4;E=E+o.write(this.ns,E,"utf8")+1;o[E-1]=0;o[E+3]=this.numberToSkip>>24&255;o[E+2]=this.numberToSkip>>16&255;o[E+1]=this.numberToSkip>>8&255;o[E]=this.numberToSkip&255;E=E+4;o[E+3]=this.numberToReturn>>24&255;o[E+2]=this.numberToReturn>>16&255;o[E+1]=this.numberToReturn>>8&255;o[E]=this.numberToReturn&255;E=E+4;return t};Query.getRequestId=function(){return++a};var GetMore=function(e,t,r,n){n=n||{};this.numberToReturn=n.numberToReturn||0;this.requestId=a++;this.bson=e;this.ns=t;this.cursorId=r};GetMore.prototype.toBin=function(){var e=4+i.byteLength(this.ns)+1+4+8+4*4;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_GETMORE>>24&255;r[t+2]=A.OP_GETMORE>>16&255;r[t+1]=A.OP_GETMORE>>8&255;r[t]=A.OP_GETMORE&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;t=t+r.write(this.ns,t,"utf8")+1;r[t-1]=0;r[t+3]=this.numberToReturn>>24&255;r[t+2]=this.numberToReturn>>16&255;r[t+1]=this.numberToReturn>>8&255;r[t]=this.numberToReturn&255;t=t+4;r[t+3]=this.cursorId.getLowBits()>>24&255;r[t+2]=this.cursorId.getLowBits()>>16&255;r[t+1]=this.cursorId.getLowBits()>>8&255;r[t]=this.cursorId.getLowBits()&255;t=t+4;r[t+3]=this.cursorId.getHighBits()>>24&255;r[t+2]=this.cursorId.getHighBits()>>16&255;r[t+1]=this.cursorId.getHighBits()>>8&255;r[t]=this.cursorId.getHighBits()&255;t=t+4;return r};var KillCursor=function(e,t,r){this.ns=t;this.requestId=a++;this.cursorIds=r};KillCursor.prototype.toBin=function(){var e=4+4+4*4+this.cursorIds.length*8;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_KILL_CURSORS>>24&255;r[t+2]=A.OP_KILL_CURSORS>>16&255;r[t+1]=A.OP_KILL_CURSORS>>8&255;r[t]=A.OP_KILL_CURSORS&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=this.cursorIds.length>>24&255;r[t+2]=this.cursorIds.length>>16&255;r[t+1]=this.cursorIds.length>>8&255;r[t]=this.cursorIds.length&255;t=t+4;for(var n=0;n>24&255;r[t+2]=this.cursorIds[n].getLowBits()>>16&255;r[t+1]=this.cursorIds[n].getLowBits()>>8&255;r[t]=this.cursorIds[n].getLowBits()&255;t=t+4;r[t+3]=this.cursorIds[n].getHighBits()>>24&255;r[t+2]=this.cursorIds[n].getHighBits()>>16&255;r[t+1]=this.cursorIds[n].getHighBits()>>8&255;r[t]=this.cursorIds[n].getHighBits()&255;t=t+4}return r};var Response=function(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.cursorId=new s(n.readInt32LE(4),n.readInt32LE(8));this.startingFrom=n.readInt32LE(12);this.numberReturned=n.readInt32LE(16);this.documents=new Array(this.numberReturned);this.cursorNotFound=(this.responseFlags&E)!==0;this.queryFailure=(this.responseFlags&m)!==0;this.shardConfigStale=(this.responseFlags&C)!==0;this.awaitCapable=(this.responseFlags&I)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false};Response.prototype.isParsed=function(){return this.parsed};Response.prototype.parse=function(e){if(this.parsed)return;e=e||{};var t=e.raw||false;var r=e.documentsReturnedIn||null;var n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;var o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;var s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;var i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;var a,A;A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};this.index=20;for(var c=0;c{"use strict";const n=r(1808);const o=r(4404);const s=r(6096);const i=r(3111).MongoError;const a=r(3111).MongoNetworkError;const A=r(3111).MongoNetworkTimeoutError;const c=r(2192).defaultAuthProviders;const l=r(557).AuthContext;const u=r(7161);const h=r(1178).makeClientMetadata;const d=u.MAX_SUPPORTED_WIRE_VERSION;const g=u.MAX_SUPPORTED_SERVER_VERSION;const p=u.MIN_SUPPORTED_WIRE_VERSION;const E=u.MIN_SUPPORTED_SERVER_VERSION;let m;function connect(e,t,r){if(typeof t==="function"){r=t;t=undefined}const n=e&&e.connectionType?e.connectionType:s;if(m==null){m=c(e.bson)}const o=e.family!==void 0?e.family:0;makeConnection(o,e,t,((t,o)=>{if(t){r(t,o);return}performInitialHandshake(new n(o,e),e,r)}))}function isModernConnectionType(e){return!(e instanceof s)}function checkSupportedServer(e,t){const r=e&&typeof e.maxWireVersion==="number"&&e.maxWireVersion>=p;const n=e&&typeof e.minWireVersion==="number"&&e.minWireVersion<=d;if(r){if(n){return null}const r=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${g})`;return new i(r)}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 ${p} (MongoDB ${E})`;return new i(o)}function performInitialHandshake(e,t,r){const callback=function(t,n){if(t&&e){e.destroy()}r(t,n)};const n=t.credentials;if(n){if(!n.mechanism.match(/DEFAULT/i)&&!m[n.mechanism]){callback(new i(`authMechanism '${n.mechanism}' not supported`));return}}const o=new l(e,n,t);prepareHandshakeDocument(o,((r,s)=>{if(r){return callback(r)}const a=Object.assign({},t);if(t.connectTimeoutMS||t.connectionTimeout){a.socketTimeout=t.connectTimeoutMS||t.connectionTimeout}s.helloOk=!!t.useUnifiedTopology;const A=(new Date).getTime();e.command("admin.$cmd",s,a,((r,a)=>{if(r){callback(r);return}const c=a.result;if(c.ok===0){callback(new i(c));return}if("isWritablePrimary"in c){c.ismaster=c.isWritablePrimary}if(t.useUnifiedTopology&&c.helloOk){e.helloOk=true}const l=checkSupportedServer(c,t);if(l){callback(l);return}if(!isModernConnectionType(e)){if(c.compression){const r=s.compression.filter((e=>c.compression.indexOf(e)!==-1));if(r.length){e.agreedCompressor=r[0]}if(t.compression&&t.compression.zlibCompressionLevel){e.zlibCompressionLevel=t.compression.zlibCompressionLevel}}}e.ismaster=c;e.lastIsMasterMS=(new Date).getTime()-A;if(!c.arbiterOnly&&n){Object.assign(o,{response:c});const t=n.resolveAuthMechanism(c);const r=m[t.mechanism];r.auth(o,(t=>{if(t)return callback(t);callback(undefined,e)}));return}callback(undefined,e)}))}))}function prepareHandshakeDocument(e,t){const r=e.options;const n=e.connection.serverApi;const o=r.compression&&r.compression.compressors?r.compression.compressors:[];const s={[n?"hello":"ismaster"]:true,client:r.metadata||h(r),compression:o};const a=e.credentials;if(a){if(a.mechanism.match(/DEFAULT/i)&&a.username){Object.assign(s,{saslSupportedMechs:`${a.source}.${a.username}`});m["scram-sha-256"].prepare(s,e,t);return}const r=m[a.mechanism];if(r==null){return t(new i(`No AuthProvider for ${a.mechanism} defined.`))}r.prepare(s,e,t);return}t(undefined,s)}const C=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function parseConnectOptions(e,t){const r=typeof t.host==="string"?t.host:"localhost";if(r.indexOf("/")!==-1){return{path:r}}const n={family:e,host:r,port:typeof t.port==="number"?t.port:27017,rejectUnauthorized:false};return n}function parseSslOptions(e,t){const r=parseConnectOptions(e,t);for(const e in t){if(t[e]!=null&&C.indexOf(e)!==-1){r[e]=t[e]}}if(t.checkServerIdentity===false){r.checkServerIdentity=function(){return undefined}}else if(typeof t.checkServerIdentity==="function"){r.checkServerIdentity=t.checkServerIdentity}if(r.servername==null&&!n.isIP(r.host)){r.servername=r.host}return r}const I=new Set(["error","close","timeout","parseError"]);function makeConnection(e,t,r,s){const i=typeof t.ssl==="boolean"?t.ssl:false;const a=typeof t.keepAlive==="boolean"?t.keepAlive:true;let A=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;const c=typeof t.noDelay==="boolean"?t.noDelay:true;const l=typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:3e4;const u=typeof t.socketTimeoutMS==="number"?t.socketTimeoutMS:typeof t.socketTimeout==="number"?t.socketTimeout:0;const h=typeof t.rejectUnauthorized==="boolean"?t.rejectUnauthorized:true;if(A>u){A=Math.round(u/2)}let d;const callback=function(e,t){if(e&&d){d.destroy()}s(e,t)};try{if(i){d=o.connect(parseSslOptions(e,t));if(typeof d.disableRenegotiation==="function"){d.disableRenegotiation()}}else{d=n.createConnection(parseConnectOptions(e,t))}}catch(e){return callback(e)}d.setKeepAlive(a,A);d.setTimeout(l);d.setNoDelay(c);const g=i?"secureConnect":"connect";let p;function errorHandler(e){return t=>{I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}d.removeListener(g,connectHandler);callback(connectionFailureError(e,t))}}function connectHandler(){I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}if(d.authorizationError&&h){return callback(d.authorizationError)}d.setTimeout(u);callback(null,d)}I.forEach((e=>d.once(e,errorHandler(e))));if(r){p=errorHandler("cancel");r.once("cancel",p)}d.once(g,connectHandler)}function connectionFailureError(e,t){switch(e){case"error":return new a(t);case"timeout":return new A(`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.exports=connect},6096:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(6113);const s=r(7746).debugOptions;const i=r(7272).parseHeader;const a=r(7793).decompress;const A=r(9814).Response;const c=r(8988).BinMsg;const l=r(3111).MongoNetworkError;const u=r(3111).MongoNetworkTimeoutError;const h=r(3111).MongoError;const d=r(104);const g=r(7272).opcodes.OP_COMPRESSED;const p=r(7272).opcodes.OP_MSG;const E=r(7272).MESSAGE_HEADER_SIZE;const m=r(1867).Buffer;const C=r(9814).Query;const I=r(2337);let y=0;const B=1024*1024*16*4;const Q=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"];let b=undefined;let w=false;let S={};class Connection extends n{constructor(e,t){super();t=t||{};if(!t.bson){throw new TypeError("must pass in valid bson parser")}this.id=y++;this.options=t;this.logger=d("Connection",t);this.bson=t.bson;this.tag=t.tag;this.maxBsonMessageSize=t.maxBsonMessageSize||B;this.helloOk=undefined;this.port=t.port||27017;this.host=t.host||"localhost";this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.keepAlive=typeof t.keepAlive==="boolean"?t.keepAlive:true;this.keepAliveInitialDelay=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;this.connectionTimeout=typeof t.connectionTimeout==="number"?t.connectionTimeout:3e4;if(this.keepAliveInitialDelay>this.socketTimeout){this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)}if(this.logger.isDebug()){this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(Q,t))}]`)}this.responseOptions={promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false};this.flushing=false;this.queue=[];this.writeStream=null;this.destroyed=false;this.timedOut=false;const r=o.createHash("sha1");r.update(this.address);this.hashedName=r.digest("hex");this.workItems=[];this.socket=e;this.socket.once("error",errorHandler(this));this.socket.once("timeout",timeoutHandler(this));this.socket.once("close",closeHandler(this));this.socket.on("data",dataHandler(this));if(w){addConnection(this.id,this)}}setSocketTimeout(e){if(this.socket){this.socket.setTimeout(e)}}resetSocketTimeout(){if(this.socket){this.socket.setTimeout(this.socketTimeout)}}static enableConnectionAccounting(e){if(e){b=e}w=true;S={}}static disableConnectionAccounting(){w=false;b=undefined}static connections(){return S}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",(()=>this.socket.unref()));return}this.socket.unref()}flush(e){while(this.workItems.length>0){const t=this.workItems.shift();if(t.cb){t.cb(e)}}}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(w){deleteConnection(this.id)}if(this.socket==null){this.destroyed=true;return}if(e.force||this.timedOut){this.socket.destroy();this.destroyed=true;if(typeof t==="function")t(null,null);return}this.socket.end((e=>{this.destroyed=true;if(typeof t==="function")t(e,null)}))}write(e){if(this.logger.isDebug()){if(!Array.isArray(e)){this.logger.debug(`writing buffer [ ${e.length} ] to ${this.address}`)}else{for(let t=0;t{};function _callback(e,t){n(e,t);n=noop}function errorHandler(e){o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);if(e==null){e=new h(`runCommand failed for connection to '${o.address}'`)}o.on("error",noop);_callback(e)}function messageHandler(e){if(e.responseTo!==a.requestId){return}o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);e.parse({promoteValues:true});const t=e.documents[0];if(t.ok===0||t.$err||t.errmsg||t.code){_callback(new h(t));return}_callback(undefined,new I(t,this,e))}o.setSocketTimeout(s);v.forEach((e=>o.once(e,errorHandler)));o.on("message",messageHandler);o.write(a.toBin())}}const v=["error","close","timeout","parseError"];function deleteConnection(e){delete S[e];if(b){b.deleteConnection(e)}}function addConnection(e,t){S[e]=t;if(b){b.addConnection(e,t)}}function errorHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`)}e.emit("error",new l(t),e)}}function timeoutHandler(e){return function(){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] timed out`)}e.timedOut=true;e.emit("timeout",new u(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}function closeHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} with for [${e.address}] closed`)}if(!t){e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}}function processMessage(e,t){const r=i(t);if(r.opCode!==g){const n=r.opCode===p?c:A;e.emit("message",new n(e.bson,t,r,t.slice(E),e.responseOptions),e);return}r.fromCompressed=true;let n=E;r.opCode=t.readInt32LE(n);n+=4;r.length=t.readInt32LE(n);n+=4;const o=t[n];n++;a(o,t.slice(n),((n,o)=>{if(n){e.emit("error",n);return}if(o.length!==r.length){e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));return}const s=r.opCode===p?c:A;e.emit("message",new s(e.bson,t,r,o,e.responseOptions),e)}))}function dataHandler(e){return function(t){while(t.length>0){if(e.bytesRead>0&&e.sizeOfMessage>0){const r=e.sizeOfMessage-e.bytesRead;if(r>t.length){t.copy(e.buffer,e.bytesRead);e.bytesRead=e.bytesRead+t.length;t=m.alloc(0)}else{t.copy(e.buffer,e.bytesRead,0,r);t=t.slice(r);const n=e.buffer;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;processMessage(e,n)}}else{if(e.stubBuffer!=null&&e.stubBuffer.length>0){if(e.stubBuffer.length+t.length>4){const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=r;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null}else{const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=m.alloc(0)}}else{if(t.length>4){const r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",t,e);return}if(r>4&&rt.length){e.buffer=m.alloc(r);t.copy(e.buffer,0);e.bytesRead=t.length;e.sizeOfMessage=r;e.stubBuffer=null;t=m.alloc(0)}else if(r>4&&re.maxBsonMessageSize){const n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=m.alloc(0)}else{const n=t.slice(0,r);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=t.slice(r);processMessage(e,n)}}else{e.stubBuffer=m.alloc(t.length);t.copy(e.stubBuffer,0);t=m.alloc(0)}}}}}}e.exports=Connection},104:(e,t,r)=>{"use strict";var n=r(3837).format,o=r(3111).MongoError;var s={};var i={};var a=null;var A=process.pid;var c=null;var Logger=function(e,t){if(!(this instanceof Logger))return new Logger(e,t);t=t||{};this.className=e;if(t.logger){c=t.logger}else if(c==null){c=console.log}if(t.loggerLevel){a=t.loggerLevel||"error"}if(i[this.className]==null)s[this.className]=true};Logger.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","DEBUG",this.className,A,r,e);var a={type:"debug",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}};Logger.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","WARN",this.className,A,r,e);var a={type:"warn",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","INFO",this.className,A,r,e);var a={type:"info",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","ERROR",this.className,A,r,e);var a={type:"error",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.isInfo=function(){return a==="info"||a==="debug"},Logger.prototype.isError=function(){return a==="error"||a==="info"||a==="debug"},Logger.prototype.isWarn=function(){return a==="error"||a==="warn"||a==="info"||a==="debug"},Logger.prototype.isDebug=function(){return a==="debug"};Logger.reset=function(){a="error";i={}};Logger.currentLogger=function(){return c};Logger.setCurrentLogger=function(e){if(typeof e!=="function")throw new o("current logger must be a function");c=e};Logger.filter=function(e,t){if(e==="class"&&Array.isArray(t)){i={};t.forEach((function(e){i[e]=true}))}};Logger.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn"){throw new Error(n("%s is an illegal logging level",e))}a=e};e.exports=Logger},8988:(e,t,r)=>{"use strict";const n=r(1867).Buffer;const o=r(7272).opcodes;const s=r(7272).databaseNamespace;const i=r(4485);const a=r(3111).MongoError;let A=0;const c=1;const l=2;const u=1<<16;class Msg{constructor(e,t,r,n){if(r==null)throw new Error("query must be specified for query");this.bson=e;this.ns=t;this.command=r;this.command.$db=s(t);if(n.readPreference&&n.readPreference.mode!==i.PRIMARY){this.command.$readPreference=n.readPreference.toJSON()}this.options=n||{};this.requestId=n.requestId?n.requestId:Msg.getRequestId();this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checksumPresent=false;this.moreToCome=n.moreToCome||false;this.exhaustAllowed=typeof n.exhaustAllowed==="boolean"?n.exhaustAllowed:false}toBin(){const e=[];let t=0;if(this.checksumPresent){t|=c}if(this.moreToCome){t|=l}if(this.exhaustAllowed){t|=u}const r=n.alloc(4*4+4);e.push(r);let s=r.length;const i=this.command;s+=this.makeDocumentSegment(e,i);r.writeInt32LE(s,0);r.writeInt32LE(this.requestId,4);r.writeInt32LE(0,8);r.writeInt32LE(o.OP_MSG,12);r.writeUInt32LE(t,16);return e}makeDocumentSegment(e,t){const r=n.alloc(1);r[0]=0;const o=this.serializeBson(t);e.push(r);e.push(o);return r.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}Msg.getRequestId=function(){A=A+1&2147483647;return A};class BinMsg{constructor(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.checksumPresent=(this.responseFlags&c)!==0;this.moreToCome=(this.responseFlags&l)!==0;this.exhaustAllowed=(this.responseFlags&u)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false;this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{};this.index=4;const t=e.raw||false;const r=e.documentsReturnedIn||null;const n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;const o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;const s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;const i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;const A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};while(this.index{"use strict";const n=r(3837).inherits;const o=r(2361).EventEmitter;const s=r(3111).MongoError;const i=r(3111).MongoTimeoutError;const a=r(3111).MongoWriteConcernError;const A=r(104);const c=r(3837).format;const l=r(8988).Msg;const u=r(2337);const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(9815);const I=r(1867).Buffer;const y=r(6573);const B=r(5474).updateSessionFromResponse;const Q=r(1178).eachAsync;const b=r(1178).makeStateMachine;const w=r(1371).now;const S="disconnected";const v="connecting";const R="connected";const k="draining";const D="destroying";const N="destroyed";const T=b({[S]:[v,k,S],[v]:[v,R,k,S],[R]:[R,S,k],[k]:[k,D,N],[D]:[D,N],[N]:[N]});const O=new Set(["error","close","timeout","parseError","connect","message"]);var _=0;var Pool=function(e,t){o.call(this);this.topology=e;this.s={state:S,cancellationToken:new o};this.s.cancellationToken.setMaxListeners(Infinity);this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:true,keepAliveInitialDelay:12e4,noDelay:true,ssl:false,checkServerIdentity:true,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:false,promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false,reconnect:true,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:false,legacyCompatMode:true},t);this.id=_++;this.retriesLeft=this.options.reconnectTries;this.reconnectId=null;this.reconnectError=null;if(!t.bson||t.bson&&(typeof t.bson.serialize!=="function"||typeof t.bson.deserialize!=="function")){throw new Error("must pass in valid bson parser")}this.logger=A("Pool",t);this.availableConnections=[];this.inUseConnections=[];this.connectingConnections=0;this.executing=false;this.queue=[];this.numberOfConsecutiveTimeouts=0;this.connectionIndex=0;const r=this;this._messageHandler=messageHandler(this);this._connectionCloseHandler=function(e){const t=this;connectionFailureHandler(r,"close",e,t)};this._connectionErrorHandler=function(e){const t=this;connectionFailureHandler(r,"error",e,t)};this._connectionTimeoutHandler=function(e){const t=this;connectionFailureHandler(r,"timeout",e,t)};this._connectionParseErrorHandler=function(e){const t=this;connectionFailureHandler(r,"parseError",e,t)}};n(Pool,o);Object.defineProperty(Pool.prototype,"size",{enumerable:true,get:function(){return this.options.size}});Object.defineProperty(Pool.prototype,"minSize",{enumerable:true,get:function(){return this.options.minSize}});Object.defineProperty(Pool.prototype,"connectionTimeout",{enumerable:true,get:function(){return this.options.connectionTimeout}});Object.defineProperty(Pool.prototype,"socketTimeout",{enumerable:true,get:function(){return this.options.socketTimeout}});Object.defineProperty(Pool.prototype,"state",{enumerable:true,get:function(){return this.s.state}});function resetPoolState(e){e.inUseConnections=[];e.availableConnections=[];e.connectingConnections=0;e.executing=false;e.numberOfConsecutiveTimeouts=0;e.connectionIndex=0;e.retriesLeft=e.options.reconnectTries;e.reconnectId=null}function connectionFailureHandler(e,t,r,n){if(n){if(n._connectionFailHandled){return}n._connectionFailHandled=true;n.destroy();removeConnection(e,n);n.flush(r)}if(t==="timeout"){e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1;if(e.numberOfConsecutiveTimeouts>e.options.reconnectTries){e.numberOfConsecutiveTimeouts=0;e.destroy(true);return e.emit("close",e)}}if(e.socketCount()===0){if(e.state!==N&&e.state!==D&&e.state!==k){if(e.options.reconnect){T(e,S)}}t=t==="error"?"close":t;e.emit(t,r)}if(!e.reconnectId&&e.options.reconnect){e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e),e.options.reconnectInterval)}const o=totalConnectionCount(e);if(o{if(r==null){e.reconnectId=null;e.retriesLeft=e.options.reconnectTries;e.emit("reconnect",e)}if(typeof t==="function"){t(r,n)}}))}}function moveConnectionBetween(e,t,r){var n=t.indexOf(e);if(n!==-1){t.splice(n,1);r.push(e)}}function messageHandler(e){return function(t,r){var n=null;for(var o=0;o{if(t){if(typeof e==="function"){this.destroy();e(t);return}if(this.state===v){this.emit("error",t)}this.destroy();return}T(this,R);if(this.minSize){for(let e=0;e{for(const t of O){e.removeAllListeners(t)}e.on("error",(()=>{}));e.destroy(r,t)}),(t=>{if(t){if(typeof n==="function")n(t,null);return}resetPoolState(e);e.queue=[];T(e,N);if(typeof n==="function")n(null,null)}))}Pool.prototype.destroy=function(e,t){var r=this;if(typeof e==="function"){t=e;e=false}if(this.state===N||r.state===D){if(typeof t==="function")t(null,null);return}T(this,k);if(e){var n=r.availableConnections.concat(r.inUseConnections);while(r.queue.length>0){var o=r.queue.shift();if(typeof o.cb==="function"){o.cb(new s("Pool was force destroyed"))}}return destroy(r,n,{force:true},t)}if(this.reconnectId){clearTimeout(this.reconnectId)}function checkStatus(){if(r.state===N||r.state===D){if(typeof t==="function"){t()}return}flushMonitoringOperations(r.queue);if(r.queue.length===0){var e=r.availableConnections.concat(r.inUseConnections);for(var n=0;n0){return setTimeout(checkStatus,1)}}destroy(r,e,{force:false},t)}else{_execute(r)();setTimeout(checkStatus,1)}}checkStatus()};Pool.prototype.reset=function(e){if(this.s.state!==R){if(typeof e==="function"){e(new s("pool is not connected, reset aborted"))}return}this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);Q(t,((e,t)=>{for(const t of O){e.removeAllListeners(t)}e.destroy({force:true},t)}),(t=>{if(t){if(typeof e==="function"){e(t,null);return}}resetPoolState(this);createConnection(this,(()=>{if(typeof e==="function"){e(null,null)}}))}))};function serializeCommand(e,t,r){const n=t.toBin();const o=!!e.options.agreedCompressor;if(!o||!canCompress(t)){return r(null,n)}const s=I.concat(n);const i=s.slice(h);const a=s.readInt32LE(12);p(e,i,(function(n,o){if(n)return r(n,null);const s=I.alloc(h);s.writeInt32LE(h+d+o.length,0);s.writeInt32LE(t.requestId,4);s.writeInt32LE(0,8);s.writeInt32LE(g.OP_COMPRESSED,12);const A=I.alloc(d);A.writeInt32LE(a,0);A.writeInt32LE(i.length,4);A.writeUInt8(E[e.options.agreedCompressor],8);return r(null,[s,A,o])}))}Pool.prototype.write=function(e,t,r){var n=this;if(typeof t==="function"){r=t}t=t||{};if(!(typeof r==="function")&&!t.noResponse){throw new s("write method must provide a callback")}if(this.state===N||this.state===D){r(new s("pool destroyed"));return}if(this.state===k){r(new s("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r==="function"){var o=r;r=process.domain.bind((function(){var e=new Array(arguments.length);for(var t=0;t{if(t){n.emit("commandFailed",new C.CommandFailedEvent(this,e,t,i.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){n.emit("commandFailed",new C.CommandFailedEvent(this,e,o.result,i.started))}else{n.emit("commandSucceeded",new C.CommandSucceededEvent(this,e,o,i.started))}}if(typeof r==="function")r(t,o)}}serializeCommand(n,e,((e,r)=>{if(e)throw e;i.buffer=r;if(t.monitoring){n.queue.unshift(i)}else{n.queue.push(i)}if(!n.executing){process.nextTick((function(){_execute(n)()}))}}))};function canCompress(e){const t=e instanceof l?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function remove(e,t){for(var r=0;r{e.connectingConnections--;if(r){if(e.logger.isDebug()){e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`)}if(!e.reconnectId&&e.options.reconnect){if(e.state===v&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e,t),e.options.reconnectInterval);return}if(typeof t==="function"){t(r)}return}if(e.state===N||e.state===D){if(typeof t==="function"){t(new s("Pool was destroyed after connection creation"))}n.destroy();return}n.on("error",e._connectionErrorHandler);n.on("close",e._connectionCloseHandler);n.on("timeout",e._connectionTimeoutHandler);n.on("parseError",e._connectionParseErrorHandler);n.on("message",e._messageHandler);e.availableConnections.push(n);if(typeof t==="function"){t(null,n)}_execute(e)()}))}function flushMonitoringOperations(e){for(var t=0;t0){e.executing=false;return}while(true){const i=totalConnectionCount(e);if(e.availableConnections.length===0){flushMonitoringOperations(e.queue);if(i0){createConnection(e)}break}if(e.queue.length===0){break}var t=null;const a=e.availableConnections.filter((e=>e.workItems.length===0));if(a.length===0){t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]}else{t=a[e.connectionIndex++%a.length]}if(!t.isConnected()){removeConnection(e,t);flushMonitoringOperations(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=false;for(let r=0;r0){createConnection(e)}setTimeout((()=>_execute(e)()),10);break}}if(i0){e.queue.unshift(r);createConnection(e);break}}var o=r.buffer;if(r.monitoring){moveConnectionBetween(t,e.availableConnections,e.inUseConnections)}if(!r.noResponse){t.workItems.push(r)}if(!r.immediateRelease&&typeof r.socketTimeout==="number"){t.setSocketTimeout(r.socketTimeout)}var s=true;if(Array.isArray(o)){for(let e=0;e{"use strict";const n=r(1371).parsePackageVersion;const o=r(3111).MongoError;const s=r(3182)(require);function debugOptions(e,t){const r={};e.forEach((function(e){r[e]=t[e]}));return r}function retrieveBSON(){const e=r(4044);e.native=false;const t=s("bson-ext");const i=n(s("bson-ext/package.json")||{version:"0.0.0"});if(t){if(i.major>=4){throw new o("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver")}t.native=true;return t}return e}function noSnappyWarning(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}const i=Symbol("kPkgVersion");function retrieveSnappy(){const e=s("snappy");if(!e){return{compress:noSnappyWarning,uncompress:noSnappyWarning,compressSync:noSnappyWarning,uncompressSync:noSnappyWarning}}const t=s("snappy/package.json")||{version:"0.0.0"};const r=n(t);e[i]=r;if(r.major>=7){const t=e.compress;const r=e.uncompress;e.compress=(e,r)=>{t(e).then((e=>r(undefined,e))).catch((e=>r(e)))};e.uncompress=(e,t)=>{r(e).then((e=>t(undefined,e))).catch((e=>t(e)))}}return e}e.exports={PKG_VERSION:i,debugOptions:debugOptions,retrieveBSON:retrieveBSON,retrieveSnappy:retrieveSnappy}},4847:(e,t,r)=>{"use strict";const n=r(104);const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(1178).collationNotSupported;const A=r(4485);const c=r(1178).isUnifiedTopology;const l=r(2548);const u=r(2781).Readable;const h=r(1371).SUPPORTS;const d=r(1371).MongoDBNamespace;const g=r(1371).mergeOptions;const p=r(1018).OperationBase;const E=o();const m=E.Long;const C={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function handleCallback(e,t,r){try{e(t,r)}catch(t){process.nextTick((function(){throw t}))}}class CoreCursor extends u{constructor(e,t,r,o){super({objectMode:true});o=o||{};if(t instanceof p){this.operation=t;t=this.operation.ns.toString();o=this.operation.options;r=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=d.fromString(t);this.cmd=r;this.options=o;this.topology=e;this.cursorState={cursorId:null,cmd:r,documents:o.documents||[],cursorIndex:0,dead:false,killed:false,init:false,notified:false,limit:o.limit||r.limit||0,skip:o.skip||r.skip||0,batchSize:o.batchSize||r.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||r&&r.raw};if(typeof o.session==="object"){this.cursorState.session=o.session}const s=e.s.options;if(typeof s.promoteLongs==="boolean"){this.cursorState.promoteLongs=s.promoteLongs}else if(typeof o.promoteLongs==="boolean"){this.cursorState.promoteLongs=o.promoteLongs}if(typeof s.promoteValues==="boolean"){this.cursorState.promoteValues=s.promoteValues}else if(typeof o.promoteValues==="boolean"){this.cursorState.promoteValues=o.promoteValues}if(typeof s.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=s.promoteBuffers}else if(typeof o.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=o.promoteBuffers}if(typeof s.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=s.bsonRegExp}else if(typeof o.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=o.bsonRegExp}if(s.reconnect){this.cursorState.reconnect=s.reconnect}this.logger=n("Cursor",s);if(typeof r==="number"){this.cursorState.cursorId=m.fromNumber(r);this.cursorState.lastCursorId=this.cursorState.cursorId}else if(r instanceof m){this.cursorState.cursorId=r;this.cursorState.lastCursorId=r}if(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){nextFunction(this,e)}clone(){const e=g({},this.options);delete e.session;return this.topology.cursor(this.ns,this.cmd,e)}isDead(){return this.cursorState.dead===true}isKilled(){return this.cursorState.killed===true}isNotified(){return this.cursorState.notified===true}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex;const r=e0&&this.cursorState.currentLimit+n.length>this.cursorState.limit){n=n.slice(0,this.cursorState.limit-this.cursorState.currentLimit);this.kill()}this.cursorState.currentLimit=this.cursorState.currentLimit+n.length;this.cursorState.cursorIndex=this.cursorState.cursorIndex+n.length;return n}kill(e){this.cursorState.dead=true;this.cursorState.killed=true;this.cursorState.documents=[];if(this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===false){if(e)e(null,null);return}this.server.killCursors(this.ns,this.cursorState,e)}rewind(){if(this.cursorState.init){if(!this.cursorState.dead){this.kill()}this.cursorState.currentLimit=0;this.cursorState.init=false;this.cursorState.dead=false;this.cursorState.killed=false;this.cursorState.notified=false;this.cursorState.documents=[];this.cursorState.cursorId=null;this.cursorState.cursorIndex=0}}_read(){if(this.s&&this.s.state===C.CLOSED||this.isDead()){return this.push(null)}this._next(((e,t)=>{if(e){if(this.listeners("error")&&this.listeners("error").length>0){this.emit("error",e)}if(!this.isDead())this.close();this.emit("end");return this.emit("finish")}if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform==="function"&&t!=null){return this.push(this.cursorState.streamOptions.transform(t))}this.push(t);if(t===null&&this.isDead()){this.once("end",(()=>{this.close();this.emit("finish")}))}}))}_endSession(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};const r=this.cursorState.session;if(r&&(e.force||r.owner===this)){this.cursorState.session=undefined;if(this.operation){this.operation.clearSession()}r.endSession(t);return true}if(t){t()}return false}_getMore(e){if(this.logger.isDebug()){this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`)}let t=this.cursorState.batchSize;if(this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit){t=this.cursorState.limit-this.cursorState.currentLimit}const r=this.cursorState;this.server.getMore(this.ns,r,t,this.options,((t,n,o)=>{if(t||r.cursorId&&r.cursorId.isZero()){this._endSession()}e(t,n,o)}))}_initializeCursor(e){const t=this;if(c(t.topology)&&t.topology.shouldCheckForSessionSupport()){t.topology.selectServer(A.primaryPreferred,(t=>{if(t){e(t);return}this._initializeCursor(e)}));return}function done(r,n){const o=t.cursorState;if(r||o.cursorId&&o.cursorId.isZero()){t._endSession()}if(o.documents.length===0&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData){return setCursorNotified(t,e)}e(r,n)}const queryCallback=(e,r)=>{if(e){return done(e)}const n=r.message;if(Array.isArray(n.documents)&&n.documents.length===1){const e=n.documents[0];if(n.queryFailure){return done(new s(e),null)}if(!t.cmd.find||t.cmd.find&&t.cmd.virtual===false){if(e.$err||e.errmsg){return done(new s(e),null)}if(e.cursor!=null&&typeof e.cursor!=="string"){const r=e.cursor.id;if(e.cursor.ns){t.ns=e.cursor.ns}t.cursorState.cursorId=typeof r==="number"?m.fromNumber(r):r;t.cursorState.lastCursorId=t.cursorState.cursorId;t.cursorState.operationTime=e.operationTime;if(Array.isArray(e.cursor.firstBatch)){t.cursorState.documents=e.cursor.firstBatch}return done(null,n)}}}const o=n.cursorId||0;t.cursorState.cursorId=o instanceof m?o:m.fromNumber(o);t.cursorState.documents=n.documents;t.cursorState.lastCursorId=n.cursorId;if(t.cursorState.transforms&&typeof t.cursorState.transforms.query==="function"){t.cursorState.documents=t.cursorState.transforms.query(n)}done(null,n)};if(t.operation){if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}l(t.topology,t.operation,((e,r)=>{if(e){done(e);return}t.server=t.operation.server;t.cursorState.init=true;if(t.cursorState.cursorId!=null){return done()}queryCallback(e,r)}));return}const r={};if(t.cursorState.session){r.session=t.cursorState.session}if(t.operation){r.readPreference=t.operation.readPreference}else if(t.options.readPreference){r.readPreference=t.options.readPreference}return t.topology.selectServer(r,((r,n)=>{if(r){const n=t.disconnectHandler;if(n!=null){return n.addObjectAndMethod("cursor",t,"next",[e],e)}return e(r)}t.server=n;t.cursorState.init=true;if(a(t.server,t.cmd)){return e(new s(`server ${t.server.name} does not support collation`))}if(t.cursorState.cursorId!=null){return done()}if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}if(t.cmd.find!=null){n.query(t.ns,t.cmd,t.cursorState,t.options,queryCallback);return}const o=Object.assign({session:t.cursorState.session},t.options);n.command(t.ns,t.cmd,o,queryCallback)}))}}if(h.ASYNC_ITERATOR){CoreCursor.prototype[Symbol.asyncIterator]=r(1749).asyncIterator}function isConnectionDead(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=true;const r=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);_setCursorNotifiedImpl(e,(()=>t(r)));return true}return false}function isCursorDeadButNotkilled(e,t){if(e.cursorState.dead&&!e.cursorState.killed){e.cursorState.killed=true;setCursorNotified(e,t);return true}return false}function isCursorDeadAndKilled(e,t){if(e.cursorState.dead&&e.cursorState.killed){handleCallback(t,new s("cursor is dead"));return true}return false}function isCursorKilled(e,t){if(e.cursorState.killed){setCursorNotified(e,t);return true}return false}function setCursorDeadAndNotified(e,t){e.cursorState.dead=true;setCursorNotified(e,t)}function setCursorNotified(e,t){_setCursorNotifiedImpl(e,(()=>handleCallback(t,null,null)))}function _setCursorNotifiedImpl(e,t){e.cursorState.notified=true;e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.cursorState.session){e._endSession(t);return}return t()}function nextFunction(e,t){if(e.cursorState.notified){return t(new Error("cursor is exhausted"))}if(isCursorKilled(e,t))return;if(isCursorDeadButNotkilled(e,t))return;if(isCursorDeadAndKilled(e,t))return;if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect){return t(new s("no connection available"))}if(e.disconnectHandler!=null){if(e.topology.isDestroyed()){return t(new s("Topology was destroyed"))}e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor(((r,n)=>{if(r||n===null){t(r,n);return}nextFunction(e,t)}));return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)))}else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!m.ZERO.equals(e.cursorState.cursorId)){e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.topology.isDestroyed())return t(new i("connection destroyed, not possible to instantiate cursor"));if(isConnectionDead(e,t))return;e._getMore((function(r,n,o){if(r){return handleCallback(t,r)}e.connection=o;if(e.cursorState.documents.length===0&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===0&&e.cmd.tailable&&!m.ZERO.equals(e.cursorState.cursorId)){return nextFunction(e,t)}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){return setCursorDeadAndNotified(e,t)}nextFunction(e,t)}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&m.ZERO.equals(e.cursorState.cursorId)){setCursorDeadAndNotified(e,t)}else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill((()=>setCursorDeadAndNotified(e,(function(){handleCallback(t,new s(r?r.$err:undefined))}))));return}if(e.cursorState.transforms&&typeof e.cursorState.transforms.doc==="function"){r=e.cursorState.transforms.doc(r)}handleCallback(t,null,r)}}e.exports={CursorState:C,CoreCursor:CoreCursor}},3111:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=Symbol("errorLabels");class MongoError extends Error{constructor(e){if(e instanceof Error){super(e.message);this.stack=e.stack}else{if(typeof e==="string"){super(e)}else{super(e.message||e.errmsg||e.$err||"n/a");if(e.errorLabels){this[o]=new Set(e.errorLabels)}for(var t in e){if(t==="errorLabels"||t==="errmsg"){continue}this[t]=e[t]}}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new MongoError(e)}hasErrorLabel(e){if(this[o]==null){return false}return this[o].has(e)}addErrorLabel(e){if(this[o]==null){this[o]=new Set}this[o].add(e)}get errorLabels(){return this[o]?Array.from(this[o]):[]}}const s=Symbol("beforeHandshake");function isNetworkErrorBeforeHandshake(e){return e[s]===true}class MongoNetworkError extends MongoError{constructor(e,t){super(e);this.name="MongoNetworkError";if(t&&typeof t.beforeHandshake==="boolean"){this[s]=t.beforeHandshake}}}class MongoNetworkTimeoutError extends MongoNetworkError{constructor(e,t){super(e,t);this.name="MongoNetworkTimeoutError"}}class MongoParseError extends MongoError{constructor(e){super(e);this.name="MongoParseError"}}class MongoTimeoutError extends MongoError{constructor(e,t){if(t&&t.error){super(t.error.message||t.error)}else{super(e)}this.name="MongoTimeoutError";if(t){this.reason=t}}}class MongoServerSelectionError extends MongoTimeoutError{constructor(e,t){super(e,t);this.name="MongoServerSelectionError"}}function makeWriteConcernResultObject(e){const t=Object.assign({},e);if(t.ok===0){t.ok=1;delete t.errmsg;delete t.code;delete t.codeName}return t}class MongoWriteConcernError extends MongoError{constructor(e,t){super(e);this.name="MongoWriteConcernError";if(t&&Array.isArray(t.errorLabels)){this[o]=new Set(t.errorLabels)}if(t!=null){this.result=makeWriteConcernResultObject(t)}}}const i=new Set([n.HostUnreachable,n.HostNotFound,n.NetworkTimeout,n.ShutdownInProgress,n.PrimarySteppedDown,n.SocketException,n.NotMaster,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary]);const a=new Set([n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMaster,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary,n.PrimarySteppedDown,n.ShutdownInProgress,n.HostNotFound,n.HostUnreachable,n.NetworkTimeout,n.SocketException,n.ExceededTimeLimit]);function isRetryableEndTransactionError(e){return e.hasErrorLabel("RetryableWriteError")}function isRetryableWriteError(e){if(e instanceof MongoWriteConcernError){return a.has(e.code)||a.has(e.result.code)}return a.has(e.code)}function isRetryableError(e){return i.has(e.code)||e instanceof MongoNetworkError||e.message.match(/not master/)||e.message.match(/node is recovering/)}const A=new Set([n.ShutdownInProgress,n.PrimarySteppedDown,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterOrSecondary]);const c=new Set([n.NotMaster,n.NotMasterNoSlaveOk,n.LegacyNotPrimary]);const l=new Set([n.InterruptedAtShutdown,n.ShutdownInProgress]);function isRecoveringError(e){if(typeof e.code==="number"){return A.has(e.code)}return/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}function isNotMasterError(e){if(typeof e.code==="number"){return c.has(e.code)}if(isRecoveringError(e)){return false}return/not master/.test(e.message)}function isNodeShuttingDownError(e){return e.code&&l.has(e.code)}function isSDAMUnrecoverableError(e){if(e instanceof MongoParseError||e==null){return true}return isRecoveringError(e)||isNotMasterError(e)}e.exports={MongoError:MongoError,MongoNetworkError:MongoNetworkError,MongoNetworkTimeoutError:MongoNetworkTimeoutError,MongoParseError:MongoParseError,MongoTimeoutError:MongoTimeoutError,MongoServerSelectionError:MongoServerSelectionError,MongoWriteConcernError:MongoWriteConcernError,isRetryableError:isRetryableError,isSDAMUnrecoverableError:isSDAMUnrecoverableError,isNodeShuttingDownError:isNodeShuttingDownError,isRetryableWriteError:isRetryableWriteError,isNetworkErrorBeforeHandshake:isNetworkErrorBeforeHandshake,isRetryableEndTransactionError:isRetryableEndTransactionError}},3994:(e,t,r)=>{"use strict";let n=r(4044);const o=r(3182)(require);const s=r(1178).retrieveEJSON();try{const e=o("bson-ext");if(e){n=e}}catch(e){}const i=Object.freeze({v1:"1"});const a=Object.keys(i).map((e=>i[e]));e.exports={ServerApiVersion:i,ValidServerApiVersions:a,MongoError:r(3111).MongoError,MongoNetworkError:r(3111).MongoNetworkError,MongoParseError:r(3111).MongoParseError,MongoTimeoutError:r(3111).MongoTimeoutError,MongoServerSelectionError:r(3111).MongoServerSelectionError,MongoWriteConcernError:r(3111).MongoWriteConcernError,Connection:r(6096),Server:r(6495),ReplSet:r(1134),Mongos:r(8175),Logger:r(104),Cursor:r(4847).CoreCursor,ReadPreference:r(4485),Sessions:r(5474),BSON:n,EJSON:s,Topology:r(4149).Topology,Query:r(9814).Query,MongoCredentials:r(2222).MongoCredentials,defaultAuthProviders:r(2192).defaultAuthProviders,MongoCR:r(4228),X509:r(7324),Plain:r(8728),GSSAPI:r(2640),ScramSHA1:r(864).ScramSHA1,ScramSHA256:r(864).ScramSHA256,parseConnectionString:r(8767)}},2291:e=>{"use strict";const t="closing";const r="closed";const n="connecting";const o="connected";const s={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};const i={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function serverType(e){let t=e.s.description||e.s.serverDescription;if(t.topologyType===s.Single)return t.servers[0].type;return t.type}const a={useUnifiedTopology:true,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function drainTimerQueue(e){e.forEach(clearTimeout);e.clear()}function clearAndRemoveTimerFrom(e,t){clearTimeout(e);return t.delete(e)}e.exports={STATE_CLOSING:t,STATE_CLOSED:r,STATE_CONNECTING:n,STATE_CONNECTED:o,TOPOLOGY_DEFAULTS:a,TopologyType:s,ServerType:i,serverType:serverType,drainTimerQueue:drainTimerQueue,clearAndRemoveTimerFrom:clearAndRemoveTimerFrom}},2785:e=>{"use strict";class ServerDescriptionChangedEvent{constructor(e,t,r,n){Object.assign(this,{topologyId:e,address:t,previousDescription:r,newDescription:n})}}class ServerOpeningEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class ServerClosedEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class TopologyDescriptionChangedEvent{constructor(e,t,r){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:r})}}class TopologyOpeningEvent{constructor(e){Object.assign(this,{topologyId:e})}}class TopologyClosedEvent{constructor(e){Object.assign(this,{topologyId:e})}}class ServerHeartbeatStartedEvent{constructor(e){Object.assign(this,{connectionId:e})}}class ServerHeartbeatSucceededEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,reply:t})}}class ServerHeartbeatFailedEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,failure:t})}}e.exports={ServerDescriptionChangedEvent:ServerDescriptionChangedEvent,ServerOpeningEvent:ServerOpeningEvent,ServerClosedEvent:ServerClosedEvent,TopologyDescriptionChangedEvent:TopologyDescriptionChangedEvent,TopologyOpeningEvent:TopologyOpeningEvent,TopologyClosedEvent:TopologyClosedEvent,ServerHeartbeatStartedEvent:ServerHeartbeatStartedEvent,ServerHeartbeatSucceededEvent:ServerHeartbeatSucceededEvent,ServerHeartbeatFailedEvent:ServerHeartbeatFailedEvent}},1203:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(2361);const s=r(6573);const i=r(9820).Connection;const a=r(2291);const A=r(1178).makeStateMachine;const c=r(3111).MongoNetworkError;const l=r(7746).retrieveBSON();const u=r(1371).makeInterruptableAsyncInterval;const h=r(1371).calculateDurationInMs;const d=r(1371).now;const g=r(2785);const p=g.ServerHeartbeatStartedEvent;const E=g.ServerHeartbeatSucceededEvent;const m=g.ServerHeartbeatFailedEvent;const C=Symbol("server");const I=Symbol("monitorId");const y=Symbol("connection");const B=Symbol("cancellationToken");const Q=Symbol("rttPinger");const b=Symbol("roundTripTime");const w=a.STATE_CLOSED;const S=a.STATE_CLOSING;const v="idle";const R="monitoring";const k=A({[S]:[S,v,w],[w]:[w,R],[v]:[v,R,S],[R]:[R,v,S]});const D=new Set([S,w,R]);function isInCloseState(e){return e.s.state===w||e.s.state===S}class Monitor extends o{constructor(e,t){super(t);this[C]=e;this[y]=undefined;this[B]=new o;this[B].setMaxListeners(Infinity);this[I]=null;this.s={state:w};this.address=e.description.address;this.options=Object.freeze({connectTimeoutMS:typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof t.heartbeatFrequencyMS==="number"?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof t.minHeartbeatFrequencyMS==="number"?t.minHeartbeatFrequencyMS:500,useUnifiedTopology:t.useUnifiedTopology});const r=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:false,promoteLongs:true,promoteValues:true,promoteBuffers:true,bsonRegExp:true});delete r.credentials;delete r.autoEncrypter;this.connectOptions=Object.freeze(r)}connect(){if(this.s.state!==w){return}const e=this.options.heartbeatFrequencyMS;const t=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:e,minInterval:t,immediate:true})}requestCheck(){if(D.has(this.s.state)){return}this[I].wake()}reset(){const e=this[C].description.topologyVersion;if(isInCloseState(this)||e==null){return}k(this,S);resetMonitorState(this);k(this,v);const t=this.options.heartbeatFrequencyMS;const r=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:t,minInterval:r})}close(){if(isInCloseState(this)){return}k(this,S);resetMonitorState(this);this.emit("close");k(this,w)}}function resetMonitorState(e){if(e[I]){e[I].stop();e[I]=null}if(e[Q]){e[Q].close();e[Q]=undefined}e[B].emit("cancel");if(e[I]){clearTimeout(e[I]);e[I]=undefined}if(e[y]){e[y].destroy({force:true})}}function checkServer(e,t){let r=d();e.emit("serverHeartbeatStarted",new p(e.address));function failureHandler(n){if(e[y]){e[y].destroy({force:true});e[y]=undefined}e.emit("serverHeartbeatFailed",new m(h(r),n,e.address));e.emit("resetServer",n);e.emit("resetConnectionPool");t(n)}if(e[y]!=null&&!e[y].closed){const n=e.options.connectTimeoutMS;const o=e.options.heartbeatFrequencyMS;const s=e[C].description.topologyVersion;const i=s!=null;const a=e[y].serverApi;const A=e[y].helloOk;const c={[a||A?"hello":"ismaster"]:true};if(A)c.helloOk=A;const l={socketTimeout:n};if(i){c.maxAwaitTimeMS=o;c.topologyVersion=makeTopologyVersion(s);if(n){l.socketTimeout=n+o}l.exhaustAllowed=true;if(e[Q]==null){e[Q]=new RTTPinger(e[B],e.connectOptions)}}e[y].command("admin.$cmd",c,l,((n,o)=>{if(n){failureHandler(n);return}const s=o.result;const a=e[Q];if("isWritablePrimary"in s){s.ismaster=s.isWritablePrimary}const A=i&&a?a.roundTripTime:h(r);e.emit("serverHeartbeatSucceeded",new E(A,s,e.address));if(i&&s.topologyVersion){e.emit("serverHeartbeatStarted",new p(e.address));r=d()}else{if(e[Q]){e[Q].close();e[Q]=undefined}t(undefined,s)}}));return}s(e.connectOptions,e[B],((n,o)=>{if(o&&isInCloseState(e)){o.destroy({force:true});return}if(n){e[y]=undefined;if(!(n instanceof c)){e.emit("resetConnectionPool")}failureHandler(n);return}e[y]=o;e.emit("serverHeartbeatSucceeded",new E(h(r),o.ismaster,e.address));t(undefined,o.ismaster)}))}function monitorServer(e){return t=>{k(e,R);function done(){if(!isInCloseState(e)){k(e,v)}t()}process.nextTick((()=>e.emit("monitoring",e[C])));checkServer(e,((t,r)=>{if(t){if(e[C].description.type===n.Unknown){e.emit("resetServer",t);return done()}}if(r&&r.topologyVersion){setTimeout((()=>{if(!isInCloseState(e)){e[I].wake()}}))}done()}))}}function makeTopologyVersion(e){return{processId:e.processId,counter:l.Long.fromNumber(e.counter)}}class RTTPinger{constructor(e,t){this[y]=null;this[B]=e;this[b]=0;this.closed=false;const r=t.heartbeatFrequencyMS;this[I]=setTimeout((()=>measureRoundTripTime(this,t)),r)}get roundTripTime(){return this[b]}close(){this.closed=true;clearTimeout(this[I]);this[I]=undefined;if(this[y]){this[y].destroy({force:true})}}}function measureRoundTripTime(e,t){const r=d();const n=e[B];const o=t.heartbeatFrequencyMS;if(e.closed){return}function measureAndReschedule(n){if(e.closed){n.destroy({force:true});return}if(e[y]==null){e[y]=n}e[b]=h(r);e[I]=setTimeout((()=>measureRoundTripTime(e,t)),o)}if(e[y]==null){s(t,n,((t,r)=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule(r)}));return}e[y].command("admin.$cmd",{ismaster:1},(t=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule()}))}e.exports={Monitor:Monitor}},7062:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2529).ConnectionPool;const s=r(897).CMAP_EVENT_NAMES;const i=r(3111).MongoError;const a=r(1178).relayEvents;const A=r(7746).retrieveBSON();const c=r(104);const l=r(750).ServerDescription;const u=r(750).compareTopologyVersion;const h=r(4485);const d=r(1203).Monitor;const g=r(3111).MongoNetworkError;const p=r(3111).MongoNetworkTimeoutError;const E=r(1178).collationNotSupported;const m=r(7746).debugOptions;const C=r(3111).isSDAMUnrecoverableError;const I=r(3111).isRetryableWriteError;const y=r(3111).isNodeShuttingDownError;const B=r(3111).isNetworkErrorBeforeHandshake;const Q=r(1178).maxWireVersion;const b=r(1178).makeStateMachine;const w=r(7703).extractCommand;const S=r(2291);const v=S.ServerType;const R=r(1707).isTransactionCommand;const k=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];const D=S.STATE_CLOSING;const N=S.STATE_CLOSED;const T=S.STATE_CONNECTING;const O=S.STATE_CONNECTED;const _=b({[N]:[N,T],[T]:[T,D,O,N],[O]:[O,D,N],[D]:[D,N]});const M=Symbol("monitor");class Server extends n{constructor(e,t,r){super();this.s={description:e,options:t,logger:c("Server",t),bson:t.bson||new A([A.Binary,A.Code,A.DBRef,A.Decimal128,A.Double,A.Int32,A.Long,A.Map,A.MaxKey,A.MinKey,A.ObjectId,A.BSONRegExp,A.Symbol,A.Timestamp]),state:N,credentials:t.credentials,topology:r};this.serverApi=t.serverApi;const n=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(n);a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s));this.s.pool.on("clusterTimeReceived",(e=>{this.clusterTime=e}));this[M]=new d(this,this.s.options);a(this[M],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]);this[M].on("resetConnectionPool",(()=>{this.s.pool.clear()}));this[M].on("resetServer",(e=>markServerUnknown(this,e)));this[M].on("serverHeartbeatSucceeded",(e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:calculateRoundTripTime(this.description.roundTripTime,e.duration)}));if(this.s.state===T){_(this,O);this.emit("connect",this)}}))}get description(){return this.s.description}get supportsRetryableWrites(){return supportsRetryableWrites(this)}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter){return this.s.options.autoEncrypter}return null}connect(){if(this.s.state!==N){return}_(this,T);this[M].connect()}destroy(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{force:false},e);if(this.s.state===N){if(typeof t==="function"){t()}return}_(this,D);this[M].close();this.s.pool.close(e,(e=>{_(this,N);this.emit("closed");if(typeof t==="function"){t(e)}}))}requestCheck(){this[M].requestCheck()}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}r.serverApi=this.serverApi;if(this.s.state===D||this.s.state===N){n(new i("server is closed"));return}const o=basicReadValidations(this,r);if(o){return n(o)}r=Object.assign({},r,{wireProtocolCommand:false});if(this.s.logger.isDebug()){const n=w(t);this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:m(k,r)})}] against ${this.name}`)}if(E(this,t)){n(new i(`server ${this.name} does not support collation`));return}this.s.pool.withConnection(((n,o,s)=>{if(n){markServerUnknown(this,n);return s(n)}o.command(e,t,r,makeOperationHandler(this,o,t,r,s))}),n)}query(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.query(e,t,r,n,makeOperationHandler(this,s,t,n,i))}),o)}getMore(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.getMore(e,t,r,n,makeOperationHandler(this,s,null,n,i))}),o)}killCursors(e,t,r){if(this.s.state===D||this.s.state===N){if(typeof r==="function"){r(new i("server is closed"))}return}this.s.pool.withConnection(((r,n,o)=>{if(r){markServerUnknown(this,r);return o(r)}n.killCursors(e,t,makeOperationHandler(this,n,null,undefined,o))}),r)}insert(e,t,r,n){executeWriteOperation({server:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({server:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({server:this,op:"remove",ns:e,ops:t},r,n)}}Object.defineProperty(Server.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function supportsRetryableWrites(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==v.Standalone}function calculateRoundTripTime(e,t){if(e===-1){return t}const r=.2;return r*t+(1-r)*e}function basicReadValidations(e,t){if(t.readPreference&&!(t.readPreference instanceof h)){return new i("readPreference must be an instance of ReadPreference")}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.server;const o=e.op;const s=e.ns;const a=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===D||n.s.state===N){r(new i("server is closed"));return}if(E(n,t)){r(new i(`server ${n.name} does not support collation`));return}const A=t.writeConcern&&t.writeConcern.w===0;if(A||Q(n)<5){if((o==="update"||o==="remove")&&a.find((e=>e.hint))){r(new i(`servers < 3.4 do not support hint on ${o}`));return}}n.s.pool.withConnection(((e,r,i)=>{if(e){markServerUnknown(n,e);return i(e)}r[o](s,a,t,makeOperationHandler(n,r,a,t,i))}),r)}function markServerUnknown(e,t){if(t instanceof g&&!(t instanceof p)){e[M].reset()}e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function connectionIsStale(e,t){return t.generation!==e.generation}function shouldHandleStateChangeError(e,t){const r=t.topologyVersion;const n=e.description.topologyVersion;return u(n,r)<0}function inActiveTransaction(e,t){return e&&e.inTransaction()&&!R(t)}function makeOperationHandler(e,t,r,n,o){const s=n&&n.session;return function handleOperationResult(n,i){if(n&&!connectionIsStale(e.s.pool,t)){if(n instanceof g){if(s&&!s.hasEnded){s.serverSession.isDirty=true}if(supportsRetryableWrites(e)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(!(n instanceof p)||B(n)){markServerUnknown(e,n);e.s.pool.clear()}}else{if(Q(e)<9&&I(n)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(C(n)){if(shouldHandleStateChangeError(e,n)){if(Q(e)<=7||y(n)){e.s.pool.clear()}markServerUnknown(e,n);process.nextTick((()=>e.requestCheck()))}}}}o(n,i)}}e.exports={Server:Server}},750:(e,t,r)=>{"use strict";const n=r(1178).arrayStrictEqual;const o=r(1178).tagsStrictEqual;const s=r(1178).errorStrictEqual;const i=r(2291).ServerType;const a=r(1371).now;const A=new Set([i.RSPrimary,i.Standalone,i.Mongos]);const c=new Set([i.RSPrimary,i.RSSecondary,i.Mongos,i.Standalone]);const l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];class ServerDescription{constructor(e,t,r){r=r||{};t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t);if(t.isWritablePrimary!=null){t.ismaster=t.isWritablePrimary}this.address=e;this.error=r.error;this.roundTripTime=r.roundTripTime||-1;this.lastUpdateTime=a();this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null;this.opTime=t.lastWrite?t.lastWrite.opTime:null;this.type=parseServerType(t);this.topologyVersion=r.topologyVersion||t.topologyVersion;l.forEach((e=>{if(typeof t[e]!=="undefined")this[e]=t[e]}));if(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 c.has(this.type)}get isWritable(){return A.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||compareTopologyVersion(this.topologyVersion,e.topologyVersion)===0;return e!=null&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&n(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}}function parseServerType(e){if(!e||!e.ok){return i.Unknown}if(e.isreplicaset){return i.RSGhost}if(e.msg&&e.msg==="isdbgrid"){return i.Mongos}if(e.setName){if(e.hidden){return i.RSOther}else if(e.ismaster){return i.RSPrimary}else if(e.secondary){return i.RSSecondary}else if(e.arbiterOnly){return i.RSArbiter}else{return i.RSOther}}return i.Standalone}function compareTopologyVersion(e,t){if(e==null||t==null){return-1}if(e.processId.equals(t.processId)){if(e.counter===t.counter){return 0}else if(e.counter{"use strict";const n=r(2291).ServerType;const o=r(2291).TopologyType;const s=r(4485);const i=r(3111).MongoError;const a=1e4;const A=90;function writableServerSelector(){return function(e,t){return latencyWindowReducer(e,t.filter((e=>e.isWritable)))}}function maxStalenessReducer(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0){return r}const n=e.maxStalenessSeconds;const s=(t.heartbeatFrequencyMS+a)/1e3;if(n{const s=o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}if(t.type===o.ReplicaSetNoPrimary){if(r.length===0){return r}const n=r.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return r.reduce(((r,o)=>{const s=n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}return r}function tagSetMatch(e,t){const r=Object.keys(e);const n=Object.keys(t);for(let o=0;o{if(tagSetMatch(n,t.tags))e.push(t);return e}),[]);if(o.length){return o}}return[]}function latencyWindowReducer(e,t){const r=t.reduce(((e,t)=>e===-1?t.roundTripTime:Math.min(t.roundTripTime,e)),-1);const n=r+e.localThresholdMS;return t.reduce(((e,t)=>{if(t.roundTripTime<=n&&t.roundTripTime>=r)e.push(t);return e}),[])}function primaryFilter(e){return e.type===n.RSPrimary}function secondaryFilter(e){return e.type===n.RSSecondary}function nearestFilter(e){return e.type===n.RSSecondary||e.type===n.RSPrimary}function knownFilter(e){return e.type!==n.Unknown}function readPreferenceServerSelector(e){if(!e.isValid()){throw new TypeError("Invalid read preference specified")}return function(t,r){const n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n){throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`)}if(t.type===o.Unknown){return[]}if(t.type===o.Single||t.type===o.Sharded){return latencyWindowReducer(t,r.filter(knownFilter))}const a=e.mode;if(a===s.PRIMARY){return r.filter(primaryFilter)}if(a===s.PRIMARY_PREFERRED){const e=r.filter(primaryFilter);if(e.length){return e}}const A=a===s.NEAREST?nearestFilter:secondaryFilter;const c=latencyWindowReducer(t,tagSetReducer(e,maxStalenessReducer(e,t,r.filter(A))));if(a===s.SECONDARY_PREFERRED&&c.length===0){return r.filter(primaryFilter)}return c}}e.exports={writableServerSelector:writableServerSelector,readPreferenceServerSelector:readPreferenceServerSelector}},9663:(e,t,r)=>{"use strict";var n;const o=r(104);const s=r(2361).EventEmitter;const i=r(7578);function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}class SrvPollingEvent{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map((e=>`${e.name}:${e.port}`)))}}class SrvPoller extends s{constructor(e){super();if(!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=o("srvPoller",e);this.haMode=false;this.generation=0;this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){if(!this._timeout){this.schedule()}}stop(){if(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=false;this.schedule();this.emit("srvRecordDiscovery",new SrvPollingEvent(e))}failure(e,t){this.logger.warn(e,t);this.haMode=true;this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,((t,r)=>{if(e!==this.generation){return}if(t){this.failure("DNS error",t);return}const n=[];r.forEach((e=>{if(matchesParentDomain(e.name,this.srvHost)){n.push(e)}else{this.parentDomainMismatch(e)}}));if(!n.length){this.failure("No valid addresses found at host");return}this.success(n)}))}}n=SrvPollingEvent;e.exports.D=SrvPoller},4149:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(750).ServerDescription;const i=r(2291).ServerType;const a=r(7962).TopologyDescription;const A=r(2291).TopologyType;const c=r(2785);const l=r(7062).Server;const u=r(1178).relayEvents;const h=r(4485);const d=r(4847).CoreCursor;const g=r(3837).deprecate;const p=r(7746).retrieveBSON();const E=r(2306).createCompressionInfo;const m=r(5474).ClientSession;const C=r(3111).MongoError;const I=r(3111).MongoServerSelectionError;const y=r(2306).resolveClusterTime;const B=r(9663).D;const Q=r(2306).getMMAPError;const b=r(1178).makeStateMachine;const w=r(1178).eachAsync;const S=r(1371).emitDeprecationWarning;const v=r(5474).ServerSessionPool;const R=r(1178).makeClientMetadata;const k=r(897).CMAP_EVENT_NAMES;const D=r(750).compareTopologyVersion;const N=r(1371).emitWarning;const T=r(2291);const O=T.drainTimerQueue;const _=T.clearAndRemoveTimerFrom;const M=r(4547);const L=M.readPreferenceServerSelector;const F=M.writableServerSelector;let U=0;const P=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(k);const G=["connect","descriptionReceived","close","ended"];const Y=T.STATE_CLOSING;const V=T.STATE_CLOSED;const W=T.STATE_CONNECTING;const J=T.STATE_CONNECTED;const q=b({[V]:[V,W],[W]:[W,Y,J,V],[J]:[J,Y,V],[Y]:[Y,V]});const j=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]);const z=Symbol("cancelled");const $=Symbol("waitQueue");class Topology extends o{constructor(e,t){super();if(typeof t==="undefined"&&typeof e!=="string"){t=e;e=[];if(t.host){e.push({host:t.host,port:t.port})}}e=e||[];if(typeof e==="string"){e=parseStringSeedlist(e)}t=Object.assign({},T.TOPOLOGY_DEFAULTS,t);t=Object.freeze(Object.assign(t,{metadata:R(t),compression:{compressors:E(t)}}));j.forEach((e=>{if(t[e]){S(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}));const r=topologyTypeFromSeedlist(e,t);const o=U++;const i=e.reduce(((e,t)=>{if(t.domain_socket)t.host=t.domain_socket;const r=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;e.set(r,new s(r));return e}),new Map);this[$]=new n;this.s={id:o,options:t,seedlist:e,state:V,description:new a(r,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new p([p.Binary,p.Code,p.DBRef,p.Decimal128,p.Double,p.Int32,p.Long,p.Map,p.MaxKey,p.MinKey,p.ObjectId,p.BSONRegExp,p.Symbol,p.Timestamp]),servers:new Map,sessionPool:new v(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set};this.serverApi=t.serverApi;if(t.srvHost){this.s.srvPoller=t.srvPoller||new B({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel});this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type;const r=e.newDescription.type;if(t!==A.Sharded&&r===A.Sharded){this.s.handleSrvPolling=srvPollingHandler(this);this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling);this.s.srvPoller.start()}};this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)}this.setMaxListeners(Infinity)}get description(){return this.s.description}get parserType(){return p.native?"c++":"js"}connect(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.s.state===J){if(typeof t==="function"){t()}return}q(this,W);this.emit("topologyOpening",new c.TopologyOpeningEvent(this.s.id));this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,new a(A.Unknown),this.s.description));connectServers(this,Array.from(this.s.description.servers.values()));h.translate(e);const r=e.readPreference||h.primary;const connectHandler=e=>{if(e){this.close();if(typeof t==="function"){t(e)}else{this.emit("error",e)}return}q(this,J);this.emit("open",e,this);this.emit("connect",this);if(typeof t==="function")t(e,this)};if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:r},connectHandler);return}this.selectServer(L(r),e,connectHandler)}close(e,t){if(typeof e==="function"){t=e;e={}}if(typeof e==="boolean"){e={force:e}}e=e||{};if(this.s.state===V||this.s.state===Y){if(typeof t==="function"){t()}return}q(this,Y);drainWaitQueue(this[$],new C("Topology closed"));O(this.s.connectionTimers);if(this.s.srvPoller){this.s.srvPoller.stop();if(this.s.handleSrvPolling){this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling);delete this.s.handleSrvPolling}}if(this.s.detectTopologyDescriptionChange){this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange);delete this.s.detectTopologyDescriptionChange}this.s.sessions.forEach((e=>e.endSession()));this.s.sessionPool.endAllPooledSessions((()=>{w(Array.from(this.s.servers.values()),((t,r)=>destroyServer(t,this,e,r)),(e=>{this.s.servers.clear();this.emit("topologyClosed",new c.TopologyClosedEvent(this.s.id));q(this,V);if(typeof t==="function"){t(e)}}))}))}selectServer(e,t,r){if(typeof t==="function"){r=t;if(typeof e!=="function"){t=e;let r;if(e instanceof h){r=e}else if(typeof e==="string"){r=new h(e)}else{h.translate(t);r=t.readPreference||h.primary}e=L(r)}else{t={}}}t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const n=this.description.type===A.Sharded;const o=t.session;const s=o&&o.transaction;if(n&&s&&s.server){r(undefined,s.server);return}let i=e;if(typeof e==="object"){const t=e.readPreference?e.readPreference:h.primary;i=L(t)}const a={serverSelector:i,transaction:s,callback:r};const c=t.serverSelectionTimeoutMS;if(c){a.timer=setTimeout((()=>{a[z]=true;a.timer=undefined;const e=new I(`Server selection timed out after ${c} ms`,this.description);a.callback(e)}),c)}this[$].push(a);processWaitQueue(this)}shouldCheckForSessionSupport(){if(this.description.type===A.Single){return!this.description.hasKnownServers}return!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new m(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){if(!Array.isArray(e)){e=[e]}this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:true,serverApi:this.serverApi},(()=>{if(typeof t==="function")t()}))}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address)){return}if(isStaleServerDescription(this.s.description,e)){return}const t=this.s.description;const r=this.s.description.servers.get(e.address);const n=e.$clusterTime;if(n){y(this,n)}const o=r&&r.equals(e);this.s.description=this.s.description.update(e);if(this.s.description.compatibilityError){this.emit("error",new C(this.s.description.compatibilityError));return}if(!o){this.emit("serverDescriptionChanged",new c.ServerDescriptionChangedEvent(this.s.id,e.address,r,this.s.description.servers.get(e.address)))}updateServers(this,e);if(this[$].length>0){processWaitQueue(this)}if(!o){this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){if(typeof e==="function")t=e,e=null;if(typeof t==="function")t(null,true)}logout(e){if(typeof e==="function")e(null,true)}insert(e,t,r,n){executeWriteOperation({topology:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({topology:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({topology:this,op:"remove",ns:e,ops:t},r,n)}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}h.translate(r);const o=r.readPreference||h.primary;this.selectServer(L(o),r,((o,s)=>{if(o){n(o);return}const i=!r.retrying;const a=!!r.retryWrites;const A=!!r.session;const c=s.supportsRetryableWrites;const l=!A||!r.session.inTransaction();const u=i&&a&&A&&c&&l&&isWriteCommand(t);const cb=(o,s)=>{if(!o)return n(null,s);if(!shouldRetryOperation(o)){return n(o)}if(u){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}return n(o)};if(u){r.session.incrementTransactionNumber();r.willRetryWrite=u}s.command(e,t,r,cb)}))}cursor(e,t,r){r=r||{};const n=r.topology||this;const o=r.cursorFactory||this.s.Cursor;h.translate(r);return new o(n,e,t,r)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===J}isDestroyed(){return this.s.state===V}unref(){N("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(e.length===0)return{};const t=e.filter((e=>e.type!==i.Unknown))[0];const r=t||{maxWireVersion:this.description.commonWireVersion};return r}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(Topology.prototype,"clusterTime",{enumerable:true,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});Topology.prototype.destroy=g(Topology.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function isWriteCommand(e){return K.some((t=>e[t]))}function isStaleServerDescription(e,t){const r=e.servers.get(t.address);const n=r.topologyVersion;return D(n,t.topologyVersion)>0}function destroyServer(e,t,r,n){r=r||{};G.forEach((t=>e.removeAllListeners(t)));e.destroy(r,(()=>{t.emit("serverClosed",new c.ServerClosedEvent(t.s.id,e.description.address));P.forEach((t=>e.removeAllListeners(t)));if(typeof n==="function"){n()}}))}function parseStringSeedlist(e){return e.split(",").map((e=>({host:e.split(":")[0],port:e.split(":")[1]||27017})))}function topologyTypeFromSeedlist(e,t){if(t.directConnection){return A.Single}const r=t.replicaSet||t.setName||t.rs_name;if(r==null){return A.Unknown}return A.ReplicaSetNoPrimary}function randomSelection(e){return e[Math.floor(Math.random()*e.length)]}function createAndConnectServer(e,t,r){e.emit("serverOpening",new c.ServerOpeningEvent(e.s.id,t.address));const n=new l(t,e.s.options,e);u(n,e,P);n.on("descriptionReceived",e.serverUpdateHandler.bind(e));if(r){const t=setTimeout((()=>{_(t,e.s.connectionTimers);n.connect()}),r);e.s.connectionTimers.add(t);return n}n.connect();return n}function connectServers(e,t){e.s.servers=t.reduce(((t,r)=>{const n=createAndConnectServer(e,r);t.set(r.address,n);return t}),new Map)}function updateServers(e,t){if(t&&e.s.servers.has(t.address)){const r=e.s.servers.get(t.address);r.s.description=t}for(const t of e.description.servers.values()){if(!e.s.servers.has(t.address)){const r=createAndConnectServer(e,t);e.s.servers.set(t.address,r)}}for(const t of e.s.servers){const r=t[0];if(e.description.hasServer(r)){continue}const n=e.s.servers.get(r);e.s.servers.delete(r);destroyServer(n,e)}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.topology;const o=e.op;const s=e.ns;const i=e.ops;n.selectServer(F(),t,((n,a)=>{if(n){r(n,null);return}const A=!e.retrying;const c=!!t.retryWrites;const l=!!t.session;const u=a.supportsRetryableWrites;const h=!l||!t.session.inTransaction();const d=t.explain===undefined;const g=A&&c&&l&&u&&h&&d;const handler=(n,o)=>{if(!n)return r(null,o);if(!shouldRetryOperation(n)){n=Q(n);return r(n)}if(g){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}return r(n)};if(r.operationId){handler.operationId=r.operationId}if(g){t.session.incrementTransactionNumber();t.willRetryWrite=g}a[o](s,i,t,handler)}))}function shouldRetryOperation(e){return e instanceof C&&e.hasErrorLabel("RetryableWriteError")}function srvPollingHandler(e){return function handleSrvPolling(t){const r=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(t);if(e.s.description===r){return}updateServers(e);e.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(e.s.id,r,e.s.description))}}function drainWaitQueue(e,t){while(e.length){const r=e.shift();clearTimeout(r.timer);if(!r[z]){r.callback(t)}}}function processWaitQueue(e){if(e.s.state===V){drainWaitQueue(e[$],new C("Topology is closed, please connect"));return}const t=Array.from(e.description.servers.values());const r=e[$].length;for(let n=0;n0){e.s.servers.forEach((e=>process.nextTick((()=>e.requestCheck()))))}}e.exports={Topology:Topology}},7962:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(750).ServerDescription;const s=r(7161);const i=r(2291).TopologyType;const a=s.MIN_SUPPORTED_SERVER_VERSION;const A=s.MAX_SUPPORTED_SERVER_VERSION;const c=s.MIN_SUPPORTED_WIRE_VERSION;const l=s.MAX_SUPPORTED_WIRE_VERSION;class TopologyDescription{constructor(e,t,r,o,s,u,h){h=h||{};this.type=e||i.Unknown;this.setName=r||null;this.maxSetVersion=o||null;this.maxElectionId=s||null;this.servers=t||new Map;this.stale=false;this.compatible=true;this.compatibilityError=null;this.logicalSessionTimeoutMinutes=null;this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0;this.localThresholdMS=h.localThresholdMS||0;this.commonWireVersion=u||null;Object.defineProperty(this,"options",{value:h,enumberable:false});for(const e of this.servers.values()){if(e.type===n.Unknown)continue;if(e.minWireVersion>l){this.compatible=false;this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${A})`}if(e.maxWireVersion=0){u.delete(t)}if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){const t=updateRsNoPrimaryFromMember(u,s,e);r=t[0],s=t[1]}}if(r===i.ReplicaSetWithPrimary){if([n.Standalone,n.Mongos].indexOf(l)>=0){u.delete(t);r=checkHasPrimary(u)}else if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){r=updateRsWithPrimaryFromMember(u,s,e)}else{r=checkHasPrimary(u)}}return new TopologyDescription(r,u,s,a,A,c,this.options)}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));if(e.length>0){return e[0].error}return undefined}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==n.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}}function topologyTypeForServerType(e){if(e===n.Standalone){return i.Single}if(e===n.Mongos){return i.Sharded}if(e===n.RSPrimary){return i.ReplicaSetWithPrimary}if(e===n.RSGhost||e===n.Unknown){return i.Unknown}return i.ReplicaSetNoPrimary}function compareObjectId(e,t){if(e==null){return-1}if(t==null){return 1}if(e.id instanceof Buffer&&t.id instanceof Buffer){const r=e.id;const n=t.id;return r.compare(n)}const r=e.toString();const n=t.toString();return r.localeCompare(n)}function updateRsFromPrimary(e,t,r,s,i){t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[checkHasPrimary(e),t,s,i]}const a=r.electionId?r.electionId:null;if(r.setVersion&&a){if(s&&i){if(s>r.setVersion||compareObjectId(i,a)>0){e.set(r.address,new o(r.address));return[checkHasPrimary(e),t,s,i]}}i=r.electionId}if(r.setVersion!=null&&(s==null||r.setVersion>s)){s=r.setVersion}for(const t of e.keys()){const s=e.get(t);if(s.type===n.RSPrimary&&s.address!==r.address){e.set(t,new o(s.address));break}}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));const A=Array.from(e.keys());const c=r.allHosts;A.filter((e=>c.indexOf(e)===-1)).forEach((t=>{e.delete(t)}));return[checkHasPrimary(e),t,s,i]}function updateRsWithPrimaryFromMember(e,t,r){if(t==null){throw new TypeError("setName is required")}if(t!==r.setName||r.me&&r.address!==r.me){e.delete(r.address)}return checkHasPrimary(e)}function updateRsNoPrimaryFromMember(e,t,r){let n=i.ReplicaSetNoPrimary;t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[n,t]}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));if(r.me&&r.address!==r.me){e.delete(r.address)}return[n,t]}function checkHasPrimary(e){for(const t of e.keys()){if(e.get(t).type===n.RSPrimary){return i.ReplicaSetWithPrimary}}return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:TopologyDescription}},5474:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(2361);const s=n();const i=s.Binary;const a=r(1178).uuidV4;const A=r(3111).MongoError;const c=r(3111).isRetryableError;const l=r(3111).isRetryableEndTransactionError;const u=r(3111).MongoNetworkError;const h=r(3111).MongoWriteConcernError;const d=r(1707).Transaction;const g=r(1707).TxnState;const p=r(1178).isPromiseLike;const E=r(4485);const m=r(1371).maybePromise;const C=r(1707).isTransactionCommand;const I=r(2306).resolveClusterTime;const y=r(7272).isSharded;const B=r(1178).maxWireVersion;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;const w=8;function assertAlive(e,t){if(e.serverSession==null){const e=new A("Cannot use a session that has ended");if(typeof t==="function"){t(e,null);return false}throw e}return true}const S=Symbol("serverSession");class ClientSession extends o{constructor(e,t,r,n){super();if(e==null){throw new Error("ClientSession requires a topology")}if(t==null||!(t instanceof ServerSessionPool)){throw new Error("ClientSession requires a ServerSessionPool")}r=r||{};n=n||{};this.topology=e;this.sessionPool=t;this.hasEnded=false;this.clientOptions=n;this[S]=undefined;this.supports={causalConsistency:typeof r.causalConsistency!=="undefined"?r.causalConsistency:true};this.clusterTime=r.initialClusterTime;this.operationTime=null;this.explicit=!!r.explicit;this.owner=r.owner;this.defaultTransactionOptions=Object.assign({},r.defaultTransactionOptions);this.transaction=new d}get id(){return this.serverSession.id}get serverSession(){if(this[S]==null){this[S]=this.sessionPool.acquire()}return this[S]}endSession(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=this;return m(this,t,(e=>{if(r.hasEnded){return e()}function completeEndSession(){r.sessionPool.release(r.serverSession);r[S]=undefined;r.hasEnded=true;r.emit("ended",r);e()}if(r.serverSession&&r.inTransaction()){r.abortTransaction((t=>{if(t)return e(t);completeEndSession()}));return}completeEndSession()}))}advanceOperationTime(e){if(this.operationTime==null){this.operationTime=e;return}if(e.greaterThan(this.operationTime)){this.operationTime=e}}equals(e){if(!(e instanceof ClientSession)){return false}return this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){assertAlive(this);if(this.inTransaction()){throw new A("Transaction already in progress")}const t=B(this.topology);if(y(this.topology)&&t!=null&&tendTransaction(this,"commitTransaction",e)))}abortTransaction(e){return m(this,e,(e=>endTransaction(this,"abortTransaction",e)))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){const r=Q();return attemptTransaction(this,r,e,t)}}const v=12e4;const R=100;const k=79;const D=50;const N=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function hasNotTimedOut(e,t){return b(e){if(o instanceof A&&hasNotTimedOut(t,v)&&!isMaxTimeMSExpiredError(o)){if(o.hasErrorLabel("UnknownTransactionCommitResult")){return attemptTransactionCommit(e,t,r,n)}if(o.hasErrorLabel("TransientTransactionError")){return attemptTransaction(e,t,r,n)}}throw o}))}const T=new Set([g.NO_TRANSACTION,g.TRANSACTION_COMMITTED,g.TRANSACTION_ABORTED]);function userExplicitlyEndedTransaction(e){return T.has(e.transaction.state)}function attemptTransaction(e,t,r,n){e.startTransaction(n);let o;try{o=r(e)}catch(e){o=Promise.reject(e)}if(!p(o)){e.abortTransaction();throw new TypeError("Function provided to `withTransaction` must return a Promise")}return o.then((()=>{if(userExplicitlyEndedTransaction(e)){return}return attemptTransactionCommit(e,t,r,n)})).catch((o=>{function maybeRetryOrThrow(o){if(o instanceof A&&o.hasErrorLabel("TransientTransactionError")&&hasNotTimedOut(t,v)){return attemptTransaction(e,t,r,n)}if(isMaxTimeMSExpiredError(o)){o.addErrorLabel("UnknownTransactionCommitResult")}throw o}if(e.transaction.isActive){return e.abortTransaction().then((()=>maybeRetryOrThrow(o)))}return maybeRetryOrThrow(o)}))}function endTransaction(e,t,r){if(!assertAlive(e,r)){return}let n=e.transaction.state;if(n===g.NO_TRANSACTION){r(new A("No transaction started"));return}if(t==="commitTransaction"){if(n===g.STARTING_TRANSACTION||n===g.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(g.TRANSACTION_COMMITTED_EMPTY);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_ABORTED);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call abortTransaction twice"));return}if(n===g.TRANSACTION_COMMITTED||n===g.TRANSACTION_COMMITTED_EMPTY){r(new A("Cannot call abortTransaction after calling commitTransaction"));return}}const o={[t]:1};let s;if(e.transaction.options.writeConcern){s=Object.assign({},e.transaction.options.writeConcern)}else if(e.clientOptions&&e.clientOptions.w){s={w:e.clientOptions.w}}if(n===g.TRANSACTION_COMMITTED){s=Object.assign({wtimeout:1e4},s,{w:"majority"})}if(s){Object.assign(o,{writeConcern:s})}if(t==="commitTransaction"&&e.transaction.options.maxTimeMS){Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS})}function commandHandler(n,o){if(t==="commitTransaction"){e.transaction.transition(g.TRANSACTION_COMMITTED);if(n){if(n instanceof u||n instanceof h||c(n)||isMaxTimeMSExpiredError(n)){if(isUnknownTransactionCommitResult(n)){n.addErrorLabel("UnknownTransactionCommitResult");e.transaction.unpinServer()}}else if(n.hasErrorLabel("TransientTransactionError")){e.transaction.unpinServer()}}}else{e.transaction.transition(g.TRANSACTION_ABORTED)}r(n,o)}function transactionError(e){return t==="commitTransaction"?e:null}if(e.transaction.recoveryToken&&supportsRecoveryToken(e)){o.recoveryToken=e.transaction.recoveryToken}e.topology.command("admin.$cmd",o,{session:e},((t,r)=>{if(t&&l(t)){if(o.commitTransaction){e.transaction.unpinServer();o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})}return e.topology.command("admin.$cmd",o,{session:e},((e,t)=>commandHandler(transactionError(e),t)))}commandHandler(transactionError(t),r)}))}function supportsRecoveryToken(e){const t=e.topology;return!!t.s.options.useRecoveryToken}class ServerSession{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)};this.lastUse=Q();this.txnNumber=0;this.isDirty=false}hasTimedOut(e){const t=Math.round(b(this.lastUse)%864e5%36e5/6e4);return t>e-1}}class ServerSessionPool{constructor(e){if(e==null){throw new Error("ServerSessionPool requires a topology")}this.topology=e;this.sessions=[]}endAllPooledSessions(e){if(this.sessions.length){this.topology.endSessions(this.sessions.map((e=>e.id)),(()=>{this.sessions=[];if(typeof e==="function"){e()}}));return}if(typeof e==="function"){e()}}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const t=this.sessions.shift();if(!t.hasTimedOut(e)){return t}}return new ServerSession}release(e){const t=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const e=this.sessions[this.sessions.length-1];if(e.hasTimedOut(t)){this.sessions.pop()}else{break}}if(!e.hasTimedOut(t)){if(e.isDirty){return}this.sessions.unshift(e)}}}function commandSupportsReadConcern(e,t){if(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch){return true}if(e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline")){return true}return false}function applySession(e,t,r){if(e.hasEnded){return new A("Cannot use a session that has ended")}if(r&&r.writeConcern&&r.writeConcern.w===0){return}const n=e.serverSession;n.lastUse=Q();t.lsid=n.id;const o=e.inTransaction()||C(t);const i=r.willRetryWrite;const a=commandSupportsReadConcern(t,r);if(n.txnNumber&&(i||o)){t.txnNumber=s.Long.fromNumber(n.txnNumber)}if(!o){if(e.transaction.state!==g.NO_TRANSACTION){e.transaction.transition(g.NO_TRANSACTION)}if(e.supports.causalConsistency&&e.operationTime&&a){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}return}if(r.readPreference&&!r.readPreference.equals(E.primary)){return new A(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`)}t.autocommit=false;if(e.transaction.state===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_IN_PROGRESS);t.startTransaction=true;const r=e.transaction.options.readConcern||e.clientOptions.readConcern;if(r){t.readConcern=r}if(e.supports.causalConsistency&&e.operationTime){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}}}function updateSessionFromResponse(e,t){if(t.$clusterTime){I(e,t.$clusterTime)}if(t.operationTime&&e&&e.supports.causalConsistency){e.advanceOperationTime(t.operationTime)}if(t.recoveryToken&&e&&e.inTransaction()){e.transaction._recoveryToken=t.recoveryToken}}e.exports={ClientSession:ClientSession,ServerSession:ServerSession,ServerSessionPool:ServerSessionPool,TxnState:g,applySession:applySession,updateSessionFromResponse:updateSessionFromResponse,commandSupportsReadConcern:commandSupportsReadConcern}},8175:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4847).CoreCursor;const a=r(104);const A=r(7746).retrieveBSON;const c=r(3111).MongoError;const l=r(6495);const u=r(2306).diff;const h=r(2306).cloneOptions;const d=r(2306).SessionMixins;const g=r(2306).isRetryableWritesSupported;const p=r(1178).relayEvents;const E=A();const m=r(2306).getMMAPError;const C=r(1178).makeClientMetadata;const I=r(2306).legacyIsRetryableWriteError;var y="disconnected";var B="connecting";var Q="connected";var b="unreferenced";var w="destroying";var S="destroyed";function stateTransition(e,t){var r={disconnected:[B,w,S,y],connecting:[B,w,S,Q,y],connected:[Q,y,w,S,b],unreferenced:[b,w,S],destroyed:[S]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{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 v=1;var R=["connect","close","error","timeout","parseError"];var Mongos=function(e,t){t=t||{};this.id=v++;if(Array.isArray(e)){e=e.reduce(((e,t)=>{if(e.find((e=>e.host===t.host&&e.port===t.port))){return e}e.push(t);return e}),[])}this.s={options:Object.assign({metadata:C(t)},t),bson:t.bson||new E([E.Binary,E.Code,E.DBRef,E.Decimal128,E.Double,E.Int32,E.Long,E.Map,E.MaxKey,E.MinKey,E.ObjectId,E.BSONRegExp,E.Symbol,E.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false,localThresholdMS:t.localThresholdMS||15};if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0){e.emit(t,r)}}const k=["serverDescriptionChanged","error","close","timeout","parseError"];function destroyServer(e,t,r){t=t||{};k.forEach((t=>e.removeAllListeners(t)));e.destroy(t,r)}Mongos.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,B);var r=this.s.seedlist.map((function(r){const n=new l(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,parent:t}));p(n,t,["serverDescriptionChanged"]);return n}));emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectProxies(t,r)};Mongos.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};function handleEvent(e){return function(){if(e.state===S||e.state===w){return}moveServerFrom(e.connectedProxies,e.disconnectedProxies,this);emitTopologyDescriptionChanged(e);e.emit("left","mongos",this);e.emit("serverClosed",{topologyId:e.id,address:this.name})}}function handleInitialConnectEvent(e,t){return function(){var r=this;if(e.state===S){emitTopologyDescriptionChanged(e);moveServerFrom(e.connectingProxies,e.disconnectedProxies,this);return this.destroy()}if(t==="connect"){e.ismaster=r.lastIsMaster();if(e.ismaster.msg==="isdbgrid"){for(let t=0;t0&&e.state===B){stateTransition(e,Q);e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.disconnectedProxies.length===0){if(e.s.logger.isWarn()){e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset"))}return e.emit("error",new c("no mongos proxies found in seed list"))}topologyMonitor(e,{firstConnect:true})}}}function connectProxies(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function connect(t,r){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name});emitTopologyDescriptionChanged(e);t.once("close",handleInitialConnectEvent(e,"close"));t.once("timeout",handleInitialConnectEvent(e,"timeout"));t.once("parseError",handleInitialConnectEvent(e,"parseError"));t.once("error",handleInitialConnectEvent(e,"error"));t.once("connect",handleInitialConnectEvent(e,"connect"));p(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}t.forEach((e=>connect(e,r++)))}function pickProxy(e,t){const r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected()){return r.server}else{r.unpinServer()}}var n=e.connectedProxies.slice(0);var o=Number.MAX_VALUE;for(var s=0;s0&&e.state===B){e.emit("error",new c("no mongos proxy available"))}else{e.emit("close",e)}return reconnectProxies(e,e.disconnectedProxies,(function(){if(e.state===S||e.state===w||e.state===b){return}if(e.state===B&&t.firstConnect){e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.isConnected()){e.emit("reconnect",e)}else if(!e.isConnected()&&e.listeners("close").length>0){e.emit("close",e)}topologyMonitor(e)}))}for(var o=0;o{n--;if(n>0){return}emitTopologyDescriptionChanged(this);emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});stateTransition(this,S);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name});destroyServer(t,e,serverDestroyed);moveServerFrom(this.connectedProxies,this.disconnectedProxies,t)}))};Mongos.prototype.isConnected=function(){return this.connectedProxies.length>0};Mongos.prototype.isDestroyed=function(){return this.state===S};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const o=e.op;const s=e.ns;const i=e.ops;let a=pickProxy(n,t.session);if(!a)return r(new c("no mongos proxy available"));const A=!e.retrying&&!!t.retryWrites&&t.session&&g(n)&&!t.session.inTransaction()&&t.explain===undefined;const handler=(o,s)=>{if(!o)return r(null,s);if(!I(o,n)||!A){o=m(o);return r(o)}a=pickProxy(n,t.session);if(!a){return r(o)}const i=Object.assign({},e,{retrying:true});return executeWriteOperation(i,t,r)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}a[o](s,i,t,handler)}Mongos.prototype.insert=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("insert",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};Mongos.prototype.update=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("update",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};Mongos.prototype.remove=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("remove",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const D=["findAndModify","insert","update","delete"];function isWriteCommand(e){return D.some((t=>e[t]))}Mongos.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}var s=this;var i=pickProxy(s,r.session);if((i==null||!i.isConnected())&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}if(i==null){return n(new c("no mongos proxy available"))}var a=h(r);a.topology=s;const A=!r.retrying&&r.retryWrites&&r.session&&g(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(r,o)=>{if(!r)return n(null,o);if(!I(r,s)){return n(r)}if(A){const r=Object.assign({},a,{retrying:true});return this.command(e,t,r,n)}return n(r)};if(A){a.session.incrementTransactionNumber();a.willRetryWrite=A}i.command(e,t,a,cb)};Mongos.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Mongos.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;t=t||{};const n=pickProxy(this,t.session);if(n==null){r(new c("server selection failed"));return}if(this.s.debug)this.emit("pickedServer",null,n);r(null,n)};Mongos.prototype.connections=function(){var e=[];for(var t=0;t0){var t="Unknown";if(e.connectedProxies.length>0){t="Sharded"}var r={topologyType:t,servers:[]};var n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map((function(e){var t=e.getDescription();t.type="Unknown";return t})));r.servers=r.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();t.type="Mongos";return t})));var o=u(e.topologyDescription,r);var s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:o};if(o.servers.length>0){e.emit("topologyDescriptionChanged",s)}e.topologyDescription=r}}e.exports=Mongos},4485:(e,t,r)=>{"use strict";const n=r(1371).emitWarningOnce;const ReadPreference=function(e,t,r){if(!ReadPreference.isValid(e)){throw new TypeError(`Invalid read preference mode ${e}`)}if(t&&!Array.isArray(t)){n("ReadPreference tags must be an array, this will change in the next major version");const e=typeof t.maxStalenessSeconds!=="undefined";const o=typeof t.hedge!=="undefined";const s=e||o;if(s){r=t;t=undefined}else{t=[t]}}this.mode=e;this.tags=t;this.hedge=r&&r.hedge;r=r||{};if(r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0){throw new TypeError("maxStalenessSeconds must be a positive integer")}this.maxStalenessSeconds=r.maxStalenessSeconds;this.minWireVersion=5}if(this.mode===ReadPreference.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(ReadPreference.prototype,"preference",{enumerable:true,get:function(){return this.mode}});ReadPreference.PRIMARY="primary";ReadPreference.PRIMARY_PREFERRED="primaryPreferred";ReadPreference.SECONDARY="secondary";ReadPreference.SECONDARY_PREFERRED="secondaryPreferred";ReadPreference.NEAREST="nearest";const o=[ReadPreference.PRIMARY,ReadPreference.PRIMARY_PREFERRED,ReadPreference.SECONDARY,ReadPreference.SECONDARY_PREFERRED,ReadPreference.NEAREST,null];ReadPreference.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const r=e.readPreferenceTags;const n=e.maxStalenessSeconds;if(typeof t==="string"){return new ReadPreference(t,r)}else if(!(t instanceof ReadPreference)&&typeof t==="object"){const e=t.mode||t.preference;if(e&&typeof e==="string"){return new ReadPreference(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}}return t};ReadPreference.resolve=function(e,t){t=t||{};const r=t.session;const n=e&&e.readPreference;let o;if(t.readPreference){o=ReadPreference.fromOptions(t)}else if(r&&r.inTransaction()&&r.transaction.options.readPreference){o=r.transaction.options.readPreference}else if(n!=null){o=n}else{o=ReadPreference.primary}return typeof o==="string"?new ReadPreference(o):o};ReadPreference.translate=function(e){if(e.readPreference==null)return e;const t=e.readPreference;if(typeof t==="string"){e.readPreference=new ReadPreference(t)}else if(t&&!(t instanceof ReadPreference)&&typeof t==="object"){const r=t.mode||t.preference;if(r&&typeof r==="string"){e.readPreference=new ReadPreference(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds})}}else if(!(t instanceof ReadPreference)){throw new TypeError("Invalid read preference: "+t)}return e};ReadPreference.isValid=function(e){return o.indexOf(e)!==-1};ReadPreference.prototype.isValid=function(e){return ReadPreference.isValid(typeof e==="string"?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];ReadPreference.prototype.slaveOk=function(){return s.indexOf(this.mode)!==-1};ReadPreference.prototype.equals=function(e){return e.mode===this.mode};ReadPreference.prototype.toJSON=function(){const e={mode:this.mode};if(Array.isArray(this.tags))e.tags=this.tags;if(this.maxStalenessSeconds)e.maxStalenessSeconds=this.maxStalenessSeconds;if(this.hedge)e.hedge=this.hedge;return e};ReadPreference.primary=new ReadPreference("primary");ReadPreference.primaryPreferred=new ReadPreference("primaryPreferred");ReadPreference.secondary=new ReadPreference("secondary");ReadPreference.secondaryPreferred=new ReadPreference("secondaryPreferred");ReadPreference.nearest=new ReadPreference("nearest");e.exports=ReadPreference},1134:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4485);const a=r(4847).CoreCursor;const A=r(7746).retrieveBSON;const c=r(104);const l=r(3111).MongoError;const u=r(6495);const h=r(8742);const d=r(2306).Timeout;const g=r(2306).Interval;const p=r(2306).SessionMixins;const E=r(2306).isRetryableWritesSupported;const m=r(1178).relayEvents;const C=A();const I=r(2306).getMMAPError;const y=r(1178).makeClientMetadata;const B=r(2306).legacyIsRetryableWriteError;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;var w="disconnected";var S="connecting";var v="connected";var R="unreferenced";var k="destroyed";function stateTransition(e,t){var r={disconnected:[S,k,w],connecting:[S,k,v,w],connected:[v,w,k,R],unreferenced:[R,k],destroyed:[k]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}}var D=1;var N=["connect","close","error","timeout","parseError"];var ReplSet=function(e,t){var r=this;t=t||{};if(!Array.isArray(e))throw new l("seedlist must be an array");if(e.length===0)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if(typeof e.host!=="string"||typeof e.port!=="number")throw new l("seedlist entry must contain a host and port")}));s.call(this);this.id=D++;var n=t.localThresholdMS||15;if(t.acceptableLatency)n=t.acceptableLatency;var i=c("ReplSet",t);this.s={options:Object.assign({metadata:y(t)},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]),Cursor:t.cursorFactory||a,logger:i,seedlist:e,replicaSetState:new h({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false};this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){r.emit("topologyDescriptionChanged",e)}));if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoute.name===t));if(r>=0){const t=e.s.connectingServers[r];t.destroy({force:true});e.s.connectingServers.splice(r,1);return done()}var n=new u(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:false,monitoring:false,parent:e}));n.once("connect",_handleEvent(e,"connect"));n.once("close",_handleEvent(e,"close"));n.once("timeout",_handleEvent(e,"timeout"));n.once("error",_handleEvent(e,"error"));n.once("parseError",_handleEvent(e,"parseError"));n.on("serverOpening",(t=>e.emit("serverOpening",t)));n.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));n.on("serverClosed",(t=>e.emit("serverClosed",t)));m(n,e,["commandStarted","commandSucceeded","commandFailed"]);e.s.connectingServers.push(n);n.connect(e.s.connectOptions)}),r)}for(var s=0;se.emit("serverOpening",t)));t.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));t.on("serverClosed",(t=>e.emit("serverClosed",t)));m(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}while(t.length>0){connect(t.shift(),r++)}}function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}ReplSet.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,S);var r=this.s.seedlist.map((function(r){return new u(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,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)))}emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectServers(t,r)};ReplSet.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};ReplSet.prototype.destroy=function(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};let r=this.s.connectingServers.length+1;const serverDestroyed=()=>{r--;if(r>0){return}emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});if(typeof t==="function"){t(null,null)}};if(this.state===k){if(typeof t==="function")t(null,null);return}stateTransition(this,k);if(this.haTimeoutId)clearTimeout(this.haTimeoutId);for(var n=0;n{if(b(s)>=T){if(o!=null){r(o,null)}else{r(new l("Server selection timed out"))}return}const e=this.s.replicaSetState.pickServer(n);if(e==null){setTimeout(_selectServer,O);return}if(!(e instanceof u)){o=e;setTimeout(_selectServer,O);return}if(this.s.debug)this.emit("pickedServer",t.readPreference,e);r(null,e)};_selectServer()};ReplSet.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const s=e.op;const i=e.ns;const a=e.ops;if(n.state===k){return r(new l(o("topology was destroyed")))}const A=!e.retrying&&!!t.retryWrites&&t.session&&E(n)&&!t.session.inTransaction()&&t.explain===undefined;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler){return n.s.disconnectHandler.add(s,i,a,t,r)}else if(!A){return r(new l("no primary server found"))}}const handler=(o,s)=>{if(!o)return r(null,s);if(!B(o,n)){o=I(o);return r(o)}if(A){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}if(n.s.replicaSetState.primary){n.s.replicaSetState.primary.destroy();n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:true})}return r(o)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}n.s.replicaSetState.primary[s](i,a,t,handler)}ReplSet.prototype.insert=function(e,t,r,n){executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};ReplSet.prototype.update=function(e,t,r,n){executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};ReplSet.prototype.remove=function(e,t,r,n){executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const _=["findAndModify","insert","update","delete"];function isWriteCommand(e){return _.some((t=>e[t]))}ReplSet.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===k)return n(new l(o("topology was destroyed")));var s=this;var a=r.readPreference?r.readPreference:i.primary;if(a.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}var A=this.s.replicaSetState.pickServer(a);if(!(A instanceof u))return n(A);if(s.s.debug)s.emit("pickedServer",i.primary,A);if(A==null){return n(new l(o("no server found that matches the provided readPreference %s",a)))}const c=!r.retrying&&!!r.retryWrites&&r.session&&E(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(o,i)=>{if(!o)return n(null,i);if(!B(o,s)){return n(o)}if(c){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}if(this.s.replicaSetState.primary){this.s.replicaSetState.primary.destroy();this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:true})}return n(o)};if(c){r.session.incrementTransactionNumber();r.willRetryWrite=c}A.command(e,t,r,cb)};ReplSet.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};e.exports=ReplSet},8742:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2306).diff,i=r(2361).EventEmitter,a=r(104),A=r(4485),c=r(3111).MongoError,l=r(1867).Buffer;var u={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};var h={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};var ReplSetState=function(e){e=e||{};i.call(this);this.topologyType=e.setName?u.ReplicaSetNoPrimary:u.Unknown;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=undefined};n(ReplSetState,i);ReplSetState.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};ReplSetState.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};ReplSetState.prototype.hasPrimary=function(){return this.primary!=null};ReplSetState.prototype.hasSecondary=function(){return this.secondaries.length>0};ReplSetState.prototype.get=function(e){var t=this.allServers();for(var r=0;r{n--;if(n>0){return}this.secondaries=[];this.arbiters=[];this.passives=[];this.ghosts=[];this.unknownServers=[];this.set={};this.primary=null;emitTopologyDescriptionChanged(this);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>t.destroy(e,serverDestroyed)))};ReplSetState.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase();var n=this.primary?[this.primary]:[];n=n.concat(this.secondaries);n=n.concat(this.arbiters);n=n.concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;ReplSetState.prototype.update=function(e){var t=this;const r=e.lastIsMaster();if(r&&r.isWritablePrimary)r.ismaster=r.isWritablePrimary;var n=e.name.toLowerCase();if(r){var s=Array.isArray(r.hosts)?r.hosts:[];s=s.concat(Array.isArray(r.arbiters)?r.arbiters:[]);s=s.concat(Array.isArray(r.passives)?r.passives:[]);s=s.map((function(e){return e.toLowerCase()}));for(var i=0;il){return false}}else if(!p&&a&&l){if(l=5&&e.ismaster.secondary&&this.hasPrimary()){e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t}else if(e.ismaster.maxWireVersion>=5&&e.ismaster.secondary){e.staleness=r-e.lastWriteDate+t}};ReplSetState.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var o=pickNearest(this,e);if(o){return o}}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e);if(o){return o}}if(e.equals(A.secondaryPreferred)){return this.primary}return null}if(e.equals(A.primaryPreferred)){o=null;if(this.primary){return this.primary}if(n.length>0&&e.maxStalenessSeconds==null){o=pickNearest(this,e)}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e)}if(o)return o}return this.primary};var filterByTags=function(e,t){if(e.tags==null)return t;var r=[];var n=Array.isArray(e.tags)?e.tags:[e.tags];for(var o=0;o0?r[0].lastIsMasterMS:0;r=r.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}));if(r.length===0){return null}e.index=e.index%r.length;var s=r[e.index];e.index=e.index+1;return s}function inList(e,t,r){for(var n=0;n0){var t="Unknown";var r=e.setName;if(e.hasPrimaryAndSecondary()){t="ReplicaSetWithPrimary"}else if(!e.hasPrimary()&&e.hasSecondary()){t="ReplicaSetNoPrimary"}var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary";n.servers.push(o)}n.servers=n.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));n.servers=n.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();t.type="RSArbiter";return t})));n.servers=n.servers.concat(e.passives.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));var i=s(e.replicasetDescription,n);var a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:i};e.emit("topologyDescriptionChanged",a);e.replicasetDescription=n}}e.exports=ReplSetState},6495:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2361).EventEmitter,i=r(4485),a=r(104),A=r(7746).debugOptions,c=r(7746).retrieveBSON,l=r(5500),u=r(3111).MongoError,h=r(3111).MongoNetworkError,d=r(9206),g=r(4847).CoreCursor,p=r(2306),E=r(2306).createCompressionInfo,m=r(2306).resolveClusterTime,C=r(2306).SessionMixins,I=r(7703).extractCommand,y=r(1178).relayEvents;const B=r(1178).collationNotSupported;const Q=r(1178).makeClientMetadata;var b=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];var w=0;var S=false;var v={};var R=c();function topologyId(e){return e.s.parent==null?e.id:e.s.parent.id}var Server=function(e){e=e||{};s.call(this);this.id=w++;this.s={options:Object.assign({metadata:Q(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||g,bson:e.bson||new R([R.Binary,R.Code,R.DBRef,R.Decimal128,R.Double,R.Int32,R.Long,R.Map,R.MaxKey,R.MinKey,R.ObjectId,R.BSONRegExp,R.Symbol,R.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring==="boolean"?e.monitoring:true,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval==="number"?e.monitoringInterval:5e3,compression:{compressors:E(e)},parent:e.parent};if(!this.s.parent){this.s.clusterTime=null}this.ismaster=null;this.lastIsMasterMS=-1;this.monitoringProcessId=null;this.initialConnect=true;this._type="server";this.lastUpdateTime=0;this.lastWriteDate=0;this.staleness=0};n(Server,s);Object.assign(Server.prototype,C);Object.defineProperty(Server.prototype,"type",{enumerable:true,get:function(){return this._type}});Object.defineProperty(Server.prototype,"parserType",{enumerable:true,get:function(){return R.native?"c++":"js"}});Object.defineProperty(Server.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){if(!this.ismaster)return null;return this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(Server.prototype,"clientMetadata",{enumerable:true,get:function(){return this.s.options.metadata}});Object.defineProperty(Server.prototype,"clusterTime",{enumerable:true,set:function(e){const t=this.s.parent?this.s.parent:this.s;m(t,e)},get:function(){const e=this.s.parent?this.s.parent:this.s;return e.clusterTime||null}});Server.enableServerAccounting=function(){S=true;v={}};Server.disableServerAccounting=function(){S=false};Server.servers=function(){return v};Object.defineProperty(Server.prototype,"name",{enumerable:true,get:function(){return this.s.options.host+":"+this.s.options.port}});function disconnectHandler(e,t,r,n,s,i){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!s.monitoring){e.s.disconnectHandler.add(t,r,n,s,i);return true}if(!e.s.pool.isConnected()){i(new u(o("no connection available to server %s",e.name)));return true}}function monitoringProcess(e){return function(){if(e.s.pool.isDestroyed())return;e.emit("monitoring",e);var t=(new Date).getTime();e.command("admin.$cmd",{ismaster:true},{socketTimeout:typeof e.s.options.connectionTimeout!=="number"?2e3:e.s.options.connectionTimeout,monitoring:true},((r,n)=>{e.lastIsMasterMS=(new Date).getTime()-t;if(e.s.pool.isDestroyed())return;if(n){e.ismaster=n.result}e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}))}}var eventHandler=function(e,t){return function(r,n){if(e.s.logger.isInfo()){var s=r instanceof u?JSON.stringify(r):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,s))}if(t==="connect"){e.initialConnect=false;e.ismaster=n.ismaster;e.lastIsMasterMS=n.lastIsMasterMS;if(n.agreedCompressor){e.s.pool.options.agreedCompressor=n.agreedCompressor}if(n.zlibCompressionLevel){e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel}if(n.ismaster.$clusterTime){const t=n.ismaster.$clusterTime;e.clusterTime=t}if(e.ismaster.msg==="isdbgrid"){e._type="mongos"}if(e.s.monitoring){e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});if(!e.s.inTopology){p.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)}]})}if(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==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(S&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1){if(!e.s.inTopology){e.emit("topologyOpening",{topologyId:e.id})}delete v[e.id]}if(t==="close"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"})}if(t==="reconnectFailed"){e.emit("reconnectFailed",r);if(e.listeners("error").length>0){e.emit("error",r)}return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1){e.initialConnect=false;return e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,r)))}if(t==="reconnect"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});return e.emit(t,e)}e.emit(t,r)}}};Server.prototype.connect=function(e){var t=this;e=e||{};if(S)v[this.id]=this;if(t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed()){throw new u(o("server instance in invalid state %s",t.s.pool.state))}t.s.pool=new l(this,Object.assign(t.s.options,e,{bson:this.s.bson}));t.s.pool.on("close",eventHandler(t,"close"));t.s.pool.on("error",eventHandler(t,"error"));t.s.pool.on("timeout",eventHandler(t,"timeout"));t.s.pool.on("parseError",eventHandler(t,"parseError"));t.s.pool.on("connect",eventHandler(t,"connect"));t.s.pool.on("reconnect",eventHandler(t,"reconnect"));t.s.pool.on("reconnectFailed",eventHandler(t,"reconnectFailed"));y(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]);if(!t.s.inTopology){this.emit("topologyOpening",{topologyId:topologyId(t)})}t.emit("serverOpening",{topologyId:topologyId(t),address:t.name});t.s.pool.connect()};Server.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};Server.prototype.getDescription=function(){var e=this.ismaster||{};var t={type:p.getTopologyType(this),address:this.name};if(e.hosts)t.hosts=e.hosts;if(e.arbiters)t.arbiters=e.arbiters;if(e.passives)t.passives=e.passives;if(e.setName)t.setName=e.setName;return t};Server.prototype.lastIsMaster=function(){return this.ismaster};Server.prototype.unref=function(){this.s.pool.unref()};Server.prototype.isConnected=function(){if(!this.s.pool)return false;return this.s.pool.isConnected()};Server.prototype.isDestroyed=function(){if(!this.s.pool)return false;return this.s.pool.isDestroyed()};function basicWriteValidations(e){if(!e.s.pool)return new u("server instance is not connected");if(e.s.pool.isDestroyed())return new u("server instance pool was destroyed")}function basicReadValidations(e,t){basicWriteValidations(e,t);if(t.readPreference&&!(t.readPreference instanceof i)){throw new Error("readPreference must be an instance of ReadPreference")}}Server.prototype.command=function(e,t,r,n){var s=this;if(typeof r==="function"){n=r,r={},r=r||{}}var i=basicReadValidations(s,r);if(i)return n(i);r=Object.assign({},r,{wireProtocolCommand:false});if(s.s.logger.isDebug()){const n=I(t);s.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:A(b,r)}),s.name))}if(disconnectHandler(s,"command",e,t,r,n))return;if(B(this,t)){return n(new u(`server ${this.name} does not support collation`))}d.command(s,e,t,r,n)};Server.prototype.query=function(e,t,r,n,o){d.query(this,e,t,r,n,o)};Server.prototype.getMore=function(e,t,r,n,o){d.getMore(this,e,t,r,n,o)};Server.prototype.killCursors=function(e,t,r){d.killCursors(this,e,t,r)};Server.prototype.insert=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"insert",e,t,r,n))return;t=Array.isArray(t)?t:[t];return d.insert(o,e,t,r,n)};Server.prototype.update=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"update",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.update(o,e,t,r,n)};Server.prototype.remove=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"remove",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.remove(o,e,t,r,n)};Server.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Server.prototype.equals=function(e){if(typeof e==="string")return this.name.toLowerCase()===e.toLowerCase();if(e.name)return this.name.toLowerCase()===e.name.toLowerCase();return false};Server.prototype.connections=function(){return this.s.pool.allConnections()};Server.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;r(null,this)};var k=["close","error","timeout","parseError","connect"];Server.prototype.destroy=function(e,t){if(this._destroyed){if(typeof t==="function")t(null,null);return}if(typeof e==="function"){t=e;e={}}e=e||{};var r=this;if(S)delete v[this.id];if(this.monitoringProcessId){clearTimeout(this.monitoringProcessId)}if(!r.s.pool||this._destroyed){this._destroyed=true;if(typeof t==="function")t(null,null);return}this._destroyed=true;if(e.emitClose){r.emit("close",r)}if(e.emitDestroy){r.emit("destroy",r)}k.forEach((function(e){r.s.pool.removeAllListeners(e)}));if(r.listeners("serverClosed").length>0)r.emit("serverClosed",{topologyId:topologyId(r),address:r.name});if(r.listeners("topologyClosed").length>0&&!r.s.inTopology){r.emit("topologyClosed",{topologyId:topologyId(r)})}if(r.s.logger.isDebug()){r.s.logger.debug(o("destroy called on server %s",r.name))}this.s.pool.destroy(e.force,t)};e.exports=Server},2306:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(4485);const s=r(2291).TopologyType;const i=r(3111).MongoError;const a=r(3111).isRetryableWriteError;const A=r(1178).maxWireVersion;const c=r(3111).MongoNetworkError;const l=n.IllegalOperation;function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}function createCompressionInfo(e){if(!e.compression||!e.compression.compressors){return[]}e.compression.compressors.forEach((function(e){if(e!=="snappy"&&e!=="zlib"){throw new Error("compressors must be at least one of snappy or zlib")}}));return e.compression.compressors}function clone(e){return JSON.parse(JSON.stringify(e))}var getPreviousDescription=function(e){if(!e.s.serverDescription){e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}}return e.s.serverDescription};var emitServerDescriptionChanged=function(e,t){if(e.listeners("serverDescriptionChanged").length>0){e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousDescription(e),newDescription:t});e.s.serverDescription=t}};var getPreviousTopologyDescription=function(e){if(!e.s.topologyDescription){e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}}return e.s.topologyDescription};var emitTopologyDescriptionChanged=function(e,t){if(e.listeners("topologyDescriptionChanged").length>0){e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousTopologyDescription(e),newDescription:t});e.s.serverDescription=t}};var changedIsMaster=function(e,t,r){var n=getTopologyType(e,t);var o=getTopologyType(e,r);if(o!==n)return true;return false};var getTopologyType=function(e,t){if(!t){t=e.ismaster}if(!t)return"Unknown";if(t.ismaster&&t.msg==="isdbgrid")return"Mongos";if(t.ismaster&&!t.hosts)return"Standalone";if(t.ismaster)return"RSPrimary";if(t.secondary)return"RSSecondary";if(t.arbiterOnly)return"RSArbiter";return"Unknown"};var inquireServerState=function(e){return function(t){if(e.s.state==="destroyed")return;var r=(new Date).getTime();emitSDAMEvent(e,"serverHeartbeatStarted",{connectionId:e.name});e.command("admin.$cmd",{ismaster:true},{monitoring:true},(function(n,o){if(!n){e.emit("ismaster",o,e);var s=(new Date).getTime()-r;emitSDAMEvent(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name});if(changedIsMaster(e,e.s.ismaster,o.result)){emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:!e.s.inTopology?"Standalone":getTopologyType(e)})}e.s.ismaster=o.result;e.s.isMasterLatencyMS=s}else{emitSDAMEvent(e,"serverHeartbeatFailed",{durationMS:s,failure:n,connectionId:e.name})}if(typeof t==="function"){return t(n,o)}e.s.inquireServerStateTimeout=setTimeout(inquireServerState(e),e.s.haInterval)}))}};var cloneOptions=function(e){var t={};for(var r in e){t[r]=e[r]}return t};function Interval(e,t){var r=false;this.start=function(){if(!this.isRunning()){r=setInterval(e,t)}return this};this.stop=function(){clearInterval(r);r=false;return this};this.isRunning=function(){return r!==false}}function Timeout(e,t){var r=false;var func=()=>{if(r){clearTimeout(r);r=false;e()}};this.start=function(){if(!this.isRunning()){r=setTimeout(func,t)}return this};this.stop=function(){clearTimeout(r);r=false;return this};this.isRunning=function(){return r!==false}}function diff(e,t){var r={servers:[]};if(!e){e={servers:[]}}for(var n=0;n{if(typeof t==="function")t()}))}};function topologyType(e){if(e.description){return e.description.type}if(e.type==="mongos"){return s.Sharded}else if(e.type==="replset"){return s.ReplicaSetWithPrimary}return s.Single}const h=6;const isRetryableWritesSupported=function(e){const t=e.lastIsMaster().maxWireVersion;if(t{"use strict";const n=r(3111).MongoError;const o=r(4485);const s=r(7289);const i=r(2481);let a;let A;(()=>{const e="NO_TRANSACTION";const t="STARTING_TRANSACTION";const r="TRANSACTION_IN_PROGRESS";const n="TRANSACTION_COMMITTED";const o="TRANSACTION_COMMITTED_EMPTY";const s="TRANSACTION_ABORTED";a={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:o,TRANSACTION_ABORTED:s};A={[e]:[e,t],[t]:[r,n,o,s],[r]:[r,n,s],[n]:[n,o,t,e],[s]:[t,e],[o]:[o,e]}})();class Transaction{constructor(e){e=e||{};this.state=a.NO_TRANSACTION;this.options={};const t=i.fromOptions(e);if(t){if(t.w<=0){throw new n("Transactions do not support unacknowledged write concern")}this.options.writeConcern=t}if(e.readConcern){this.options.readConcern=s.fromOptions(e)}if(e.readPreference){this.options.readPreference=o.fromOptions(e)}if(e.maxCommitTimeMS){this.options.maxTimeMS=e.maxCommitTimeMS}this._pinnedServer=undefined;this._recoveryToken=undefined}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(e){const t=A[this.state];if(t&&t.indexOf(e)!==-1){this.state=e;if(this.state===a.NO_TRANSACTION||this.state===a.STARTING_TRANSACTION||this.state===a.TRANSACTION_ABORTED){this.unpinServer()}return}throw new n(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){if(this.isActive){this._pinnedServer=e}}unpinServer(){this._pinnedServer=undefined}}function isTransactionCommand(e){return!!(e.commitTransaction||e.abortTransaction)}e.exports={TxnState:a,Transaction:Transaction,isTransactionCommand:isTransactionCommand}},8767:(e,t,r)=>{"use strict";const n=r(7310);const o=r(3477);const s=r(7578);const i=r(3111).MongoParseError;const a=r(4485);const A=r(1371).emitWarningOnce;const c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;const l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map((e=>e.toLowerCase())));function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}function parseSrvConnectionString(e,t,r){const a=n.parse(e,true);if(t.directConnection||t.directconnection){return r(new i("directConnection not supported with SRV URI"))}if(a.hostname.split(".").length<3){return r(new i("URI does not have hostname, domain name and tld"))}a.domainLength=a.hostname.split(".").length;const A=e.substring("mongodb+srv://".length).split("/")[0];if(A.match(",")){return r(new i("Invalid URI, cannot contain multiple hostnames"))}if(a.port){return r(new i(`Ports not accepted with '${m}' URIs`))}const c=a.host;s.resolveSrv(`_mongodb._tcp.${c}`,((e,A)=>{if(e)return r(e);if(A.length===0){return r(new i("No addresses found at host"))}for(let e=0;e`${e.name}:${e.port}`)).join(",");if(!("ssl"in t)&&(!a.search||!("ssl"in a.query)||a.query.ssl===null)){a.query.ssl=true}s.resolveTxt(c,((e,s)=>{if(e){if(e.code!=="ENODATA"&&e.code!=="ENOTFOUND"){return r(e)}s=null}if(s){if(s.length>1){return r(new i("Multiple text records not allowed"))}s=o.parse(s[0].join(""));if(Object.keys(s).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(Object.keys(s).some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new i("Text record must only set `authSource` or `replicaSet`"))}a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);const A=n.format(a);parseConnectionString(A,t,((e,t)=>{if(e){r(e);return}r(null,Object.assign({},t,{srvHost:c}))}))}))}))}function parseQueryStringItemValue(e,t){if(Array.isArray(t)){t=t.filter(((e,r)=>t.indexOf(e)===r));if(t.length===1)t=t[0]}else if(t.indexOf(":")>0){t=t.split(",").reduce(((t,r)=>{const n=r.split(":");t[n[0]]=parseQueryStringItemValue(e,n[1]);return t}),{})}else if(t.indexOf(",")>0){t=t.split(",").map((t=>parseQueryStringItemValue(e,t)))}else if(t.toLowerCase()==="true"||t.toLowerCase()==="false"){t=t.toLowerCase()==="true"}else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);if(!Number.isNaN(e)){t=parseFloat(t)}}return t}const u=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]);const h=new Set(["authsource","replicaset"]);const d=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]);const g={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 applyConnectionStringOption(e,t,r,n){if(t==="journal"){t="j"}else if(t==="wtimeoutms"){t="wtimeout"}if(u.has(t)){r=r==="true"||r===true}else if(t==="appname"){r=decodeURIComponent(r)}else if(t==="readconcernlevel"){e["readConcernLevel"]=r;t="readconcern";r={level:r}}if(t==="compressors"){r=Array.isArray(r)?r:[r];if(!r.every((e=>e==="snappy"||e==="zlib"))){throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`")}}if(t==="authmechanism"&&!d.has(r)){throw new i(`Value for authMechanism must be one of: ${Array.from(d).join(", ")}, found: ${r}`)}if(t==="readpreference"&&!a.isValid(r)){throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`")}if(t==="zlibcompressionlevel"&&(r<-1||r>9)){throw new i("zlibCompressionLevel must be an integer between -1 and 9")}if(t==="compressors"||t==="zlibcompressionlevel"){e.compression=e.compression||{};e=e.compression}if(t==="authmechanismproperties"){if(typeof r.SERVICE_NAME==="string")e.gssapiServiceName=r.SERVICE_NAME;if(typeof r.SERVICE_REALM==="string")e.gssapiServiceRealm=r.SERVICE_REALM;if(typeof r.CANONICALIZE_HOST_NAME!=="undefined"){e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME}}if(t==="readpreferencetags"){r=Array.isArray(r)?splitArrayOfMultipleReadPreferenceTags(r):[r]}if(n.caseTranslate&&g[t]){e[g[t]]=r;return}e[t]=r}const p=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function splitArrayOfMultipleReadPreferenceTags(e){const t=[];for(let r=0;r{const n=e.split(":");t[r][n[0]]=n[1]}))}return t}function applyAuthExpectations(e){if(e.options==null){return}const t=e.options;const r=t.authsource||t.authSource;if(r!=null){e.auth=Object.assign({},e.auth,{db:r})}const n=t.authmechanism||t.authMechanism;if(n!=null){if(p.has(n)&&(!e.auth||e.auth.username==null)){throw new i(`Username required for mechanism \`${n}\``)}if(n==="GSSAPI"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null){throw new i(`Password not allowed for mechanism \`${n}\``)}if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="PLAIN"){if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"$external"})}}}if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"admin"})}return e}function parseQueryString(e,t){const r={};let n=o.parse(e);checkTLSOptions(n);for(const e in n){const o=n[e];if(o===""||o==null){throw new i("Incomplete key value pair for option")}const s=e.toLowerCase();if(s==="serverapi"){throw new i("URI cannot contain `serverApi`, it can only be passed to the client")}const a=l.has(s)?o:parseQueryStringItemValue(s,o);applyConnectionStringOption(r,s,a,t)}if(r.wtimeout&&r.wtimeoutms){delete r.wtimeout;A("Unsupported option `wtimeout` specified")}return Object.keys(r).length?r:null}function translateTLSOptions(e){if(e.tls){e.ssl=e.tls}if(e.tlsInsecure){e.checkServerIdentity=false;e.sslValidate=false}else{Object.assign(e,{checkServerIdentity:e.tlsAllowInvalidHostnames?false:true,sslValidate:e.tlsAllowInvalidCertificates?false:true})}if(e.tlsCAFile){e.ssl=true;e.sslCA=e.tlsCAFile}if(e.tlsCertificateKeyFile){e.ssl=true;if(e.tlsCertificateFile){e.sslCert=e.tlsCertificateFile;e.sslKey=e.tlsCertificateKeyFile}else{e.sslKey=e.tlsCertificateKeyFile;e.sslCert=e.tlsCertificateKeyFile}}if(e.tlsCertificateKeyFilePassword){e.ssl=true;e.sslPass=e.tlsCertificateKeyFilePassword}return e}function checkTLSOptions(e){const t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1)){throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.")}const r=assertTlsOptionsAreEqual("tls",e,t);const n=assertTlsOptionsAreEqual("ssl",e,t);if(r!=null&&n!=null){if(r!==n){throw new i("All values of `tls` and `ssl` must be the same.")}}}function assertTlsOptionsAreEqual(e,t,r){const n=r.indexOf(e)!==-1;let o;if(Array.isArray(t[e])){o=t[e][0]}else{o=t[e]}if(n){if(Array.isArray(t[e])){const r=t[e][0];t[e].forEach((t=>{if(t!==r){throw new i(`All values of ${e} must be the same.`)}}))}}return o}const E="mongodb";const m="mongodb+srv";const C=[E,m];function parseConnectionString(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},{caseTranslate:true},t);try{n.parse(e)}catch(e){return r(new i("URI malformed, cannot be parsed"))}const s=e.match(c);if(!s){return r(new i("Invalid connection string"))}const a=s[1];if(C.indexOf(a)===-1){return r(new i("Invalid protocol provided"))}const A=s[4].split("?");const l=A.length>0?A[0]:null;const u=A.length>1?A[1]:null;let h;try{h=parseQueryString(u,t)}catch(e){return r(e)}h=Object.assign({},h,t);if(Object.keys(h).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(a===m){return parseSrvConnectionString(e,h,r)}const d={username:null,password:null,db:l&&l!==""?o.unescape(l):null};if(h.auth){if(h.auth.username)d.username=h.auth.username;if(h.auth.user)d.username=h.auth.user;if(h.auth.password)d.password=h.auth.password}else{if(h.username)d.username=h.username;if(h.user)d.username=h.user;if(h.password)d.password=h.password}if(s[4].split("?")[0].indexOf("@")!==-1){return r(new i("Unescaped slash in userinfo section"))}const g=s[3].split("@");if(g.length>2){return r(new i("Unescaped at-sign in authority section"))}if(g[0]==null||g[0]===""){return r(new i("No username provided in authority section"))}if(g.length>1){const e=g.shift().split(":");if(e.length>2){return r(new i("Unescaped colon in authority section"))}if(e[0]===""){return r(new i("Invalid empty username provided"))}if(!d.username)d.username=o.unescape(e[0]);if(!d.password)d.password=e[1]?o.unescape(e[1]):null}let p=null;const E=g.shift().split(",").map((e=>{let t=n.parse(`mongodb://${e}`);if(t.path==="/:"){p=new i("Double colon in host identifier");return null}if(e.match(/\.sock/)){t.hostname=o.unescape(e);t.port=null}if(Number.isNaN(t.port)){p=new i("Invalid port (non-numeric string)");return}const r={host:t.hostname,port:t.port?parseInt(t.port):27017};if(r.port===0){p=new i("Invalid port (zero) with hostname");return}if(r.port>65535){p=new i("Invalid port (larger than 65535) with hostname");return}if(r.port<0){p=new i("Invalid port (negative number)");return}return r})).filter((e=>!!e));if(p){return r(p)}if(E.length===0||E[0].host===""||E[0].host===null){return r(new i("No hostname or hostnames provided in connection string"))}const I=!!h.directConnection;if(I&&E.length!==1){return r(new i("directConnection option requires exactly one host"))}if(h.directConnection==null&&E.length===1&&h.replicaSet==null){h.directConnection=true}const y={hosts:E,auth:d.db||d.username?d:null,options:Object.keys(h).length?h:null};if(y.auth&&y.auth.db){y.defaultDatabase=y.auth.db}else{y.defaultDatabase="test"}y.options=translateTLSOptions(y.options);try{applyAuthExpectations(y)}catch(e){return r(e)}r(null,y)}e.exports=parseConnectionString},1178:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6113);const s=r(3182)(require);const uuidV4=()=>{const e=o.randomBytes(16);e[6]=e[6]&15|64;e[8]=e[8]&63|128;return e};function relayEvents(e,t,r){r.forEach((r=>e.on(r,(e=>t.emit(r,e)))))}function retrieveKerberos(){let e;try{e=s("kerberos")}catch(e){if(e.code==="MODULE_NOT_FOUND"){throw new Error("The `kerberos` module was not found. Please install it and try again.")}throw e}return e}const noEJSONError=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function retrieveEJSON(){let e=s("mongodb-extjson");if(!e){e={parse:noEJSONError,deserialize:noEJSONError,serialize:noEJSONError,stringify:noEJSONError,setBSONModule:noEJSONError,BSON:noEJSONError}}return e}function maxWireVersion(e){if(e){if(e.ismaster){return e.ismaster.maxWireVersion}if(typeof e.lastIsMaster==="function"){const t=e.lastIsMaster();if(t){return t.maxWireVersion}}if(e.description){return e.description.maxWireVersion}}return 0}function collationNotSupported(e,t){return t&&t.collation&&maxWireVersion(e)<5}function isPromiseLike(e){return e&&typeof e.then==="function"}function eachAsync(e,t,r){e=e||[];let n=0;let o=0;for(n=0;ne===t[r]))}function tagsStrictEqual(e,t){const r=Object.keys(e);const n=Object.keys(t);return r.length===n.length&&r.every((r=>t[r]===e[r]))}function errorStrictEqual(e,t){if(e===t){return true}if(e==null&&t!=null||e!=null&&t==null){return false}if(e.constructor.name!==t.constructor.name){return false}if(e.message!==t.message){return false}return true}function makeStateMachine(e){return function stateTransition(t,r){const n=e[t.s.state];if(n&&n.indexOf(r)<0){throw new TypeError(`illegal state transition from [${t.s.state}] => [${r}], allowed: [${n}]`)}t.emit("stateChanged",t.s.state,r);t.s.state=r}}function makeClientMetadata(e){e=e||{};const t={driver:{name:"nodejs",version:r(1693).i8},os:{type:n.type(),name:process.platform,architecture:process.arch,version:n.release()},platform:`'Node.js ${process.version}, ${n.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo){if(e.driverInfo.name){t.driver.name=`${t.driver.name}|${e.driverInfo.name}`}if(e.driverInfo.version){t.version=`${t.driver.version}|${e.driverInfo.version}`}if(e.driverInfo.platform){t.platform=`${t.platform}|${e.driverInfo.platform}`}}if(e.appname){const r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}const noop=()=>{};e.exports={uuidV4:uuidV4,relayEvents:relayEvents,collationNotSupported:collationNotSupported,retrieveEJSON:retrieveEJSON,retrieveKerberos:retrieveKerberos,maxWireVersion:maxWireVersion,isPromiseLike:isPromiseLike,eachAsync:eachAsync,eachAsyncSeries:eachAsyncSeries,isUnifiedTopology:isUnifiedTopology,arrayStrictEqual:arrayStrictEqual,tagsStrictEqual:tagsStrictEqual,errorStrictEqual:errorStrictEqual,makeStateMachine:makeStateMachine,makeClientMetadata:makeClientMetadata,noop:noop}},7276:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(8988).Msg;const s=r(3111).MongoError;const i=r(7272).getReadPreference;const a=r(7272).isSharded;const A=r(7272).databaseNamespace;const c=r(1707).isTransactionCommand;const l=r(5474).applySession;const u=r(3111).MongoNetworkError;const h=r(1178).maxWireVersion;function isClientEncryptionEnabled(e){const t=h(e);return t&&e.autoEncrypter}function command(e,t,r,n,o){if(typeof n==="function")o=n,n={};n=n||{};if(r==null){return o(new s(`command ${JSON.stringify(r)} does not return a cursor`))}if(!isClientEncryptionEnabled(e)){_command(e,t,r,n,o);return}const i=h(e);if(typeof i!=="number"||i<8){o(new s("Auto-encryption requires a minimum MongoDB version of 4.2"));return}_cryptCommand(e,t,r,n,o)}function _command(e,t,r,h,d){const g=e.s.bson;const p=e.s.pool;const E=i(r,h);const m=supportsOpMsg(e);const C=h.session;const I=e.clusterTime;let y=I;let B=Object.assign({},r);const Q=h.serverApi;if(Q){B.apiVersion=Q.version||Q;if(Q.strict!=null){B.apiStrict=Q.strict}if(Q.deprecationErrors!=null){B.apiDeprecationErrors=Q.deprecationErrors}}if(hasSessionSupport(e)&&C){const e=C.clusterTime;if(I&&I.clusterTime&&e&&e.clusterTime&&e.clusterTime.greaterThan(I.clusterTime)){y=e}if(!C.transaction.isActive&&C.transaction.isPinned&&!B.startTransaction&&!B.commitTransaction){C.transaction.unpinServer()}const t=l(C,B,h);if(t){return d(t)}}if(y){B.$clusterTime=y}if(a(e)&&!m&&E&&E.mode!=="primary"){B={$query:B,$readPreference:E.toJSON()}}const b=Object.assign({command:true,numberToSkip:0,numberToReturn:-1,checkKeys:false},h);b.slaveOk=E.slaveOk();const w=`${A(t)}.$cmd`;const S=m?new o(g,w,B,b):new n(g,w,B,b);const v=C&&(C.inTransaction()||c(B));const R=v?function(e){if(e&&e instanceof u&&!e.hasErrorLabel("TransientTransactionError")){e.addErrorLabel("TransientTransactionError")}if(!r.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")){C.transaction.unpinServer()}return d.apply(null,arguments)}:d;try{p.write(S,b,R)}catch(e){R(e)}}function hasSessionSupport(e){if(e==null)return false;if(e.description){return e.description.maxWireVersion>=6}return e.ismaster==null?false:e.ismaster.maxWireVersion>=6}function supportsOpMsg(e){const t=e.ismaster?e.ismaster:e.description;if(t==null){return false}return t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}function _cryptCommand(e,t,r,n,o){const s=e.autoEncrypter;function commandResponseHandler(e,t){if(e||t==null){o(e,t);return}s.decrypt(t.result,n,((e,r)=>{if(e){o(e,null);return}t.result=r;t.message.documents=[r];o(null,t)}))}s.encrypt(t,r,n,((r,s)=>{if(r){o(r,null);return}_command(e,t,s,n,commandResponseHandler)}))}e.exports=command},7793:(e,t,r)=>{"use strict";const n=r(7746).retrieveSnappy();const o=r(9796);const s={snappy:1,zlib:2};const i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function compress(e,t,r){switch(e.options.agreedCompressor){case"snappy":n.compress(t,r);break;case"zlib":var s={};if(e.options.zlibCompressionLevel){s.level=e.options.zlibCompressionLevel}o.deflate(t,s,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}function decompress(e,t,r){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:n.uncompress(t,r);break;case s.zlib:o.inflate(t,r);break;default:r(null,t)}}e.exports={compressorIDs:s,uncompressibleCommands:i,compress:compress,decompress:decompress}},7161:e=>{"use strict";const t="2.6";const r="5.0";const n=2;const o=13;e.exports={MIN_SUPPORTED_SERVER_VERSION:t,MAX_SUPPORTED_SERVER_VERSION:r,MIN_SUPPORTED_WIRE_VERSION:n,MAX_SUPPORTED_WIRE_VERSION:o}},1971:(e,t,r)=>{"use strict";const n=r(9814).GetMore;const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=o();const A=a.Long;const c=r(7272).collectionNamespace;const l=r(1178).maxWireVersion;const u=r(7272).applyCommonQueryOptions;const h=r(7276);function getMore(e,t,r,o,a,d){a=a||{};const g=l(e);function queryCallback(e,t){if(e)return d(e);const n=t.message;if(n.cursorNotFound){return d(new i("cursor killed or timed out"),null)}if(g<4){const e=typeof n.cursorId==="number"?A.fromNumber(n.cursorId):n.cursorId;r.documents=n.documents;r.cursorId=e;d(null,null,n.connection);return}if(n.documents[0].ok===0){return d(new s(n.documents[0]))}const o=typeof n.documents[0].cursor.id==="number"?A.fromNumber(n.documents[0].cursor.id):n.documents[0].cursor.id;r.documents=n.documents[0].cursor.nextBatch;r.cursorId=o;d(null,n.documents[0],n.connection)}if(g<4){const s=e.s.bson;const i=new n(s,t,r.cursorId,{numberToReturn:o});const a=u({},r);e.s.pool.write(i,a,queryCallback);return}const p=r.cursorId instanceof A?r.cursorId:A.fromNumber(r.cursorId);const E={getMore:p,collection:c(t),batchSize:Math.abs(o)};if(r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS==="number"){E.maxTimeMS=r.cmd.maxAwaitTimeMS}const m=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},a);if(r.session){m.session=r.session}h(e,t,E,m,queryCallback)}e.exports=getMore},9206:(e,t,r)=>{"use strict";const n=r(779);e.exports={insert:function insert(e,t,r,o,s){n(e,"insert","documents",t,r,o,s)},update:function update(e,t,r,o,s){n(e,"update","updates",t,r,o,s)},remove:function remove(e,t,r,o,s){n(e,"delete","deletes",t,r,o,s)},killCursors:r(6044),getMore:r(1971),query:r(1820),command:r(7276)}},6044:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(3111).MongoError;const s=r(3111).MongoNetworkError;const i=r(7272).collectionNamespace;const a=r(1178).maxWireVersion;const A=r(1178).emitWarning;const c=r(7276);function killCursors(e,t,r,l,u){if(typeof l==="function"){u=l;l={}}u=typeof u==="function"?u:()=>{};const h=r.cursorId;if(a(e)<4){const o=e.s.bson;const s=e.s.pool;const i=new n(o,t,[h]);const a={immediateRelease:true,noResponse:true};if(typeof r.session==="object"){a.session=r.session}if(s&&s.isConnected()){try{s.write(i,a,u)}catch(e){if(typeof u==="function"){u(e,null)}else{A(e)}}}return}const d={killCursors:i(t),cursors:[h]};const g=l||{};if(typeof r.session==="object")g.session=r.session;c(e,t,d,g,((e,t)=>{if(e){return u(e)}const r=t.message;if(r.cursorNotFound){return u(new s("cursor killed or timed out"),null)}if(!Array.isArray(r.documents)||r.documents.length===0){return u(new o(`invalid killCursors result returned for cursor id ${h}`))}u(null,r.documents[0])}))}e.exports=killCursors},1820:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(3111).MongoError;const s=r(7272).getReadPreference;const i=r(7272).collectionNamespace;const a=r(7272).isSharded;const A=r(1178).maxWireVersion;const c=r(7272).applyCommonQueryOptions;const l=r(7276);const u=r(1371).decorateWithExplain;const h=r(5293).Explain;function query(e,t,r,n,i,a){i=i||{};if(n.cursorId!=null){return a()}if(r==null){return a(new o(`command ${JSON.stringify(r)} does not return a cursor`))}if(A(e)<4){const o=prepareLegacyFindQuery(e,t,r,n,i);const s=c({},n);if(typeof o.documentsReturnedIn==="string"){s.documentsReturnedIn=o.documentsReturnedIn}e.s.pool.write(o,s,a);return}const d=s(r,i);let g=prepareFindCommand(e,t,r,n,i);try{const e=h.fromOptions(i);if(e){g=u(g,e)}}catch(e){return a(e)}r.virtual=false;const p=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:d.slaveOk()},i);if(r.readPreference){p.readPreference=d}if(n.session){p.session=n.session}l(e,t,g,p,a)}function prepareFindCommand(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;const o={find:i(t)};if(r.query){if(r.query["$query"]){o.filter=r.query["$query"]}else{o.filter=r.query}}let s=r.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];if(t==="asc"){t=1}else if(t==="desc"){t=-1}e[s[0]]=t}else{for(let t=0;t0&&i.batchSize===0){u=i.limit}else{u=i.batchSize}const h=i.skip||0;const d={};if(a(e)&&l){d["$readPreference"]=l.toJSON()}if(r.sort)d["$orderby"]=r.sort;if(r.hint)d["$hint"]=r.hint;if(r.snapshot)d["$snapshot"]=r.snapshot;if(typeof r.returnKey!=="undefined")d["$returnKey"]=r.returnKey;if(r.maxScan)d["$maxScan"]=r.maxScan;if(r.min)d["$min"]=r.min;if(r.max)d["$max"]=r.max;if(typeof r.showDiskLoc!=="undefined")d["$showDiskLoc"]=r.showDiskLoc;if(r.comment)d["$comment"]=r.comment;if(r.maxTimeMS)d["$maxTimeMS"]=r.maxTimeMS;if(A.explain!==undefined){u=-Math.abs(r.limit||0);d["$explain"]=true}d["$query"]=r.query;if(r.readConcern&&r.readConcern.level!=="local"){throw new o(`server find command does not support a readConcern level of ${r.readConcern.level}`)}if(r.readConcern){r=Object.assign({},r);delete r["readConcern"]}const g=typeof A.serializeFunctions==="boolean"?A.serializeFunctions:false;const p=typeof A.ignoreUndefined==="boolean"?A.ignoreUndefined:false;const E=new n(c,t,d,{numberToSkip:h,numberToReturn:u,pre32Limit:typeof r.limit!=="undefined"?r.limit:undefined,checkKeys:false,returnFieldSelector:r.fields,serializeFunctions:g,ignoreUndefined:p});if(typeof r.tailable==="boolean")E.tailable=r.tailable;if(typeof r.oplogReplay==="boolean")E.oplogReplay=r.oplogReplay;if(typeof r.noCursorTimeout==="boolean")E.noCursorTimeout=r.noCursorTimeout;if(typeof r.awaitData==="boolean")E.awaitData=r.awaitData;if(typeof r.partial==="boolean")E.partial=r.partial;E.slaveOk=l.slaveOk();return E}e.exports=query},7272:(e,t,r)=>{"use strict";const n=r(4485);const o=r(3111).MongoError;const s=r(2291).ServerType;const i=r(7962).TopologyDescription;const a=16;const A=9;var c={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};var getReadPreference=function(e,t){var r=e.readPreference||new n("primary");if(t.readPreference){r=t.readPreference}if(typeof r==="string"){r=new n(r)}if(!(r instanceof n)){throw new o("read preference must be a ReadPreference instance")}return r};var parseHeader=function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}};function applyCommonQueryOptions(e,t){Object.assign(e,{raw:typeof t.raw==="boolean"?t.raw:false,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,monitoring:typeof t.monitoring==="boolean"?t.monitoring:false,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false});if(typeof t.socketTimeout==="number"){e.socketTimeout=t.socketTimeout}if(t.session){e.session=t.session}if(typeof t.documentsReturnedIn==="string"){e.documentsReturnedIn=t.documentsReturnedIn}return e}function isSharded(e){if(e.type==="mongos")return true;if(e.description&&e.description.type===s.Mongos){return true}if(e.description&&e.description instanceof i){const t=Array.from(e.description.servers.values());return t.some((e=>e.type===s.Mongos))}return false}function databaseNamespace(e){return e.split(".")[0]}function collectionNamespace(e){return e.split(".").slice(1).join(".")}e.exports={getReadPreference:getReadPreference,MESSAGE_HEADER_SIZE:a,COMPRESSION_DETAILS_SIZE:A,opcodes:c,parseHeader:parseHeader,applyCommonQueryOptions:applyCommonQueryOptions,isSharded:isSharded,databaseNamespace:databaseNamespace,collectionNamespace:collectionNamespace}},779:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(7272).collectionNamespace;const s=r(7276);const i=r(1371).decorateWithExplain;const a=r(5293).Explain;function writeCommand(e,t,r,A,c,l,u){if(c.length===0)throw new n(`${t} must contain at least one document`);if(typeof l==="function"){u=l;l={}}l=l||{};const h=typeof l.ordered==="boolean"?l.ordered:true;const d=l.writeConcern;let g={};g[t]=o(A);g[r]=c;g.ordered=h;if(d&&Object.keys(d).length>0){g.writeConcern=d}if(l.collation){for(let e=0;e{"use strict";const n=r(2781).Transform;const o=r(2781).PassThrough;const s=r(3837).deprecate;const i=r(1371).handleCallback;const a=r(3994).ReadPreference;const A=r(3994).MongoError;const c=r(4847).CoreCursor;const l=r(4847).CursorState;const u=r(3994).BSON.Map;const h=r(1371).maybePromise;const d=r(2548);const g=r(1371).formattedOrderClause;const p=r(5293).Explain;const E=r(1018).Aspect;const m=r(3554).each;const C=r(7885);const I=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];const y=["numberOfRetries","tailableRetryInterval"];class Cursor extends c{constructor(e,t,r,n){super(e,t,r,n);if(this.operation){n=this.operation.options}const o=n.numberOfRetries||5;const s=n.tailableRetryInterval||500;const i=o;const a=n.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!n.explicitlyIgnoreSession};if(!n.explicitlyIgnoreSession&&n.session){this.cursorState.session=n.session}if(this.options.noCursorTimeout===true){this.addCursorFlag("noCursorTimeout",true)}let A=1e3;if(this.cmd.cursor&&this.cmd.cursor.batchSize){A=this.cmd.cursor.batchSize}else if(n.cursor&&n.cursor.batchSize){A=n.cursor.batchSize}else if(typeof n.batchSize==="number"){A=n.batchSize}this.setCursorBatchSize(A)}get readPreference(){if(this.operation){return this.operation.readPreference}return this.options.readPreference}get sortValue(){return this.cmd.sort}set session(e){this.cursorState.session=e}_initializeCursor(e){if(this.operation&&this.operation.session!=null){this.cursorState.session=this.operation.session}else{if(!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()){this.cursorState.session=this.topology.startSession({owner:this});if(this.operation){this.operation.session=this.cursorState.session}}}super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}return h(this,e,(e=>{const t=this;if(t.isNotified()){return e(null,false)}t._next(((r,n)=>{if(r)return e(r);if(n==null||t.s.state===Cursor.CLOSED||t.isDead()){return e(null,false)}t.s.state=l.OPEN;t.cursorState.cursorIndex--;if(t.cursorState.limit>0){t.cursorState.currentLimit--}e(null,true)}))}))}next(e){return h(this,e,(e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead()){e(A.create({message:"Cursor is closed",driver:true}));return}if(t.s.state===l.INIT&&t.cmd.sort){try{t.cmd.sort=g(t.cmd.sort)}catch(t){return e(t)}}t._next(((r,n)=>{if(r)return e(r);t.s.state=l.OPEN;e(null,n)}))}))}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.query=e;return this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxScan=e;return this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.hint=e;return this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.min=e;return this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.max=e;return this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.returnKey=e;return this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.showDiskLoc=e;return this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.snapshot=e;return this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(y.indexOf(e)===-1){throw A.create({message:`option ${e} is not a supported option ${y}`,driver:true})}this.s[e]=t;if(e==="numberOfRetries")this.s.currentNumberOfRetries=t;return this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(I.indexOf(e)===-1){throw A.create({message:`flag ${e} is not a supported flag ${I}`,driver:true})}if(typeof t!=="boolean"){throw A.create({message:`flag ${e} must be a boolean value`,driver:true})}this.cmd[e]=t;return this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(e[0]!=="$"){throw A.create({message:`${e} is not a valid query modifier`,driver:true})}const r=e.substr(1);this.cmd[r]=t;if(r==="orderby")this.cmd.sort=this.cmd[r];return this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.comment=e;return this}maxAwaitTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxAwaitTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxAwaitTimeMS=e;return this}maxTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxTimeMS=e;return this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.fields=e;return this}sort(e,t){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support sorting",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}let r=e;if(Array.isArray(r)&&Array.isArray(r[0])){r=new u(r.map((e=>{const t=[e[0],null];if(e[1]==="asc"){t[1]=1}else if(e[1]==="desc"){t[1]=-1}else if(e[1]===1||e[1]===-1||e[1].$meta){t[1]=e[1]}else{throw new A("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}return t})))}if(t!=null){r=[[e,t]]}this.cmd.sort=r;return this}batchSize(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support batchSize",driver:true})}if(this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"batchSize requires an integer",driver:true})}this.cmd.batchSize=e;this.setCursorBatchSize(e);return this}collation(e){this.cmd.collation=e;return this}limit(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support limit",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"limit requires an integer",driver:true})}this.cmd.limit=e;this.setCursorLimit(e);return this}skip(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support skip",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"skip requires an integer",driver:true})}this.cmd.skip=e;this.setCursorSkip(e);return this}each(e){this.rewind();this.s.state=l.INIT;m(this,e)}forEach(e,t){this.rewind();this.s.state=l.INIT;if(typeof t==="function"){m(this,((r,n)=>{if(r){t(r);return false}if(n!=null){try{e(n)}catch(e){t(e);return false}return true}if(n==null&&t){const e=t;t=null;e(null);return false}}))}else{return new this.s.promiseLibrary(((t,r)=>{m(this,((n,o)=>{if(n){r(n);return false}else if(o==null){t(null);return false}else{try{e(o)}catch(e){r(e);return false}return true}}))}))}}setReadPreference(e){if(this.s.state!==l.INIT){throw A.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof a){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new a(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}toArray(e){if(this.options.tailable){throw A.create({message:"Tailable cursor cannot be converted to array",driver:true})}return h(this,e,(e=>{const t=this;const r=[];t.rewind();t.s.state=l.INIT;const fetchDocs=()=>{t._next(((n,o)=>{if(n){return i(e,n)}if(o==null){return t.close({skipKillCursors:true},(()=>i(e,null,r)))}r.push(o);if(t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(r,e)}fetchDocs()}))};fetchDocs()}))}count(e,t,r){if(this.cmd.query==null)throw A.create({message:"count can only be used with find command",driver:true});if(typeof t==="function")r=t,t={};t=t||{};if(typeof e==="function"){r=e;e=true}if(this.cursorState.session){t=Object.assign({},t,{session:this.cursorState.session})}const n=new C(this,e,t);return d(this.topology,n,r)}close(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{skipKillCursors:false},e);return h(this,t,(t=>{this.s.state=l.CLOSED;if(!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=r=>e(t(r))}else{this.cursorState.transforms={doc:e}}return this}isClosed(){return this.isDead()}destroy(e){if(e)this.emit("error",e);this.pause();this.close()}stream(e){this.cursorState.streamOptions=e||{};return this}transformStream(e){const t=e||{};if(typeof t.transform==="function"){const e=new n({objectMode:true,transform:function(e,r,n){this.push(t.transform(e));n()}});return this.pipe(e)}return this.pipe(new o({objectMode:true}))}explain(e,t){if(typeof e==="function")t=e,e=true;if(e===undefined)e=true;if(!this.operation||!this.operation.hasAspect(E.EXPLAINABLE)){throw new A("This command cannot be explained")}this.operation.explain=new p(e);return h(this,t,(e=>{c.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}Cursor.prototype.maxTimeMs=Cursor.prototype.maxTimeMS;s(Cursor.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");s(Cursor.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");s(Cursor.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");e.exports=Cursor},6662:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(3837).inherits;const s=r(1371).getSingleProperty;const i=r(538);const a=r(1371).handleCallback;const A=r(1371).filterOptions;const c=r(1371).toError;const l=r(3994).ReadPreference;const u=r(3994).MongoError;const h=r(3994).ObjectID;const d=r(3994).Logger;const g=r(5193);const p=r(1371).conditionallyMergeWriteConcern;const E=r(1371).executeLegacyOperation;const m=r(1117);const C=r(3837).deprecate;const I=r(1371).deprecateOptions;const y=r(1371).MongoDBNamespace;const B=r(147);const Q=r(2481);const b=r(7289);const w=r(7429);const S=r(2226).createListener;const v=r(2226).ensureIndex;const R=r(2226).evaluate;const k=r(2226).profilingInfo;const D=r(2226).validateDatabaseName;const N=r(1554);const T=r(7057);const O=r(286);const _=r(499);const M=r(1363);const L=r(5561);const F=r(6394);const U=r(2360).DropCollectionOperation;const P=r(2360).DropDatabaseOperation;const G=r(1681);const Y=r(4245);const V=r(840);const W=r(3969);const J=r(1969);const q=r(2808);const j=r(6301);const z=r(2548);const $=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function Db(e,t,r){r=r||{};if(!(this instanceof Db))return new Db(e,t,r);n.call(this);const o=r.promiseLibrary||Promise;r=A(r,$);r.promiseLibrary=o;this.s={dbCache:{},children:[],topology:t,options:r,logger:d("Db",r),bson:t?t.bson:null,readPreference:l.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||h,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:o,noListener:typeof r.noListener==="boolean"?r.noListener:false,readConcern:b.fromOptions(r),writeConcern:Q.fromOptions(r),namespace:new y(e)};D(e);s(this,"serverConfig",this.s.topology);s(this,"bufferMaxEntries",this.s.bufferMaxEntries);s(this,"databaseName",this.s.namespace.db);if(r.parentDb)return;if(this.s.noListener)return;t.on("error",S(this,"error",this));t.on("timeout",S(this,"timeout",this));t.on("close",S(this,"close",this));t.on("parseError",S(this,"parseError",this));t.once("open",S(this,"open",this));t.once("fullsetup",S(this,"fullsetup",this));t.once("all",S(this,"all",this));t.on("reconnect",S(this,"reconnect",this))}o(Db,n);Db.prototype.on=C((function(){return Db.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Db.prototype.once=C((function(){return Db.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(Db.prototype,"topology",{enumerable:true,get:function(){return this.s.topology}});Object.defineProperty(Db.prototype,"options",{enumerable:true,get:function(){return this.s.options}});Object.defineProperty(Db.prototype,"slaveOk",{enumerable:true,get:function(){if(this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")){return true}return false}});Object.defineProperty(Db.prototype,"readConcern",{enumerable:true,get:function(){return this.s.readConcern}});Object.defineProperty(Db.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return l.primary}return this.s.readPreference}});Object.defineProperty(Db.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(Db.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Db.prototype.command=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);const n=new M(this,e,t);return z(this.s.topology,n,r)};Db.prototype.aggregate=function(e,t,r){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}const n=new w(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Db.prototype.admin=function(){const e=r(3238);return new e(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];Db.prototype.collection=I({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t=Object.assign({},t);t.promiseLibrary=this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;if(this.s.options.ignoreUndefined){t.ignoreUndefined=this.s.options.ignoreUndefined}for(const e of K){if(!(e in t)&&this.s.options[e]!==undefined){t[e]=this.s.options[e]}}t=p(t,this.s.options);if(t==null||!t.strict){try{const n=new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);if(r)r(null,n);return n}catch(e){if(e instanceof u&&r)return r(e);throw e}}if(typeof r!=="function"){throw c(`A callback is required in strict mode. While getting collection ${e}`)}if(this.serverConfig&&this.serverConfig.isDestroyed()){return r(new u("topology was destroyed"))}const n=Object.assign({},t,{nameOnly:true});this.listCollections({name:e},n).toArray(((n,o)=>{if(n!=null)return a(r,n,null);if(o.length===0)return a(r,c(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(r,null,new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(n){return a(r,n,null)}}))}));Db.prototype.createCollection=I({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;const n=new L(this,e,t);return z(this.s.topology,n,r)}));Db.prototype.stats=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={dbStats:true};if(e["scale"]!=null)r["scale"]=e["scale"];if(e.readPreference==null&&this.s.readPreference){e.readPreference=this.s.readPreference}const n=new _(this,e,null,r);return z(this.s.topology,n,t)};Db.prototype.listCollections=function(e,t){e=e||{};t=t||{};return new i(this.s.topology,new V(this,e,t),t)};Db.prototype.eval=C((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():t;r=o.length?o.shift()||{}:{};return E(this.s.topology,R,[this,e,t,r,n])}),"Db.eval is deprecated as of MongoDB version 3.2");Db.prototype.renameCollection=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r,{readPreference:l.PRIMARY});r.new_collection=true;const o=new q(this.collection(e),t,r);return z(this.s.topology,o,n)};Db.prototype.dropCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new U(this,e,t);return z(this.s.topology,n,r)};Db.prototype.dropDatabase=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new P(this,e);return z(this.s.topology,r,t)};Db.prototype.collections=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new O(this,e);return z(this.s.topology,r,t)};Db.prototype.executeDbAdminCommand=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.readPreference=l.resolve(this,t);const n=new G(this,e,t);return z(this.s.topology,n,r)};Db.prototype.createIndex=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r?Object.assign({},r):{};const o=new F(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.ensureIndex=C((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return E(this.s.topology,v,[this,e,t,r,n])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");Db.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};Db.prototype.addUser=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}const o=new T(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.removeUser=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new J(this,e,t);return z(this.s.topology,n,r)};Db.prototype.setProfilingLevel=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new j(this,e,t);return z(this.s.topology,n,r)};Db.prototype.profilingInfo=C((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return E(this.s.topology,k,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly.");Db.prototype.profilingLevel=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new W(this,e);return z(this.s.topology,r,t)};Db.prototype.indexInformation=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new Y(this,e,t);return z(this.s.topology,n,r)};Db.prototype.unref=function(){this.s.topology.unref()};Db.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Db.prototype.getLogger=function(){return this.s.logger};Db.SYSTEM_NAMESPACE_COLLECTION=B.SYSTEM_NAMESPACE_COLLECTION;Db.SYSTEM_INDEX_COLLECTION=B.SYSTEM_INDEX_COLLECTION;Db.SYSTEM_PROFILE_COLLECTION=B.SYSTEM_PROFILE_COLLECTION;Db.SYSTEM_USER_COLLECTION=B.SYSTEM_USER_COLLECTION;Db.SYSTEM_COMMAND_COLLECTION=B.SYSTEM_COMMAND_COLLECTION;Db.SYSTEM_JS_COLLECTION=B.SYSTEM_JS_COLLECTION;e.exports=Db},8275:(e,t,r)=>{"use strict";let n;let o;let s;function loadCollection(){if(!n){n=r(5193)}return n}function loadCursor(){if(!o){o=r(7159)}return o}function loadDb(){if(!s){s=r(6662)}return s}e.exports={loadCollection:loadCollection,loadCursor:loadCursor,loadDb:loadDb}},3012:(e,t,r)=>{"use strict";const n=r(1545);const o=r(7746).retrieveBSON();const s=r(3111).MongoError;let i=undefined;try{i=r(5764)}catch(e){throw new s("Auto-encryption requested, but the module is not installed. "+"Please add `mongodb-client-encryption` as a dependency of your project")}if(i===undefined||typeof i.extension!=="function"){throw new s("loaded version of `mongodb-client-encryption` does not have property `extension`. "+"Please make sure you are loading the correct version of `mongodb-client-encryption`")}const a=i.extension(r(5517)).AutoEncrypter;const A=Symbol("internalClient");class Encrypter{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption;this.needsConnecting=false;if(t.maxPoolSize===0&&t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=e}else if(t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=this.getInternalClient(e)}if(this.bypassAutoEncryption){t.autoEncryption.metadataClient=undefined}else if(t.maxPoolSize===0){t.autoEncryption.metadataClient=e}else{t.autoEncryption.metadataClient=this.getInternalClient(e)}t.autoEncryption.bson=Encrypter.makeBSON(t);this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[A]){const t={};for(const r of Object.keys(e.s.options)){if(["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(r)!==-1)continue;t[r]=e.s.options[r]}t.minPoolSize=0;const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[A]=new n(e.s.url,t);for(const t of r){for(const r of e.listeners(t)){this[A].on(t,r)}}e.on("newListener",((e,t)=>{this[A].on(e,t)}));this.needsConnecting=true}return this[A]}connectInternalClient(e){if(this.needsConnecting){this.needsConnecting=false;return this[A].connect(e)}return e()}close(e,t,r){this.autoEncrypter.teardown((n=>{if(this[A]&&e!==this[A]){return this[A].close(t,r)}r(n)}))}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:Encrypter}},9386:(e,t,r)=>{"use strict";const n=r(3994).MongoNetworkError;const o=r(8072).MONGODB_ERROR_CODES;const s=new Set([o.HostUnreachable,o.HostNotFound,o.NetworkTimeout,o.ShutdownInProgress,o.PrimarySteppedDown,o.ExceededTimeLimit,o.SocketException,o.NotMaster,o.InterruptedAtShutdown,o.InterruptedDueToReplStateChange,o.NotMasterNoSlaveOk,o.NotMasterOrSecondary,o.StaleShardVersion,o.StaleEpoch,o.StaleConfig,o.RetryChangeStream,o.FailedToSatisfyReadPreference,o.CursorNotFound]);function isResumableError(e,t){if(e instanceof n){return true}if(t>=9){if(e.code===o.CursorNotFound){return true}return e.hasErrorLabel("ResumableChangeStreamError")}return s.has(e.code)}e.exports={GET_MORE_RESUMABLE_CODES:s,isResumableError:isResumableError,MONGODB_ERROR_CODES:o}},8072:e=>{"use strict";const t=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});e.exports=Object.freeze({MONGODB_ERROR_CODES:t})},5293:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class Explain{constructor(e){if(typeof e==="boolean"){this.verbosity=e?"allPlansExecution":"queryPlanner"}else{this.verbosity=e}}static fromOptions(e){if(e==null||e.explain===undefined){return}const t=e.explain;if(typeof t==="boolean"||typeof t==="string"){return new Explain(e.explain)}throw new n(`explain must be a string or a boolean`)}}e.exports={Explain:Explain}},4190:(e,t,r)=>{"use strict";var n=r(2781),o=r(3837);e.exports=GridFSBucketReadStream;function GridFSBucketReadStream(e,t,r,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:false,expectedEnd:0,file:null,options:s,readPreference:r};n.Readable.call(this)}o.inherits(GridFSBucketReadStream,n.Readable);GridFSBucketReadStream.prototype._read=function(){var e=this;if(this.destroyed){return}waitForFile(e,(function(){doRead(e)}))};GridFSBucketReadStream.prototype.start=function(e){throwIfInitialized(this);this.s.options.start=e;return this};GridFSBucketReadStream.prototype.end=function(e){throwIfInitialized(this);this.s.options.end=e;return this};GridFSBucketReadStream.prototype.abort=function(e){var t=this;this.push(null);this.destroyed=true;if(this.s.cursor){this.s.cursor.close((function(r){t.emit("close");e&&e(r)}))}else{if(!this.s.init){t.emit("close")}e&&e()}};function throwIfInitialized(e){if(e.s.init){throw new Error("You cannot change options after the stream has entered"+"flowing mode!")}}function doRead(e){if(e.destroyed){return}e.s.cursor.next((function(t,r){if(e.destroyed){return}if(t){return __handleError(e,t)}if(!r){e.push(null);process.nextTick((()=>{e.s.cursor.close((function(t){if(t){__handleError(e,t);return}e.emit("close")}))}));return}var n=e.s.file.length-e.s.bytesRead;var o=e.s.expected++;var s=Math.min(e.s.file.chunkSize,n);if(r.n>o){var i="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+o;return __handleError(e,new Error(i))}if(r.n0){i["n"]={$gte:a}}}e.s.cursor=e.s.chunks.find(i).sort({n:1});if(e.s.readPreference){e.s.cursor.setReadPreference(e.s.readPreference)}e.s.expectedEnd=Math.ceil(r.length/r.chunkSize);e.s.file=r;try{e.s.bytesToTrim=handleEndOption(e,r,e.s.cursor,e.s.options)}catch(t){return __handleError(e,t)}e.emit("file",r)}))}function waitForFile(e,t){if(e.s.file){return t()}if(!e.s.init){init(e);e.s.init=true}e.once("file",(function(){t()}))}function handleStartOption(e,t,r){if(r&&r.start!=null){if(r.start>t.length){throw new Error("Stream start ("+r.start+") must not be "+"more than the length of the file ("+t.length+")")}if(r.start<0){throw new Error("Stream start ("+r.start+") must not be "+"negative")}if(r.end!=null&&r.endt.length){throw new Error("Stream end ("+n.end+") must not be "+"more than the length of the file ("+t.length+")")}if(n.start<0){throw new Error("Stream end ("+n.end+") must not be "+"negative")}var o=n.start!=null?Math.floor(n.start/t.chunkSize):0;r.limit(Math.ceil(n.end/t.chunkSize)-o);e.s.expectedEnd=Math.ceil(n.end/t.chunkSize);return Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}function __handleError(e,t){e.emit("error",t)}},2573:(e,t,r)=>{"use strict";var n=r(2361).EventEmitter;var o=r(4190);var s=r(1413);var i=r(1371).shallowClone;var a=r(1371).toError;var A=r(3837);var c=r(1371).executeLegacyOperation;const l=r(1371).deprecateOptions;var u={bucketName:"fs",chunkSizeBytes:255*1024};e.exports=GridFSBucket;function GridFSBucket(e,t){n.apply(this);this.setMaxListeners(0);if(t&&typeof t==="object"){t=i(t);var r=Object.keys(u);for(var o=0;o=0){r={uploadDate:1};n=t.revision}else{n=-t.revision-1}}var s={filename:e};t={sort:r,skip:n,start:t&&t.start,end:t&&t.end};return new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)};GridFSBucket.prototype.rename=function(e,t,r){return c(this.s.db.s.topology,_rename,[this,e,t,r],{skipSessions:true})};function _rename(e,t,r,n){var o={_id:t};var s={$set:{filename:r}};e.s._filesCollection.updateOne(o,s,(function(e,r){if(e){return n(e)}if(!r.result.n){return n(a("File with id "+t+" not found"))}n()}))}GridFSBucket.prototype.drop=function(e){return c(this.s.db.s.topology,_drop,[this,e],{skipSessions:true})};GridFSBucket.prototype.getLogger=function(){return this.s.db.s.logger};function _drop(e,t){e.s._filesCollection.drop((function(r){if(r){return t(r)}e.s._chunksCollection.drop((function(e){if(e){return t(e)}return t()}))}))}},1413:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(3994);const s=r(6113);const i=r(2781);const a=r(3837);const A=r(1867).Buffer;const c=r(1371).deprecateOptions;const l=c({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},(function(e,t,r){r=r||{};i.Writable.call(this,r);this.bucket=e;this.chunks=e.s._chunksCollection;this.filename=t;this.files=e.s._filesCollection;this.options=r;this.done=false;this.id=r.id?r.id:o.BSON.ObjectId();this.chunkSizeBytes=this.options.chunkSizeBytes;this.bufToStore=A.alloc(this.chunkSizeBytes);this.length=0;this.md5=!r.disableMD5&&s.createHash("md5");this.n=0;this.pos=0;this.state={streamEnd:false,outstandingRequests:0,errored:false,aborted:false,promiseLibrary:this.bucket.s.promiseLibrary};if(!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=true;var n=this;checkIndexes(this,(function(){n.bucket.s.checkedIndexes=true;n.bucket.emit("index")}))}}));a.inherits(l,i.Writable);l.prototype.write=function(e,t,r){var n=this;return waitForIndexes(this,(function(){return doWrite(n,e,t,r)}))};l.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}if(this.state.aborted){t=new Error("Cannot call abort() on a stream twice");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}this.state.aborted=true;this.chunks.deleteMany({files_id:this.id},(function(t){if(typeof e==="function")e(t)}))};l.prototype.end=function(e,t,r){var n=this;if(typeof e==="function"){r=e,e=null,t=null}else if(typeof t==="function"){r=t,t=null}if(checkAborted(this,r)){return}this.state.streamEnd=true;if(r){this.once("finish",(function(e){r(null,e)}))}if(!e){waitForIndexes(this,(function(){writeRemnant(n)}));return}this.write(e,t,(function(){writeRemnant(n)}))};function __handleError(e,t,r){if(e.state.errored){return}e.state.errored=true;if(r){return r(t)}e.emit("error",t)}function createChunkDoc(e,t,r){return{_id:o.BSON.ObjectId(),files_id:e,n:t,data:r}}function checkChunksIndex(e,t){e.chunks.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={files_id:1,n:1};e.chunks.createIndex(s,{background:false,unique:true},(function(e){if(e){return t(e)}t()}));return}return t(r)}var i=false;o.forEach((function(e){if(e.key){var t=Object.keys(e.key);if(t.length===2&&e.key.files_id===1&&e.key.n===1){i=true}}}));if(i){t()}else{s={files_id:1,n:1};var a=getWriteOptions(e);a.background=false;a.unique=true;e.chunks.createIndex(s,a,(function(e){if(e){return t(e)}t()}))}}))}function checkDone(e,t){if(e.done)return true;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=true;var r=createFilesDoc(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);if(checkAborted(e,t)){return false}e.files.insertOne(r,getWriteOptions(e),(function(n){if(n){return __handleError(e,n,t)}e.emit("finish",r);e.emit("close")}));return true}return false}function checkIndexes(e,t){e.files.findOne({},{_id:1},(function(r,o){if(r){return t(r)}if(o){return t()}e.files.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={filename:1,uploadDate:1};e.files.createIndex(s,{background:false},(function(r){if(r){return t(r)}checkChunksIndex(e,t)}));return}return t(r)}var i=false;o.forEach((function(e){var t=Object.keys(e.key);if(t.length===2&&e.key.filename===1&&e.key.uploadDate===1){i=true}}));if(i){checkChunksIndex(e,t)}else{s={filename:1,uploadDate:1};var a=getWriteOptions(e);a.background=false;e.files.createIndex(s,a,(function(r){if(r){return t(r)}checkChunksIndex(e,t)}))}}))}))}function createFilesDoc(e,t,r,n,o,s,i,a){var A={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:o};if(n){A.md5=n}if(s){A.contentType=s}if(i){A.aliases=i}if(a){A.metadata=a}return A}function doWrite(e,t,r,n){if(checkAborted(e,n)){return false}var o=A.isBuffer(t)?t:A.from(t,r);e.length+=o.length;if(e.pos+o.length0){var l=o.length-s;o.copy(e.bufToStore,e.pos,l,l+a);e.pos+=a;i-=a;if(i===0){if(e.md5){e.md5.update(e.bufToStore)}var u=createChunkDoc(e.id,e.n,A.from(e.bufToStore));++e.state.outstandingRequests;++c;if(checkAborted(e,n)){return false}e.chunks.insertOne(u,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;--c;if(!c){e.emit("drain",u);n&&n();checkDone(e)}}));i=e.chunkSizeBytes;e.pos=0;++e.n}s-=a;a=Math.min(i,s)}return false}function getWriteOptions(e){var t={};if(e.options.writeConcern){t.w=e.options.writeConcern.w;t.wtimeout=e.options.writeConcern.wtimeout;t.j=e.options.writeConcern.j}return t}function waitForIndexes(e,t){if(e.bucket.s.checkedIndexes){return t(false)}e.bucket.once("index",(function(){t(true)}));return true}function writeRemnant(e,t){if(e.pos===0){return checkDone(e,t)}++e.state.outstandingRequests;var r=A.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);if(e.md5){e.md5.update(r)}var n=createChunkDoc(e.id,e.n,r);if(checkAborted(e,t)){return false}e.chunks.insertOne(n,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;checkDone(e)}))}function checkAborted(e,t){if(e.state.aborted){if(typeof t==="function"){t(new Error("this stream has been aborted"))}return true}return false}e.exports=l},3890:(e,t,r)=>{"use strict";var n=r(3994).BSON.Binary,o=r(3994).BSON.ObjectID;var s=r(1867).Buffer;var Chunk=function(e,t,r){if(!(this instanceof Chunk))return new Chunk(e,t);this.file=e;var i=t==null?{}:t;this.writeConcern=r||{w:1};this.objectId=i._id==null?new o:i._id;this.chunkNumber=i.n==null?0:i.n;this.data=new n;if(typeof i.data==="string"){var a=s.alloc(i.data.length);a.write(i.data,0,i.data.length,"binary");this.data=new n(a)}else if(Array.isArray(i.data)){a=s.alloc(i.data.length);var A=i.data.join("");a.write(A,0,A.length,"binary");this.data=new n(a)}else if(i.data&&i.data._bsontype==="Binary"){this.data=i.data}else if(!s.isBuffer(i.data)&&!(i.data==null)){throw Error("Illegal chunk format")}this.internalPosition=0};Chunk.prototype.write=function(e,t){this.data.write(e,this.internalPosition,e.length,"binary");this.internalPosition=this.data.length();if(t!=null)return t(null,this);return this};Chunk.prototype.read=function(e){e=e==null||e===0?this.length():e;if(this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);this.internalPosition=this.internalPosition+e;return t}else{return""}};Chunk.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;if(this.data.buffer!=null){t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e)}else{t=s.alloc(e);e=this.data.readInto(t,this.internalPosition)}this.internalPosition=this.internalPosition+e;return t}else{return null}};Chunk.prototype.eof=function(){return this.internalPosition===this.length()?true:false};Chunk.prototype.getc=function(){return this.read(1)};Chunk.prototype.rewind=function(){this.internalPosition=0;this.data=new n};Chunk.prototype.save=function(e,t){var r=this;if(typeof e==="function"){t=e;e={}}r.file.chunkCollection((function(n,o){if(n)return t(n);var s={upsert:true};for(var i in e)s[i]=e[i];for(i in r.writeConcern)s[i]=r.writeConcern[i];if(r.data.length()>0){r.buildMongoObject((function(e){var n={forceServerObjectId:true};for(var i in r.writeConcern){n[i]=r.writeConcern[i]}o.replaceOne({_id:r.objectId},e,s,(function(e){t(e,r)}))}))}else{t(null,r)}}))};Chunk.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};if(this.objectId!=null)t._id=this.objectId;e(t)};Chunk.prototype.length=function(){return this.data.length()};Object.defineProperty(Chunk.prototype,"position",{enumerable:true,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Chunk.DEFAULT_CHUNK_SIZE=1024*255;e.exports=Chunk},9406:(e,t,r)=>{"use strict";const n=r(3890);const o=r(3994).BSON.ObjectID;const s=r(3994).ReadPreference;const i=r(1867).Buffer;const a=r(7147);const A=r(3837).format;const c=r(3837);const l=r(3994).MongoError;const u=c.inherits;const h=r(2781).Duplex;const d=r(1371).shallowClone;const g=r(1371).executeLegacyOperation;const p=r(3837).deprecate;var E=0,m=1;const C=p((()=>{}),"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var I=function GridStore(e,t,r,i,a){C();if(!(this instanceof GridStore))return new GridStore(e,t,r,i,a);this.db=e;if(typeof a==="undefined")a={};if(typeof i==="undefined"){i=r;r=undefined}else if(typeof i==="object"){a=i;i=r;r=undefined}if(t&&t._bsontype==="ObjectID"){this.referenceBy=m;this.fileId=t;this.filename=r}else if(typeof r==="undefined"){this.referenceBy=E;this.filename=t;if(i.indexOf("w")!=null){this.fileId=new o}}else{this.referenceBy=m;this.fileId=t;this.filename=r}this.mode=i==null?"r":i;this.options=a||{};this.isOpen=false;this.root=this.options["root"]==null?GridStore.DEFAULT_ROOT_COLLECTION:this.options["root"];this.position=0;this.readPreference=this.options.readPreference||e.options.readPreference||s.primary;this.writeConcern=_getWriteConcern(e,this.options);this.internalChunkSize=this.options["chunkSize"]==null?n.DEFAULT_CHUNK_SIZE:this.options["chunkSize"];var A=this.options.promiseLibrary||Promise;this.promiseLibrary=A;Object.defineProperty(this,"chunkSize",{enumerable:true,get:function(){return this.internalChunkSize},set:function(e){if(!(this.mode[0]==="w"&&this.position===0&&this.uploadDate==null)){this.internalChunkSize=this.internalChunkSize}else{this.internalChunkSize=e}}});Object.defineProperty(this,"md5",{enumerable:true,get:function(){return this.internalMd5}});Object.defineProperty(this,"chunkNumber",{enumerable:true,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};I.prototype.open=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r"){throw l.create({message:"Illegal mode "+this.mode,driver:true})}return g(this.db.s.topology,open,[this,e,t],{skipSessions:true})};var open=function(e,t,r){var n=_getWriteConcern(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var o=e.collection();o.ensureIndex([["filename",1]],n,(function(){var t=e.chunkCollection();var o=d(n);o.unique=true;t.ensureIndex([["files_id",1],["n",1]],o,(function(){_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}))}))}else{_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}};I.prototype.eof=function(){return this.position===this.length?true:false};I.prototype.getc=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,getc,[this,e,t],{skipSessions:true})};var getc=function(e,t,r){if(e.eof()){r(null,null)}else if(e.currentChunk.eof()){nthChunk(e,e.currentChunk.chunkNumber+1,(function(t,n){e.currentChunk=n;e.position=e.position+1;r(t,e.currentChunk.getc())}))}else{e.position=e.position+1;r(null,e.currentChunk.getc())}};I.prototype.puts=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};var n=e.match(/\n$/)==null?e+"\n":e;return g(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:true})};I.prototype.stream=function(){return new GridStoreStream(this)};I.prototype.write=function write(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return g(this.db.s.topology,_writeNormal,[this,e,t,r,n],{skipSessions:true})};I.prototype.destroy=function destroy(){if(!this.writable)return;this.readable=false;if(this.writable){this.writable=false;this._q.length=0;this.emit("close")}};I.prototype.writeFile=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return g(this.db.s.topology,writeFile,[this,e,t,r],{skipSessions:true})};var writeFile=function(e,t,r,o){if(typeof t==="string"){a.open(t,"r",(function(t,r){if(t)return o(t);e.writeFile(r,o)}));return}e.open((function(e,r){if(e)return o(e,r);a.fstat(t,(function(e,s){if(e)return o(e,r);var A=0;var c=0;var writeChunk=function(){var e=i.alloc(r.chunkSize);a.read(t,e,0,e.length,A,(function(e,i,l){if(e)return o(e,r);A=A+i;var u=new n(r,{n:c++},r.writeConcern);u.write(l.slice(0,i),(function(e,n){if(e)return o(e,r);n.save({},(function(e){if(e)return o(e,r);r.position=r.position+i;r.currentChunk=n;if(A>=s.size){a.close(t,(function(e){if(e)return o(e);r.close((function(e){if(e)return o(e,r);return o(null,r)}))}))}else{return process.nextTick(writeChunk)}}))}))}))};process.nextTick(writeChunk)}))}))};I.prototype.close=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,close,[this,e,t],{skipSessions:true})};var close=function(e,t,r){if(e.mode[0]==="w"){t=Object.assign({},e.writeConcern,t);if(e.currentChunk!=null&&e.currentChunk.position>0){e.currentChunk.save({},(function(n){if(n&&typeof r==="function")return r(n);e.collection((function(n,o){if(n&&typeof r==="function")return r(n);if(e.uploadDate!=null){buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}else{e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}}))}))}else{e.collection((function(n,o){if(n&&typeof r==="function")return r(n);e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}))}}else if(e.mode[0]==="r"){if(typeof r==="function")r(null,null)}else{if(typeof r==="function")r(l.create({message:A("Illegal mode %s",e.mode),driver:true}))}};I.prototype.chunkCollection=function(e){if(typeof e==="function")return this.db.collection(this.root+".chunks",e);return this.db.collection(this.root+".chunks")};I.prototype.unlink=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,unlink,[this,e,t],{skipSessions:true})};var unlink=function(e,t,r){deleteChunks(e,(function(t){if(t!==null){t.message="at deleteChunks: "+t.message;return r(t)}e.collection((function(t,n){if(t!==null){t.message="at collection: "+t.message;return r(t)}n.remove({_id:e.fileId},e.writeConcern,(function(t){r(t,e)}))}))}))};I.prototype.collection=function(e){if(typeof e==="function")this.db.collection(this.root+".files",e);return this.db.collection(this.root+".files")};I.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift():"\n";e=e||"\n";t=n.length?n.shift():{};return g(this.db.s.topology,readlines,[this,e,t,r],{skipSessions:true})};var readlines=function(e,t,r,n){e.read((function(e,r){if(e)return n(e);var o=r.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var A=e.currentChunk.readSlice(s-a._index);A.copy(a,a._index);e.position=e.position+a.length;if(s===0&&a.length===0)return o(l.create({message:"File does not exist",driver:true}),null);return o(null,a)}A=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position);A.copy(a,a._index);a._index+=A.length;nthChunk(e,e.currentChunk.chunkNumber+1,(function(r,n){if(r)return o(r);if(n.length()>0){e.currentChunk=n;e.read(t,a,o)}else{if(a._index>0){o(null,a)}else{o(l.create({message:"no chunks found for file, possibly corrupt",driver:true}),null)}}}))};I.prototype.tell=function(e){var t=this;if(typeof e==="function")return e(null,this.position);return new t.promiseLibrary((function(e){e(t.position)}))};I.prototype.seek=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():null;r=o.length?o.shift():{};return g(this.db.s.topology,seek,[this,e,t,r,n],{skipSessions:true})};var seek=function(e,t,r,n,o){if(e.mode!=="r"){return o(l.create({message:"seek is only supported for mode r",driver:true}))}var s=r==null?I.IO_SEEK_SET:r;var i=t;var a=0;if(s===I.IO_SEEK_CUR){a=e.position+i}else if(s===I.IO_SEEK_END){a=e.length+i}else{a=i}var A=Math.floor(a/e.chunkSize);var seekChunk=function(){nthChunk(e,A,(function(t,r){if(t)return o(t,null);if(r==null)return o(new Error("no chunk found"));e.currentChunk=r;e.position=a;e.currentChunk.position=e.position%e.chunkSize;o(t,e)}))};seekChunk()};var _open=function(e,t,r){var s=e.collection();var i=e.referenceBy===m?{_id:e.fileId}:{filename:e.filename};i=null==e.fileId&&e.filename==null?null:i;t.readPreference=e.readPreference;if(i!=null){s.findOne(i,t,(function(s,i){if(s){return error(s)}if(i!=null){e.fileId=i._id;e.filename=e.mode==="r"||e.filename===undefined?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(e.mode!=="r"){e.fileId=e.fileId==null?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0}else{e.length=0;var a=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return error(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?a:e.filename),driver:true}),e)}if(e.mode==="r"){nthChunk(e,0,t,(function(t,n){if(t)return error(t);e.currentChunk=n;e.position=0;r(null,e)}))}else if(e.mode==="w"&&i){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w"){e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}))}else{e.fileId=null==e.fileId?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0;if(e.mode==="w"){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}function error(e){if(error.err)return;r(error.err=e)}};var writeBuffer=function(e,t,r,o){if(typeof r==="function"){o=r;r=null}var s=typeof r==="boolean"?r:false;if(e.mode!=="w"){o(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?e.referenceBy:e.filename),driver:true}),null)}else{if(e.currentChunk.position+t.length>=e.chunkSize){var i=e.currentChunk.chunkNumber;var a=e.chunkSize-e.currentChunk.position;var c=t.slice(0,a);var u=t.slice(a);var h=[e.currentChunk.write(c)];while(u.length>=e.chunkSize){var d=new n(e,{n:i+1},e.writeConcern);c=u.slice(0,e.chunkSize);u=u.slice(e.chunkSize);i=i+1;d.write(c);h.push(d)}e.currentChunk=new n(e,{n:i+1},e.writeConcern);if(u.length>0)e.currentChunk.write(u);e.position=e.position+t.length;var g=h.length;for(var p=0;p=t.length)return s("offset larger than size of file",null);if(r&&r>t.length)return s("length is larger than the size of the file",null);if(n&&r&&n+r>t.length)return s("offset and length is larger than the size of the file",null);if(n!=null){t.seek(n,(function(e,t){if(e)return s(e);t.read(r,s)}))}else{t.read(r,s)}}))};I.readlines=function(e,t,r,n,o){var s=Array.prototype.slice.call(arguments,2);o=typeof s[s.length-1]==="function"?s.pop():undefined;r=s.length?s.shift():null;n=s.length?s.shift():null;n=n||{};return g(e.s.topology,readlinesStatic,[e,t,r,n,o],{skipSessions:true})};var readlinesStatic=function(e,t,r,n,o){var s=r==null?"\n":r;new I(e,t,"r",n).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};I.unlink=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift():{};r=r||{};return g(e.s.topology,unlinkStatic,[this,e,t,r,n],{skipSessions:true})};var unlinkStatic=function(e,t,r,n,o){var s=_getWriteConcern(t,n);if(r.constructor===Array){var i=0;for(var a=0;ae.totalBytesToRead){e.totalBytesToRead=e.totalBytesToRead-r._index;e.push(r.slice(0,r._index))}if(e.totalBytesToRead<=0){e.endCalled=true}}))};var t=e.gs.length{"use strict";const n=r(1117);const o=r(6662);const s=r(2361).EventEmitter;const i=r(3837).inherits;const a=r(3994).MongoError;const A=r(3994).ValidServerApiVersions;const c=r(3837).deprecate;const l=r(2481);const u=r(1371).MongoDBNamespace;const h=r(4485);const d=r(1371).maybePromise;const g=r(2632);const p=r(5210).connect;const E=r(5210).validOptions;function MongoClient(e,t){t=t||{};if(!(this instanceof MongoClient))return new MongoClient(e,t);s.call(this);if(t.autoEncryption)r(3012);if(t.serverApi){const e=typeof t.serverApi==="string"?{version:t.serverApi}:t.serverApi;const r=e&&e.version;if(!r){throw new a(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${A.join('", "')}"]`)}if(!A.some((e=>e===r))){throw new a(`Invalid server API version=${r}; must be in the following enum: ["${A.join('", "')}"]`)}t.serverApi=e}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:l.fromOptions(t),readPreference:h.fromOptions(t)||h.primary,namespace:new u("admin")}}i(MongoClient,s);Object.defineProperty(MongoClient.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(MongoClient.prototype,"readPreference",{enumerable:true,get:function(){return this.s.readPreference}});MongoClient.prototype.connect=function(e){if(typeof e==="string"){throw new TypeError("`connect` only accepts a callback")}const t=this;return d(this,e,(e=>{const r=E(t.s.options);if(r)return e(r);p(t,t.s.url,t.s.options,(r=>{if(r)return e(r);e(null,t)}))}))};MongoClient.prototype.logout=c((function(e,t){if(typeof e==="function")t=e,e={};if(typeof t==="function")t(null,true)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");MongoClient.prototype.close=function(e,t){if(typeof e==="function"){t=e;e=false}const r=this;return d(this,t,(t=>{const completeClose=e=>{r.emit("close",r);if(!(r.topology instanceof g)){for(const e of r.s.dbCache){e[1].emit("close",r)}}r.removeAllListeners("close");t(e)};if(r.topology==null){completeClose();return}r.topology.close(e,(t=>{const n=r.topology.s.options.encrypter;if(n){return n.close(r,e,(e=>{completeClose(t||e)}))}completeClose(t)}))}))};MongoClient.prototype.db=function(e,t){t=t||{};if(!e){e=this.s.options.dbName}const r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==true){return this.s.dbCache.get(e)}r.promiseLibrary=this.s.promiseLibrary;if(!this.topology){throw new a("MongoClient must be connected before calling MongoClient.prototype.db")}const n=new o(e,this.topology,r);this.s.dbCache.set(e,n);return n};MongoClient.prototype.isConnected=c((function(e){e=e||{};if(!this.topology)return false;return this.topology.isConnected(e)}),"isConnected is deprecated and will be removed in the next major version");MongoClient.connect=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():null;t=t||{};const o=new MongoClient(e,t);return o.connect(r)};MongoClient.prototype.startSession=function(e){e=Object.assign({explicit:true},e);if(!this.topology){throw new a("Must connect to a server before calling this method")}return this.topology.startSession(e,this.s.options)};MongoClient.prototype.withSession=function(e,t){if(typeof e==="function")t=e,e=undefined;const r=this.startSession(e);let cleanupHandler=(e,t,n)=>{cleanupHandler=()=>{throw new ReferenceError("cleanupHandler was called too many times")};n=Object.assign({throw:true},n);r.endSession();if(e){if(n.throw)throw e;return Promise.reject(e)}};try{const e=t(r);return Promise.resolve(e).then((e=>cleanupHandler(null,e))).catch((e=>cleanupHandler(e,null,{throw:true})))}catch(e){return cleanupHandler(e,null,{throw:false})}};MongoClient.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new n(this,e,t)};MongoClient.prototype.getLogger=function(){return this.s.options.logger};e.exports=MongoClient},7057:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(6113);const a=r(1371).handleCallback;const A=r(1371).toError;const c=r(1371).emitWarning;class AddUserOperation extends o{constructor(e,t,r,n){super(e,n);this.username=t;this.password=r}_buildCommand(){const e=this.db;const t=this.username;const r=this.password;const n=this.options;let o=[];if(Array.isArray(n.roles))o=n.roles;if(typeof n.roles==="string")o=[n.roles];if(o.length===0){c("Creating a user without roles is deprecated in MongoDB >= 2.6")}if((e.databaseName.toLowerCase()==="admin"||n.dbName==="admin")&&!Array.isArray(n.roles)){o=["root"]}else if(!Array.isArray(n.roles)){o=["dbOwner"]}const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=r;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+r);a=e.digest("hex")}const A={createUser:t,customData:n.customData||{},roles:o,digestPassword:s};if(typeof r==="string"){A.pwd=a}return A}execute(e){const t=this.options;if(t.digestPassword!=null){return e(A("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."))}super.execute(((t,r)=>{if(!t){return a(e,t,r)}return a(e,t,null)}))}}s(AddUserOperation,n.WRITE_OPERATION);e.exports=AddUserOperation},1554:(e,t,r)=>{"use strict";const n=r(1189);const o=r(3994).MongoError;const s=r(1178).maxWireVersion;const i=r(3994).ReadPreference;const a=r(1018).Aspect;const A=r(1018).defineAspects;const c=1;const l=8;class AggregateOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:c;this.pipeline=t;this.hasWriteStage=false;if(typeof r.out==="string"){this.pipeline=this.pipeline.concat({$out:r.out});this.hasWriteStage=true}else if(t.length>0){const e=t[t.length-1];if(e.$out||e.$merge){this.hasWriteStage=true}}if(this.hasWriteStage){this.readPreference=i.primary}if(this.explain&&this.writeConcern){throw new o('"explain" cannot be used on an aggregate call with writeConcern')}if(r.cursor!=null&&typeof r.cursor!=="object"){throw new o("cursor options must be an object")}}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const r=this.options;const n=s(e);const o={aggregate:this.target,pipeline:this.pipeline};if(this.hasWriteStage&&n=5){if(this.hasWriteStage&&this.writeConcern){Object.assign(o,{writeConcern:this.writeConcern})}}if(r.bypassDocumentValidation===true){o.bypassDocumentValidation=r.bypassDocumentValidation}if(typeof r.allowDiskUse==="boolean"){o.allowDiskUse=r.allowDiskUse}if(r.hint){o.hint=r.hint}if(this.explain){r.full=false}o.cursor=r.cursor||{};if(r.batchSize&&!this.hasWriteStage){o.cursor.batchSize=r.batchSize}super.executeCommand(e,o,t)}}A(AggregateOperation,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]);e.exports=AggregateOperation},6976:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(3994).MongoError;const i=r(1018).OperationBase;class BulkWriteOperation extends i{constructor(e,t,r){super(r);this.collection=e;this.operations=t}execute(e){const t=this.collection;const r=this.operations;let i=this.options;if(t.s.options.ignoreUndefined){i=Object.assign({},i);i.ignoreUndefined=t.s.options.ignoreUndefined}const a=i.ordered===true||i.ordered==null?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let A=false;try{for(let e=0;e{if(!r&&t){return e(t,null)}e(null,r)}))}}e.exports=BulkWriteOperation},6716:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(2226).createIndex;const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(2226).ensureIndex;const c=r(2226).evaluate;const l=r(2226).executeCommand;const u=r(1371).handleCallback;const h=r(2226).indexInformation;const d=r(3994).BSON.Long;const g=r(3994).MongoError;const p=r(3994).ReadPreference;const E=r(2296).insertDocuments;const m=r(2296).updateDocuments;const C='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}';function createIndex(e,t,r,n){s(e.s.db,e.collectionName,t,r,n)}function createIndexes(e,t,r,n){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}));h.group.key=e}d=Object.assign({},d);d.readPreference=p.resolve(e,d);a(h,e,d);try{i(h,e,d)}catch(e){return g(e,null)}l(e.s.db,h,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.retval)}))}else{const i=s!=null&&s._bsontype==="Code"?s.scope:{};i.ns=e.collectionName;i.keys=t;i.condition=r;i.initial=n;const a=C.replace(/ reduce;/,s.toString()+";");c(e.s.db,new o(a,i),null,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.result||t)}))}}function indexes(e,t,r){t=Object.assign({},{full:true},t);h(e.s.db,e.collectionName,t,r)}function indexExists(e,t,r,n){indexInformation(e,r,((e,r)=>{if(e!=null)return u(n,e,null);if(!Array.isArray(t))return u(n,null,r[t]!=null);for(let e=0;e{if(n)return u(r,n,null);if(s==null)return u(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:true},t);const i=[];if(o)t.raw=o;for(let r=0;r{if(o==null)return;if(t==null)return u(o,null,null);if(e)return u(o,e,null);u(o,null,r)}))}e.exports={createIndex:createIndex,createIndexes:createIndexes,ensureIndex:ensureIndex,group:group,indexes:indexes,indexExists:indexExists,indexInformation:indexInformation,parallelCollectionScan:parallelCollectionScan,save:save}},286:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;let s;function loadCollection(){if(!s){s=r(5193)}return s}class CollectionsOperation extends n{constructor(e,t){super(t);this.db=e}execute(e){const t=this.db;let r=this.options;let n=loadCollection();r=Object.assign({},r,{nameOnly:true});t.listCollections({},r).toArray(((r,s)=>{if(r!=null)return o(e,r,null);s=s.filter((e=>e.name.indexOf("$")===-1));o(e,null,s.map((e=>new n(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options))))}))}}e.exports=CollectionsOperation},499:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(1371).applyWriteConcern;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=r(1371).MongoDBNamespace;const u=r(7703).extractCommand;const h=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];class CommandOperation extends o{constructor(e,t,r,o){super(t);if(!this.hasAspect(n.WRITE_OPERATION)){if(r!=null){this.options.readPreference=c.resolve(r,t)}else{this.options.readPreference=c.resolve(e,t)}}else{if(r!=null){s(this.options,{db:e,coll:r},this.options)}else{s(this.options,{db:e},this.options)}this.options.readPreference=c.primary}this.db=e;if(o!=null){this.command=o}if(r!=null){this.collection=r}}_buildCommand(){if(this.command!=null){return this.command}}execute(e){const t=this.db;const r=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new A("topology was destroyed"))}let o;try{o=this._buildCommand()}catch(t){return e(t)}const s=r.dbName||r.authdb||t.databaseName;if(this.hasAspect(n.WRITE_OPERATION)){if(r.writeConcern&&(!r.session||!r.session.inTransaction())){o.writeConcern=r.writeConcern}}if(t.s.logger.isDebug()){const e=u(o);t.s.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:o)} against ${s}.$cmd with options [${JSON.stringify(i(h,r))}]`)}const c=this.namespace!=null?this.namespace:new l(s,"$cmd");t.s.topology.command(c,o,r,((t,n)=>{if(t)return a(e,t);if(r.full)return a(e,null,n);a(e,null,n.result)}))}}e.exports=CommandOperation},1189:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(3994).ReadPreference;const i=r(7289);const a=r(2481);const A=r(1178).maxWireVersion;const c=r(1371).decorateWithExplain;const l=r(5474).commandSupportsReadConcern;const u=r(3111).MongoError;const h=r(7703).extractCommand;const d=5;class CommandOperationV2 extends o{constructor(e,t,r){super(t);this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(n.NO_INHERIT_OPTIONS)?undefined:e;this.readPreference=this.hasAspect(n.WRITE_OPERATION)?s.primary:s.resolve(o,this.options);this.readConcern=resolveReadConcern(o,this.options);this.writeConcern=resolveWriteConcern(o,this.options);if(r&&typeof r.fullResponse==="boolean"){this.fullResponse=true}this.options.readPreference=this.readPreference;if(e.s.logger){this.logger=e.s.logger}else if(e.s.db&&e.s.db.logger){this.logger=e.s.db.logger}}executeCommand(e,t,r){this.server=e;const o=this.options;const s=A(e);const i=this.session&&this.session.inTransaction();if(this.readConcern&&l(t)&&!i){Object.assign(t,{readConcern:this.readConcern})}if(o.collation&&s=d){if(this.writeConcern&&this.hasAspect(n.WRITE_OPERATION)){Object.assign(t,{writeConcern:this.writeConcern})}if(o.collation&&typeof o.collation==="object"){Object.assign(t,{collation:o.collation})}}if(typeof o.maxTimeMS==="number"){t.maxTimeMS=o.maxTimeMS}if(typeof o.comment==="string"){t.comment=o.comment}if(this.hasAspect(n.EXPLAINABLE)&&this.explain){if(s<6&&t.aggregate){t.explain=true}else{t=c(t,this.explain)}}if(this.logger&&this.logger.isDebug()){const e=h(t);this.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:t)} against ${this.ns}`)}e.command(this.ns.toString(),t,this.options,((e,t)=>{if(e){r(e,null);return}if(this.fullResponse){r(null,t);return}r(null,t.result)}))}}function resolveWriteConcern(e,t){return a.fromOptions(t)||e&&e.writeConcern}function resolveReadConcern(e,t){return i.fromOptions(t)||e&&e.readConcern}e.exports=CommandOperationV2},2296:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).MongoError;const u=r(3994).ReadPreference;const h=r(1371).toError;const d=r(4847).CursorState;const g=r(1178).maxWireVersion;function buildCountCommand(e,t,r){const n=r.skip;const o=r.limit;let a=r.hint;const A=r.maxTimeMS;t=t||{};const c={count:r.collectionName,query:t};if(e.s.numberOfRetries){if(e.options.hint){a=e.options.hint}else if(e.cmd.hint){a=e.cmd.hint}s(c,e,e.cmd)}else{s(c,e,r)}if(typeof n==="number")c.skip=n;if(typeof o==="number")c.limit=o;if(typeof A==="number")c.maxTimeMS=A;if(a)c.hint=a;i(c,e);return c}function findAndModify(e,t,r,i,l,h){const d={findAndModify:e.collectionName,query:t};r=A(r);if(r){d.sort=r}d.new=l.new?true:false;d.remove=l.remove?true:false;d.upsert=l.upsert?true:false;const g=l.projection||l.fields;if(g){d.fields=g}if(l.arrayFilters){d.arrayFilters=l.arrayFilters;delete l.arrayFilters}if(i&&!l.remove){d.update=i}if(l.maxTimeMS)d.maxTimeMS=l.maxTimeMS;l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions;l.checkKeys=false;let p=Object.assign({},l);p=n(p,e.s.db);p=o(p,{db:e.s.db,collection:e},l);if(p.writeConcern){d.writeConcern=p.writeConcern}if(p.bypassDocumentValidation===true){d.bypassDocumentValidation=p.bypassDocumentValidation}p.readPreference=u.primary;try{s(d,e,p)}catch(e){return h(e,null)}a(e.s.db,d,p,((e,t)=>{if(e)return c(h,e,null);return c(h,null,t)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new l("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(h(e));if(!Array.isArray(t))return c(n,null,[]);if(o)return c(n,null,t);c(n,null,processResults(t))}))}function prepareDocs(e,t,r){const n=typeof r.forceServerObjectId==="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;if(n===true){return t}return t.map((t=>{if(n!==true&&t._id==null){t._id=e.s.pkFactory.createPk()}return t}))}function nextObject(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead()){return c(t,l.create({message:"Cursor is closed",driver:true}))}if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort){try{e.cmd.sort=A(e.cmd.sort)}catch(e){return c(t,e)}}e._next(((r,n)=>{e.s.state=d.OPEN;if(r)return c(t,r);c(t,null,n)}))}function insertDocuments(e,t,r,s){if(typeof r==="function")s=r,r={};r=r||{};t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=n(i,e.s.db);i=o(i,{db:e.s.db,collection:e},r);if(i.keepGoing===true)i.ordered=false;i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions;t=prepareDocs(e,t,r);e.s.topology.insert(e.s.namespace,t,i,((e,r)=>{if(s==null)return;if(e)return c(s,e);if(r==null)return c(s,null,null);if(r.result.code)return c(s,h(r.result));if(r.result.writeErrors)return c(s,h(r.result.writeErrors[0]));r.ops=t;c(s,null,r)}))}function removeDocuments(e,t,r,i){if(typeof r==="function"){i=r,r={}}else if(typeof t==="function"){i=t;r={};t={}}r=r||{};let a=Object.assign({},r);a=n(a,e.s.db);a=o(a,{db:e.s.db,collection:e},r);if(t==null)t={};const A={q:t,limit:0};if(r.single){A.limit=1}else if(a.retryWrites){a.retryWrites=false}if(r.hint){A.hint=r.hint}try{s(a,e,r)}catch(e){return i(e,null)}if(r.explain!==undefined&&g(e.s.topology)<3){return i?i(new l(`server does not support explain on remove`)):undefined}e.s.topology.remove(e.s.namespace,[A],a,((e,t)=>{if(i==null)return;if(e)return c(i,e,null);if(t==null)return c(i,null,null);if(t.result.code)return c(i,h(t.result));if(t.result.writeErrors){return c(i,h(t.result.writeErrors[0]))}c(i,null,t)}))}function updateDocuments(e,t,r,i,a){if("function"===typeof i)a=i,i=null;if(i==null)i={};if(!("function"===typeof a))a=null;if(t==null||typeof t!=="object")return a(h("selector must be a valid JavaScript object"));if(r==null||typeof r!=="object")return a(h("document must be a valid JavaScript object"));let A=Object.assign({},i);A=n(A,e.s.db);A=o(A,{db:e.s.db,collection:e},i);A.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const u={q:t,u:r};u.upsert=i.upsert!==void 0?!!i.upsert:false;u.multi=i.multi!==void 0?!!i.multi:false;if(i.hint){u.hint=i.hint}if(A.arrayFilters){u.arrayFilters=A.arrayFilters;delete A.arrayFilters}if(A.retryWrites&&u.multi){A.retryWrites=false}try{s(A,e,i)}catch(e){return a(e,null)}if(i.explain!==undefined&&g(e.s.topology)<3){return a?a(new l(`server does not support explain on update`)):undefined}e.s.topology.update(e.s.namespace,[u],A,((e,t)=>{if(a==null)return;if(e)return c(a,e,null);if(t==null)return c(a,null,null);if(t.result.code)return c(a,h(t.result));if(t.result.writeErrors)return c(a,h(t.result.writeErrors[0]));c(a,null,t)}))}e.exports={buildCountCommand:buildCountCommand,findAndModify:findAndModify,indexInformation:indexInformation,nextObject:nextObject,prepareDocs:prepareDocs,insertDocuments:insertDocuments,removeDocuments:removeDocuments,updateDocuments:updateDocuments}},5210:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(3994).Logger;const s=r(3994).MongoCredentials;const i=r(3994).MongoError;const a=r(2048);const A=r(2632);const c=r(3994).parseConnectionString;const l=r(7289);const u=r(3994).ReadPreference;const h=r(382);const d=r(8421);const g=r(3994).Sessions.ServerSessionPool;const p=r(1371).emitDeprecationWarning;const E=r(1371).emitWarningOnce;const m=r(7147);const C=r(2481);const I=r(897).CMAP_EVENT_NAMES;let y;function loadClient(){if(!y){y=r(1545)}return y}const B=n(r(8729),"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.");const Q={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"};const b=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"];const w=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]);const S=["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","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","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"];const v=["native_parser"];const R=["server","replset","replSet","mongos","db"];function validOptions(e){const t=S.concat(R);for(const r in e){if(v.indexOf(r)!==-1){continue}if(t.indexOf(r)===-1){if(e.validateOptions){return new i(`option ${r} is not supported`)}else{E(`the options [${r}] is not supported`)}}if(R.indexOf(r)!==-1){E(`the server/replset/mongos/db options are deprecated, `+`all their options are supported at the top level of the options object [${S}]`)}}}const k=S.reduce(((e,t)=>{e[t.toLowerCase()]=t;return e}),{});function addListeners(e,t){t.on("authenticated",createListener(e,"authenticated"));t.on("error",createListener(e,"error"));t.on("timeout",createListener(e,"timeout"));t.on("close",createListener(e,"close"));t.on("parseError",createListener(e,"parseError"));t.once("open",createListener(e,"open"));t.once("fullsetup",createListener(e,"fullsetup"));t.once("all",createListener(e,"all"));t.on("reconnect",createListener(e,"reconnect"))}function assignTopology(e,t){e.topology=t;if(!(t instanceof A)){t.s.sessionPool=new g(t.s.coreTopology)}}function clearAllEvents(e){b.forEach((t=>e.removeAllListeners(t)))}function collectEvents(e,t){let r=loadClient();const n=[];if(e instanceof r){b.forEach((r=>{t.on(r,((t,o)=>{if(r==="open"){n.push({event:r,object1:e})}else{n.push({event:r,object1:t,object2:o})}}))}))}return n}function resolveTLSOptions(e){if(e.tls==null){return}["sslCA","sslKey","sslCert"].forEach((t=>{if(e[t]){e[t]=m.readFileSync(e[t])}}))}function connect(e,t,r,n){r=Object.assign({},r);if(n==null){throw new Error("no callback function provided")}let s=false;const A=o("MongoClient",r);if(t instanceof d||t instanceof h||t instanceof a){return connectWithUrl(e,t,r,connectCallback)}const l=r.useNewUrlParser!==false;const g=l?c:B;const p=l?transformUrlOptions:legacyTransformUrlOptions;g(t,r,((t,o)=>{if(t)return n(t);const i=p(o);const a=createUnifiedOptions(i,r);if(a.socketTimeoutMS==null)a.socketTimeoutMS=0;if(a.connectTimeoutMS==null)a.connectTimeoutMS=1e4;if(a.retryWrites==null)a.retryWrites=true;if(a.useRecoveryToken==null)a.useRecoveryToken=true;if(a.readPreference==null)a.readPreference="primary";if(a.db_options&&a.db_options.auth){delete a.db_options.auth}resolveTLSOptions(a);e.s.options=a;e.s.readPreference=u.fromOptions(a);e.s.writeConcern=C.fromOptions(a);if(i.servers.length===0){return n(new Error("connection string must contain at least one seed host"))}if(a.auth&&!a.credentials){try{s=true;a.credentials=generateCredentials(e,a.auth.user,a.auth.password,a)}catch(t){return n(t)}}if(a.useUnifiedTopology){return createTopology(e,"unified",a,connectCallback)}E("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.");if(a.replicaSet||a.rs_name){return createTopology(e,"replicaset",a,connectCallback)}else if(i.servers.length>1){return createTopology(e,"mongos",a,connectCallback)}else{return createServer(e,a,connectCallback)}}));function connectCallback(t,r){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&&t.message==="no mongos proxies found in seed list"){if(A.isWarn()){A.warn(o)}return n(new i(o))}if(s){e.emit("authenticated",null,true)}n(t,r)}}function connectWithUrl(e,t,r,n){assignTopology(e,t);addListeners(e,t);relayEvents(e,t);let o=Object.assign({},r);if(typeof r.readPreference==="string"||typeof r.read_preference==="string"){o.readPreference=new u(r.readPreference||r.read_preference)}const s=o.user||o.password||o.authMechanism;if(s&&!o.credentials){try{o.credentials=generateCredentials(e,o.user,o.password,o)}catch(e){return n(e,t)}}return t.connect(o,n)}function createListener(e,t){const r=new Set(["all","fullsetup","open","reconnect"]);return(n,o)=>{if(r.has(t)){return e.emit(t,e)}e.emit(t,n,o)}}function createServer(e,t,r){t.promiseLibrary=e.s.promiseLibrary;const n=translateOptions(t);const o=n[0];const s=collectEvents(e,o);o.connect(t,((n,i)=>{if(n){o.close(true);return r(n)}clearAllEvents(o);relayEvents(e,o);addListeners(e,o);const a=i.lastIsMaster();assignTopology(e,i);if(a&&a.msg==="isdbgrid"){i.close();return createTopology(e,"mongos",t,r)}replayEvents(e,s);r(n,i)}))}const D=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function registerDeprecatedEventNotifiers(e){e.on("newListener",(e=>{if(D.has(e)){p(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}))}function createTopology(e,t,n,o){n.promiseLibrary=e.s.promiseLibrary;const s={};if(t==="unified")s.createServers=false;const i=translateOptions(n,s);if(n.autoEncryption!=null){const t=r(3012).Encrypter;n.encrypter=new t(e,n);n.autoEncrypter=n.encrypter.autoEncrypter}let c;if(t==="mongos"){c=new a(i,n)}else if(t==="replicaset"){c=new h(i,n)}else if(t==="unified"){c=new A(n.servers,n);registerDeprecatedEventNotifiers(e)}addListeners(e,c);relayEvents(e,c);assignTopology(e,c);if(n.autoEncrypter){n.autoEncrypter.init((e=>{if(e){o(e);return}c.connect(n,(e=>{if(e){c.close(true);o(e);return}n.encrypter.connectInternalClient((e=>{if(e)return o(e);o(undefined,c)}))}))}));return}c.connect(n,(e=>{if(e){c.close(true);return o(e)}o(undefined,c);return}))}function createUnifiedOptions(e,t){const r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"];const n=["readconcern","compression","autoencryption"];const o=["w","wtimeout","j","journal","fsync","writeconcern"];for(const s in t){if(o.indexOf(s.toLowerCase())!==-1){continue}else if(n.indexOf(s.toLowerCase())!==-1){e[s]=t[s]}else if(r.indexOf(s.toLowerCase())!==-1){e=mergeOptions(e,t[s],false)}else{if(t[s]&&typeof t[s]==="object"&&!Buffer.isBuffer(t[s])&&!Array.isArray(t[s])){e=mergeOptions(e,t[s],true)}else{e[s]=t[s]}}}const s=C.fromOptions(t);if(s){e.writeConcern=Object.assign({},e.writeConcern,s)}return e}function generateCredentials(e,t,r,n){n=Object.assign({},n);const o=n.authSource||n.authdb||n.dbName;const a=n.authMechanism||"DEFAULT";const A=a.toUpperCase();const c=n.authMechanismProperties;if(!w.has(A)){throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:true})}return new s({mechanism:Q[A],mechanismProperties:c,source:o,username:t,password:r})}function legacyTransformUrlOptions(e){return mergeOptions(createUnifiedOptions({},e),e,false)}function mergeOptions(e,t,r){for(const n in t){if(t[n]&&typeof t[n]==="object"&&r){e=mergeOptions(e,t[n],r)}else{e[n]=t[n]}}return e}function relayEvents(e,t){const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(I);r.forEach((r=>{t.on(r,((t,n)=>{e.emit(r,t,n)}))}))}function replayEvents(e,t){for(let r=0;rt.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e)))}e.exports={validOptions:validOptions,connect:connect}},7885:(e,t,r)=>{"use strict";const n=r(2296).buildCountCommand;const o=r(1018).OperationBase;class CountOperation extends o{constructor(e,t,r){super(r);this.cursor=e;this.applySkipLimit=t}execute(e){const t=this.cursor;const r=this.applySkipLimit;const o=this.options;if(r){if(typeof t.cursorSkip()==="number")o.skip=t.cursorSkip();if(typeof t.cursorLimit()==="number")o.limit=t.cursorLimit()}if(o.readPreference){t.setReadPreference(o.readPreference)}if(typeof o.maxTimeMS!=="number"&&t.cmd&&typeof t.cmd.maxTimeMS==="number"){o.maxTimeMS=t.cmd.maxTimeMS}let s={};s.skip=o.skip;s.limit=o.limit;s.hint=o.hint;s.maxTimeMS=o.maxTimeMS;s.collectionName=t.namespace.collection;let i;try{i=n(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology;t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,((t,r)=>{e(t,r?r.result.n:null)}))}}e.exports=CountOperation},5131:(e,t,r)=>{"use strict";const n=r(1554);class CountDocumentsOperation extends n{constructor(e,t,r){const n=[{$match:t}];if(typeof r.skip==="number"){n.push({$skip:r.skip})}if(typeof r.limit==="number"){n.push({$limit:r.limit})}n.push({$group:{_id:1,n:{$sum:1}}});super(e,n,r)}execute(e,t){super.execute(e,((e,r)=>{if(e){t(e,null);return}const n=r.result;if(n.cursor==null||n.cursor.firstBatch==null){t(null,0);return}const o=n.cursor.firstBatch;t(null,o.length?o[0].n:0)}))}}e.exports=CountDocumentsOperation},5561:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(8275).loadCollection;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class CreateCollectionOperation extends s{constructor(e,t,r){super(e,r);this.name=t}_buildCommand(){const e=this.name;const t=this.options;const r={create:e};for(let e in t){if(t[e]!=null&&typeof t[e]!=="function"&&!l.has(e)){r[e]=t[e]}}return r}execute(e){const t=this.db;const r=this.name;const n=this.options;const o=a();let s=Object.assign({nameOnly:true,strict:false},n);s=i(s,{db:t},s);function done(s){if(s){return e(s)}try{e(null,new o(t,t.s.topology,t.databaseName,r,t.s.pkFactory,n))}catch(s){e(s)}}const l=s.strict;if(l){t.listCollections({name:r},s).setReadPreference(c.PRIMARY).toArray(((t,n)=>{if(t){return e(t)}if(n.length>0){return e(new A(`Collection ${r} already exists. Currently in strict mode.`))}super.execute(done)}));return}super.execute(done)}}o(CreateCollectionOperation,n.WRITE_OPERATION);e.exports=CreateCollectionOperation},6394:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(3994).MongoError;const a=r(1371).parseIndexOptions;const A=r(1178).maxWireVersion;const c=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class CreateIndexesOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=t;if(!Array.isArray(r)||Array.isArray(r[0])){this.onlyReturnNameOfCreatedIndex=true;const e=a(r);const t=typeof n.name==="string"?n.name:e.name;const o={name:t,key:e.fieldHash};for(let e in n){if(c.has(e)){o[e]=n[e]}}this.indexes=[o];return}this.indexes=r}execute(e,t){const r=this.options;const n=this.indexes;const o=A(e);for(let r=0;r{if(e){t(e);return}t(null,this.onlyReturnNameOfCreatedIndex?n[0].name:r)}))}}o(CreateIndexesOperation,[n.WRITE_OPERATION,n.EXECUTE_WITH_SELECTION]);e.exports=CreateIndexesOperation},3554:(e,t,r)=>{"use strict";const n=r(6716).buildCountCommand;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=Array.prototype.push;const a=r(4847).CursorState;function count(e,t,r,o){if(t){if(typeof e.cursorSkip()==="number")r.skip=e.cursorSkip();if(typeof e.cursorLimit()==="number")r.limit=e.cursorLimit()}if(r.readPreference){e.setReadPreference(r.readPreference)}if(typeof r.maxTimeMS!=="number"&&e.cmd&&typeof e.cmd.maxTimeMS==="number"){r.maxTimeMS=e.cmd.maxTimeMS}let s={};s.skip=r.skip;s.limit=r.limit;s.hint=r.hint;s.maxTimeMS=r.maxTimeMS;s.collectionName=e.namespace.collection;let i;try{i=n(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology;e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,((e,t)=>{o(e,t?t.result.n:null)}))}function each(e,t){if(!t)throw s.create({message:"callback is mandatory",driver:true});if(e.isNotified())return;if(e.s.state===a.CLOSED||e.isDead()){return o(t,s.create({message:"Cursor is closed",driver:true}))}if(e.s.state===a.INIT){e.s.state=a.OPEN}let r=null;if(e.bufferedCount()>0){while(r=loop(e,t))r(e,t);each(e,t)}else{e.next(((r,n)=>{if(r)return o(t,r);if(n==null){return e.close({skipKillCursors:true},(()=>o(t,null,null)))}if(o(t,null,n)===false)return;each(e,t)}))}}function loop(e,t){if(e.bufferedCount()===0)return;e._next(t);return loop}function toArray(e,t){const r=[];e.rewind();e.s.state=a.INIT;const fetchDocs=()=>{e._next(((n,s)=>{if(n){return o(t,n)}if(s==null){return e.close({skipKillCursors:true},(()=>o(t,null,r)))}r.push(s);if(e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());if(e.s.transforms&&typeof e.s.transforms.doc==="function"){t=t.map(e.s.transforms.doc)}i.apply(r,t)}fetchDocs()}))};fetchDocs()}e.exports={count:count,each:each,toArray:toArray}},2226:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1371).applyWriteConcern;const s=r(3994).BSON.Code;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(1371).parseIndexOptions;const l=r(3994).ReadPreference;const u=r(1371).toError;const h=r(7703).extractCommand;const d=r(147);const g=r(1371).MongoDBNamespace;const p=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function createIndex(e,t,r,s,i){let c=Object.assign({},{readPreference:l.PRIMARY},s);c=o(c,{db:e},s);if(c.writeConcern&&typeof i!=="function"){throw A.create({message:"Cannot use a writeConcern without a provided callback",driver:true})}if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new A("topology was destroyed"));createIndexUsingCreateIndexes(e,t,r,c,((o,l)=>{if(o==null)return a(i,o,l);if(o.code===n.CannotCreateIndex||o.code===n.DuplicateKey||o.code===n.IndexOptionsConflict||o.code===n.IndexKeySpecsConflict||o.code===n.InterruptedAtShutdown||o.code===n.InvalidIndexSpecificationOption){return a(i,o,l)}const u=createCreateIndexCommand(e,t,r,s);c.checkKeys=false;e.s.topology.insert(e.s.namespace.withCollection(d.SYSTEM_INDEX_COLLECTION),u,c,((e,t)=>{if(i==null)return;if(e)return a(i,e);if(t==null)return a(i,null,null);if(t.result.writeErrors)return a(i,A.create(t.result.writeErrors[0]),null);a(i,null,u.name)}))}))}function createListener(e,t,r){function listener(n){if(r.listeners(t).length>0){r.emit(t,n,e);for(let r=0;r{if(o!=null&&o.code!==n.NamespaceNotFound){return a(i,o,null)}if(A==null||!A[h]){createIndex(e,t,r,s,i)}else{if(typeof i==="function")return a(i,null,h)}}))}function evaluate(e,t,r,n,o){let i=t;let c=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return o(new A("topology was destroyed"));if(!(i&&i._bsontype==="Code"))i=new s(i);if(r!=null&&!Array.isArray(r)&&typeof r!=="function"){c=[r]}else if(r!=null&&Array.isArray(r)&&typeof r!=="function"){c=r}let u={$eval:i,args:c};if(n["nolock"]){u["nolock"]=n["nolock"]}n.readPreference=new l(l.PRIMARY);executeCommand(e,u,n,((e,t)=>{if(e)return a(o,e,null);if(t&&t.ok===1)return a(o,null,t.retval);if(t)return a(o,A.create({message:`eval failed: ${t.errmsg}`,driver:true}),null);a(o,e,t)}))}function executeCommand(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));const o=r.dbName||r.authdb||e.databaseName;r.readPreference=l.resolve(e,r);if(e.s.logger.isDebug()){const n=h(t);e.s.logger.debug(`executing command ${JSON.stringify(n.shouldRedact?`${n.name} details REDACTED`:t)} against ${o}.$cmd with options [${JSON.stringify(i(p,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,((e,t)=>{if(e)return a(n,e);if(r.full)return a(n,null,t);a(n,null,t.result)}))}function executeDbAdminCommand(e,t,r,n){const o=new g("admin","$cmd");e.s.topology.command(o,t,r,((t,r)=>{if(e.serverConfig&&e.serverConfig.isDestroyed()){return n(new A("topology was destroyed"))}if(t)return a(n,t);a(n,null,r.result)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(u(e));if(!Array.isArray(t))return a(n,null,[]);if(o)return a(n,null,t);a(n,null,processResults(t))}))}function profilingInfo(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(e){return r(e,null)}}function validateDatabaseName(e){if(typeof e!=="string")throw A.create({message:"database name must be a string",driver:true});if(e.length===0)throw A.create({message:"database name cannot be the empty string",driver:true});if(e==="$external")return;const t=[" ",".","$","/","\\"];for(let r=0;r{if(e)return a(s,e,null);if(t.ok===0)return a(s,u(t),null);a(s,null,h)}))}e.exports={createListener:createListener,createIndex:createIndex,ensureIndex:ensureIndex,evaluate:evaluate,executeCommand:executeCommand,executeDbAdminCommand:executeDbAdminCommand,indexInformation:indexInformation,profilingInfo:profilingInfo,validateDatabaseName:validateDatabaseName}},323:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=false;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteManyOperation,[s.EXPLAINABLE]);e.exports=DeleteManyOperation},6352:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteOneOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=true;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteOneOperation,[s.EXPLAINABLE]);e.exports=DeleteOneOperation},6469:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(1178).maxWireVersion;const c=r(9386).MongoError;class DistinctOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=e;this.key=t;this.query=r}execute(e,t){const r=this.collection;const n=this.key;const o=this.query;const s=this.options;const l={distinct:r.collectionName,key:n,query:o};if(typeof s.maxTimeMS==="number"){l.maxTimeMS=s.maxTimeMS}a(l,r,s);try{i(l,r,s)}catch(e){return t(e,null)}if(this.explain&&A(e)<4){t(new c(`server does not support explain on distinct`));return}super.executeCommand(e,l,((e,r)=>{if(e){t(e);return}t(null,this.options.full||this.explain?r:r.values)}))}}o(DistinctOperation,[n.READ_OPERATION,n.RETRYABLE,n.EXECUTE_WITH_SELECTION,n.EXPLAINABLE]);e.exports=DistinctOperation},2360:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;class DropOperation extends o{constructor(e,t){const r=Object.assign({},t,e.s.options);if(t.session){r.session=t.session}super(e,r)}execute(e){super.execute(((t,r)=>{if(t)return i(e,t);if(r.ok)return i(e,null,true);i(e,null,false)}))}}s(DropOperation,n.WRITE_OPERATION);class DropCollectionOperation extends DropOperation{constructor(e,t,r){super(e,r);this.name=t;this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}}class DropDatabaseOperation extends DropOperation{_buildCommand(){return{dropDatabase:1}}}e.exports={DropOperation:DropOperation,DropCollectionOperation:DropCollectionOperation,DropDatabaseOperation:DropDatabaseOperation}},3560:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(1371).handleCallback;class DropIndexOperation extends s{constructor(e,t,r){super(e.s.db,r,e);this.collection=e;this.indexName=t}_buildCommand(){const e=this.collection;const t=this.indexName;const r=this.options;let n={dropIndexes:e.collectionName,index:t};n=i(n,{db:e.s.db,collection:e},r);return n}execute(e){super.execute(((t,r)=>{if(typeof e!=="function")return;if(t)return a(e,t,null);a(e,null,r)}))}}o(DropIndexOperation,n.WRITE_OPERATION);e.exports=DropIndexOperation},5328:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(3560);const i=r(1371).handleCallback;class DropIndexesOperation extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute((t=>{if(t)return i(e,t,false);i(e,null,true)}))}}o(DropIndexesOperation,n.WRITE_OPERATION);e.exports=DropIndexesOperation},4451:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1189);const a=r(1178).maxWireVersion;const A=r(5131);class EstimatedDocumentCountOperation extends i{constructor(e,t){super(e,t);this.collection=e;this.collectionName=e.s.namespace.collection}execute(e,t){if(a(e)<12){return this.executeLegacy(e,t)}if(this.options.query){const r=new A(this.collection,this.options.query,this.options);return r.execute(e,t)}const r=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}];const o={aggregate:this.collectionName,pipeline:r,cursor:{}};if(typeof this.options.maxTimeMS==="number"){o.maxTimeMS=this.options.maxTimeMS}super.executeCommand(e,o,((e,r)=>{if(e&&e.code!==n.NamespaceNotFound){t(e);return}t(undefined,r&&r.cursor&&r.cursor.firstBatch&&r.cursor.firstBatch[0].n||0)}))}executeLegacy(e,t){const r={count:this.collectionName};const n=this.options;if(n.query){r.query=n.query}if(n.hint){r.hint=n.hint}if(typeof n.maxTimeMS==="number"){r.maxTimeMS=n.maxTimeMS}if(typeof n.skip==="number"){r.skip=n.skip}if(typeof n.limit==="number"){r.limit=n.limit}super.executeCommand(e,r,((e,r)=>{if(e){t(e);return}t(null,r.n)}))}}s(EstimatedDocumentCountOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=EstimatedDocumentCountOperation},1681:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=r(1371).MongoDBNamespace;class ExecuteDbAdminCommandOperation extends n{constructor(e,t,r){super(r);this.db=e;this.selector=t}execute(e){const t=this.db;const r=this.selector;const n=this.options;const a=new i("admin","$cmd");t.s.topology.command(a,r,n,((r,n)=>{if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new s("topology was destroyed"))}if(r)return o(e,r);o(e,null,n.result)}))}}e.exports=ExecuteDbAdminCommandOperation},2548:(e,t,r)=>{"use strict";const n=r(1371).maybePromise;const o=r(3111).MongoError;const s=r(1018).Aspect;const i=r(1018).OperationBase;const a=r(4485);const A=r(3111).isRetryableError;const c=r(1178).maxWireVersion;const l=r(1178).isUnifiedTopology;function executeOperation(e,t,r){if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!(t instanceof i)){throw new TypeError("This method requires a valid operation instance")}return n(e,r,(r=>{if(l(e)&&e.shouldCheckForSessionSupport()){return selectServerForSessionSupport(e,t,r)}let n,i;if(e.hasSessionSupport()){if(t.session==null){i=Symbol();n=e.startSession({owner:i});t.session=n}else if(t.session.hasEnded){return r(new o("Use of expired sessions is not permitted"))}}else if(t.session){return r(new o("Current topology does not support sessions"))}function executeCallback(e,o){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e,o)}try{if(t.hasAspect(s.EXECUTE_WITH_SELECTION)){executeWithServerSelection(e,t,executeCallback)}else{t.execute(executeCallback)}}catch(e){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e)}}))}function supportsRetryableReads(e){return c(e)>=6}function executeWithServerSelection(e,t,r){const n=t.readPreference||a.primary;const i=t.session&&t.session.inTransaction();if(i&&!n.equals(a.primary)){r(new o(`Read preference in a transaction must be primary, not: ${n.mode}`));return}const c={readPreference:n,session:t.session};function callbackWithRetry(n,o){if(n==null){return r(null,o)}if(!A(n)){return r(n)}e.selectServer(c,((e,n)=>{if(e||!supportsRetryableReads(n)){r(e,null);return}t.execute(n,r)}))}e.selectServer(c,((n,o)=>{if(n){r(n,null);return}const a=e.s.options.retryReads!==false&&t.session&&!i&&supportsRetryableReads(o)&&t.canRetryRead;if(t.hasAspect(s.RETRYABLE)&&a){t.execute(o,callbackWithRetry);return}t.execute(o,r)}))}function selectServerForSessionSupport(e,t,r){e.selectServer(a.primaryPreferred,(n=>{if(n){return r(n)}executeOperation(e,t,r)}))}e.exports=executeOperation},9961:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(3994).ReadPreference;const a=r(1178).maxWireVersion;const A=r(3111).MongoError;class FindOperation extends n{constructor(e,t,r,n){super(n);this.ns=t;this.cmd=r;this.readPreference=i.resolve(e,this.options)}execute(e,t){this.server=e;this.readPreference=i.resolve(this,this.options);if(typeof this.cmd.allowDiskUse!=="undefined"&&a(e)<4){t(new A("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}if(this.explain){this.options.explain=this.explain.verbosity}const r=this.cursorState||{};e.query(this.ns.toString(),this.cmd,r,this.options,t)}}s(FindOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]);e.exports=FindOperation},711:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyRetryableWrites;const s=r(1371).applyWriteConcern;const i=r(1371).decorateWithCollation;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1178).maxWireVersion;const h=r(9386).MongoError;const d=r(1018).Aspect;const g=r(1018).defineAspects;const p=r(1371).decorateWithExplain;class FindAndModifyOperation extends n{constructor(e,t,r,n,o){super(o);this.collection=e;this.query=t;this.sort=r;this.doc=n}execute(e){const t=this.collection;const r=this.query;const n=A(this.sort);const d=this.doc;let g=this.options;let E={findAndModify:t.collectionName,query:r};if(n){E.sort=n}E.new=g.new?true:false;E.remove=g.remove?true:false;E.upsert=g.upsert?true:false;const m=g.projection||g.fields;if(m){E.fields=m}if(g.arrayFilters){E.arrayFilters=g.arrayFilters}if(d&&!g.remove){E.update=d}if(g.maxTimeMS)E.maxTimeMS=g.maxTimeMS;g.serializeFunctions=g.serializeFunctions||t.s.serializeFunctions;g.checkKeys=false;g=o(g,t.s.db);g=s(g,{db:t.s.db,collection:t},g);if(g.writeConcern){E.writeConcern=g.writeConcern}if(g.bypassDocumentValidation===true){E.bypassDocumentValidation=g.bypassDocumentValidation}g.readPreference=l.primary;try{i(E,t,g)}catch(t){return e(t,null)}if(g.hint){const r=g.writeConcern&&g.writeConcern.w===0;if(r||u(t.s.topology)<8){e(new h("The current topology does not support a hint on findAndModify commands"));return}E.hint=g.hint}if(this.explain){if(u(t.s.topology)<4){e(new h(`server does not support explain on findAndModify`));return}E=p(E,this.explain)}a(t.s.db,E,g,((t,r)=>{if(t)return c(e,t,null);return c(e,null,r)}))}}g(FindAndModifyOperation,[d.EXPLAINABLE]);e.exports=FindAndModifyOperation},4497:(e,t,r)=>{"use strict";const n=r(1371).handleCallback;const o=r(1018).OperationBase;const s=r(1371).toError;const i=r(1018).Aspect;const a=r(1018).defineAspects;class FindOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.query=t}execute(e){const t=this.collection;const r=this.query;const o=this.options;try{const i=t.find(r,o).limit(-1).batchSize(1);i.next(((t,r)=>{if(t!=null)return n(e,s(t),null);n(e,null,r)}))}catch(t){e(t)}}}a(FindOneOperation,[i.EXPLAINABLE]);e.exports=FindOneOperation},5841:(e,t,r)=>{"use strict";const n=r(711);class FindOneAndDeleteOperation extends n{constructor(e,t,r){const n=Object.assign({},r);n.fields=r.projection;n.remove=true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}super(e,t,n.sort,null,n)}}e.exports=FindOneAndDeleteOperation},4316:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndReplaceOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Replacement parameter must be an object")}if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndReplaceOperation},1925:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndUpdateOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Update parameter must be an object")}if(!s(r)){throw new TypeError("Update document requires atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndUpdateOperation},8169:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1018).OperationBase;const i=r(1371).decorateCommand;const a=r(1371).decorateWithReadConcern;const A=r(2226).executeCommand;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1371).toError;class GeoHaystackSearchOperation extends s{constructor(e,t,r,n){super(n);this.collection=e;this.x=t;this.y=r}execute(e){const t=this.collection;const r=this.x;const n=this.y;let o=this.options;let s={geoSearch:t.collectionName,near:[r,n]};s=i(s,o,["readPreference","session"]);o=Object.assign({},o);o.readPreference=l.resolve(t,o);a(s,t,o);A(t.s.db,s,o,((t,r)=>{if(t)return c(e,t);if(r.err||r.errmsg)c(e,u(r));c(e,null,r)}))}}o(GeoHaystackSearchOperation,n.READ_OPERATION);e.exports=GeoHaystackSearchOperation},7809:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(2226).indexInformation;class IndexExistsOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.indexes=t}execute(e){const t=this.collection;const r=this.indexes;const n=this.options;s(t.s.db,t.collectionName,n,((t,n)=>{if(t!=null)return o(e,t,null);if(!Array.isArray(r))return o(e,null,n[r]!=null);for(let t=0;t{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexInformationOperation extends n{constructor(e,t,r){super(r);this.db=e;this.name=t}execute(e){const t=this.db;const r=this.name;const n=this.options;o(t,r,n,e)}}e.exports=IndexInformationOperation},4218:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexesOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;let r=this.options;r=Object.assign({},{full:true},r);o(t.s.db,t.collectionName,r,e)}}e.exports=IndexesOperation},3592:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(6976);const s=r(3994).MongoError;const i=r(2296).prepareDocs;class InsertManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.docs=t}execute(e){const t=this.collection;let r=this.docs;const n=this.options;if(!Array.isArray(r)){return e(s.create({message:"docs parameter must be an array of documents",driver:true}))}n["serializeFunctions"]=n["serializeFunctions"]||t.s.serializeFunctions;r=i(t,r,n);const a=r.map((e=>({insertOne:{document:e}})));const A=new o(t,a,n);A.execute(((t,n)=>{if(t)return e(t,null);e(null,mapInsertManyResults(r,n))}))}}function mapInsertManyResults(e,t){const r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};if(t.getLastOp()){r.result.opTime=t.getLastOp()}return r}e.exports=InsertManyOperation},9915:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(1018).OperationBase;const s=r(2296).insertDocuments;class InsertOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.doc=t}execute(e){const t=this.collection;const r=this.doc;const o=this.options;if(Array.isArray(r)){return e(n.create({message:"doc parameter must be an object",driver:true}))}s(t,[r],o,((t,n)=>{if(e==null)return;if(t&&e)return e(t);if(n==null)return e(null,{result:{ok:1}});n.insertedCount=n.result.n;n.insertedId=r._id;if(e)e(null,n)}))}}e.exports=InsertOneOperation},4956:(e,t,r)=>{"use strict";const n=r(43);const o=r(1371).handleCallback;class IsCappedOperation extends n{constructor(e,t){super(e,t)}execute(e){super.execute(((t,r)=>{if(t)return o(e,t);o(e,null,!!(r&&r.capped))}))}}e.exports=IsCappedOperation},840:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=r(147);const A=3;function listCollectionsTransforms(e){const t=`${e}.`;return{doc:e=>{const r=e.name.indexOf(t);if(e.name&&r===0){e.name=e.name.substr(r+t.length)}return e}}}class ListCollectionsOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.db=e;this.filter=t;this.nameOnly=!!this.options.nameOnly;if(typeof this.options.batchSize==="number"){this.batchSize=this.options.batchSize}}execute(e,t){if(i(e){if(r&&r.message&&r.message.documents&&Array.isArray(r.message.documents)){r.message.documents=r.message.documents.map(o.doc)}t(e,r)}));return}const r={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,r,t)}}s(ListCollectionsOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListCollectionsOperation},9929:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1371).MongoDBNamespace;class ListDatabasesOperation extends n{constructor(e,t){super(e,t);this.ns=new i("admin","$cmd")}execute(e,t){const r={listDatabases:1};if(this.options.nameOnly){r.nameOnly=Number(r.nameOnly)}if(this.options.filter){r.filter=this.options.filter}if(typeof this.options.authorizedDatabases==="boolean"){r.authorizedDatabases=this.options.authorizedDatabases}super.executeCommand(e,r,t)}}s(ListDatabasesOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListDatabasesOperation},28:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=3;class ListIndexesOperation extends n{constructor(e,t){super(e,t,{fullResponse:true});this.collectionNamespace=e.s.namespace}execute(e,t){const r=i(e);if(r{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).handleCallback;const c=r(1371).isObject;const l=r(8275).loadDb;const u=r(1018).OperationBase;const h=r(3994).ReadPreference;const d=r(1371).toError;const g=r(1018).Aspect;const p=r(1018).defineAspects;const E=r(1371).decorateWithExplain;const m=r(1178).maxWireVersion;const C=r(9386).MongoError;const I=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class MapReduceOperation extends u{constructor(e,t,r,n){super(n);this.collection=e;this.map=t;this.reduce=r}execute(e){const t=this.collection;const r=this.map;const o=this.reduce;let c=this.options;let u={mapReduce:t.collectionName,map:r,reduce:o};for(let e in c){if("scope"===e){u[e]=processScope(c[e])}else{if(I.indexOf(e)===-1){u[e]=c[e]}}}c=Object.assign({},c);c.readPreference=h.resolve(t,c);if(c.readPreference!==false&&c.readPreference!=="primary"&&c["out"]&&c["out"].inline!==1&&c["out"]!=="inline"){c.readPreference="primary";n(u,{db:t.s.db,collection:t},c)}else{i(u,t,c)}if(c.bypassDocumentValidation===true){u.bypassDocumentValidation=c.bypassDocumentValidation}try{s(u,t,c)}catch(t){return e(t,null)}if(this.explain){if(m(t.s.topology)<9){e(new C(`server does not support explain on mapReduce`));return}u=E(u,this.explain)}a(t.s.db,u,c,((r,n)=>{if(r)return A(e,r);if(1!==n.ok||n.err||n.errmsg){return A(e,d(n))}if(this.explain)return e(undefined,n);const o={};if(n.timeMillis)o["processtime"]=n.timeMillis;if(n.counts)o["counts"]=n.counts;if(n.timing)o["timing"]=n.timing;if(n.results){if(c["verbose"]==null||!c["verbose"]){return A(e,null,n.results)}return A(e,null,{results:n.results,stats:o})}let s=null;if(n.result!=null&&typeof n.result==="object"){const e=n.result;let r=l();s=new r(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else{s=t.s.db.collection(n.result)}if(c["verbose"]==null||!c["verbose"]){return A(e,r,s)}A(e,r,{collection:s,stats:o})}))}}function processScope(e){if(!c(e)||e._bsontype==="ObjectID"){return e}const t=Object.keys(e);let r;const n={};for(let s=t.length-1;s>=0;s--){r=t[s];if("function"===typeof e[r]){n[r]=new o(String(e[r]))}else{n[r]=processScope(e[r])}}return n}p(MapReduceOperation,[g.EXPLAINABLE]);e.exports=MapReduceOperation},1018:(e,t,r)=>{"use strict";const n=r(5293).Explain;const o=r(3111).MongoError;const s={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"),EXPLAINABLE:Symbol("EXPLAINABLE")};class OperationBase{constructor(e){this.options=Object.assign({},e);if(this.hasAspect(s.EXPLAINABLE)){this.explain=n.fromOptions(e)}else if(this.options.explain!==undefined){throw new o(`explain is not supported on this command`)}}hasAspect(e){if(this.constructor.aspects==null){return false}return 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 true}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}function defineAspects(e,t){if(!Array.isArray(t)&&!(t instanceof Set)){t=[t]}t=new Set(t);Object.defineProperty(e,"aspects",{value:t,writable:false});return t}e.exports={Aspect:s,defineAspects:defineAspects,OperationBase:OperationBase}},43:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;class OptionsOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;const r=this.options;t.s.db.listCollections({name:t.collectionName},r).toArray(((r,n)=>{if(r)return o(e,r);if(n.length===0){return o(e,s.create({message:`collection ${t.namespace} not found`,driver:true}))}o(e,r,n[0].options||null)}))}}e.exports=OptionsOperation},3969:(e,t,r)=>{"use strict";const n=r(499);class ProfilingLevelOperation extends n{constructor(e,t,r){super(e,r)}_buildCommand(){const e={profile:-1};return e}execute(e){super.execute(((t,r)=>{if(t==null&&r.ok===1){const t=r.was;if(t===0)return e(null,"off");if(t===1)return e(null,"slow_only");if(t===2)return e(null,"all");return e(new Error("Error: illegal profiling level value "+t),null)}else{t!=null?e(t,null):e(new Error("Error with profile command"),null)}}))}}e.exports=ProfilingLevelOperation},6331:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(2291).serverType;const a=r(2291).ServerType;const A=r(3994).MongoError;class ReIndexOperation extends s{constructor(e,t){super(e,t);this.collectionName=e.collectionName}execute(e,t){if(i(e)!==a.Standalone){t(new A(`reIndex can only be executed on standalone servers.`));return}super.executeCommand(e,{reIndex:this.collectionName},((e,r)=>{if(e){t(e);return}t(null,!!r.ok)}))}}o(ReIndexOperation,[n.EXECUTE_WITH_SELECTION]);e.exports=ReIndexOperation},1969:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;const a=r(2481);class RemoveUserOperation extends o{constructor(e,t,r){const n={};const o=a.fromOptions(r);if(o!=null){n.writeConcern=o}if(r.dbName){n.dbName=r.dbName}if(typeof r.maxTimeMS==="number"){n.maxTimeMS=r.maxTimeMS}super(e,n);this.username=t}_buildCommand(){const e=this.username;const t={dropUser:e};return t}execute(e){super.execute(((t,r)=>{if(t)return i(e,t,null);i(e,t,r.ok?true:false)}))}}s(RemoveUserOperation,n.WRITE_OPERATION);e.exports=RemoveUserOperation},2808:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyWriteConcern;const s=r(1371).checkCollectionName;const i=r(2226).executeDbAdminCommand;const a=r(1371).handleCallback;const A=r(8275).loadCollection;const c=r(1371).toError;class RenameOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.newName=t}execute(e){const t=this.collection;const r=this.newName;const n=this.options;let l=A();s(r);const u=t.namespace;const h=t.s.namespace.withCollection(r).toString();const d=typeof n.dropTarget==="boolean"?n.dropTarget:false;const g={renameCollection:u,to:h,dropTarget:d};o(g,{db:t.s.db,collection:t},n);i(t.s.db.admin().s.db,g,n,((n,o)=>{if(n)return a(e,n,null);if(o.errmsg)return a(e,c(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,r,t.s.pkFactory,t.s.options))}catch(n){return a(e,c(n),null)}}))}}e.exports=RenameOperation},2508:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;class ReplaceOneOperation extends n{constructor(e,t,r,n){super(n);if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}this.collection=e;this.filter=t;this.replacement=r}execute(e){const t=this.collection;const r=this.filter;const n=this.replacement;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>replaceCallback(t,r,n,e)))}}function replaceCallback(e,t,r,n){if(n==null)return;if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?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=[r];if(n)n(null,t)}e.exports=ReplaceOneOperation},1363:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).defineAspects;const s=r(1018).Aspect;class RunCommandOperation extends n{constructor(e,t,r){super(e,r);this.command=t}execute(e,t){const r=this.command;this.executeCommand(e,r,t)}}o(RunCommandOperation,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]);e.exports=RunCommandOperation},6301:(e,t,r)=>{"use strict";const n=r(499);const o=new Set(["off","slow_only","all"]);class SetProfilingLevelOperation extends n{constructor(e,t,r){let n=0;if(t==="off"){n=0}else if(t==="slow_only"){n=1}else if(t==="all"){n=2}super(e,r);this.level=t;this.profile=n}_buildCommand(){const e=this.profile;const t={profile:e};return t}execute(e){const t=this.level;if(!o.has(t)){return e(new Error("Error: illegal profiling level value "+t))}super.execute(((r,n)=>{if(r==null&&n.ok===1)return e(null,t);return r!=null?e(r,null):e(new Error("Error with profile command"),null)}))}}e.exports=SetProfilingLevelOperation},968:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;class StatsOperation extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection;const t=this.options;const r={collStats:e.collectionName};if(t["scale"]!=null){r["scale"]=t["scale"]}return r}}s(StatsOperation,n.READ_OPERATION);e.exports=StatsOperation},9350:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateManyOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=true;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateManyOperation,[i.EXPLAINABLE]);e.exports=UpdateManyOperation},9068:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateOneOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateOneOperation,[i.EXPLAINABLE]);e.exports=UpdateOneOperation},9263:(e,t,r)=>{"use strict";const n=r(499);class ValidateCollectionOperation extends n{constructor(e,t,r){let n={validate:t};const o=Object.keys(r);for(let e=0;e{if(r!=null)return e(r,null);if(n.ok===0)return e(new Error("Error with validate command"),null);if(n.result!=null&&n.result.constructor!==String)return e(new Error("Error with validation data"),null);if(n.result!=null&&n.result.match(/exception|corrupt/)!=null)return e(new Error("Error: invalid collection "+t),null);if(n.valid!=null&&!n.valid)return e(new Error("Error: invalid collection "+t),null);return e(null,n)}))}}e.exports=ValidateCollectionOperation},7289:e=>{"use strict";class ReadConcern{constructor(e){if(e!=null){this.level=e}}static fromOptions(e){if(e==null){return}if(e.readConcern){if(e.readConcern instanceof ReadConcern){return e.readConcern}return new ReadConcern(e.readConcern.level)}if(e.level){return new ReadConcern(e.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=ReadConcern},2048:(e,t,r)=>{"use strict";const n=r(8589).oF;const o=r(3994).MongoError;const s=r(3994).Mongos;const i=r(7159);const a=r(8421);const A=r(8589).yh;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"];class Mongos extends n{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var n=0;n0?t.socketOptions:t;C=l(C,I);this.s={coreTopology:new s(E,C),sCapabilities:null,debug:C.debug,storeOptions:g,clonedOptions:C,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var n=["timeout","error","close"];n.forEach((function(e){r.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.close(true);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect");r.s.store.execute()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){var e=["timeout","error","close","fullsetup"];e.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.on("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r)}));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("joined",relay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.connect(e)}}Object.defineProperty(Mongos.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=Mongos},2632:(e,t,r)=>{"use strict";const n=r(3994).Topology;const o=r(8589).ug;const s=r(7159);const i=r(1371).translateOptions;class NativeTopology extends n{constructor(e,t){t=t||{};let r=Object.assign({},{cursorFactory:s,reconnect:false,emitError:typeof t.emitError==="boolean"?t.emitError:true,maxPoolSize:typeof t.maxPoolSize==="number"?t.maxPoolSize:typeof t.poolSize==="number"?t.poolSize:10,minPoolSize:typeof t.minPoolSize==="number"?t.minPoolSize:typeof t.minSize==="number"?t.minSize:0,monitorCommands:typeof t.monitorCommands==="boolean"?t.monitorCommands:false});r=i(r,t);var n=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;r=i(r,n);r.serverApi=t.serverApi;r.useUnifiedTopology=t.useUnifiedTopology;super(e,r)}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.lastIsMaster()==null)return null;this.s.sCapabilities=new o(this.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){super.command(e.toString(),t,r,n)}insert(e,t,r,n){super.insert(e.toString(),t,r,n)}update(e,t,r,n){super.update(e.toString(),t,r,n)}remove(e,t,r,n){super.remove(e.toString(),t,r,n)}}e.exports=NativeTopology},382:(e,t,r)=>{"use strict";const n=r(8421);const o=r(7159);const s=r(3994).MongoError;const i=r(8589).oF;const a=r(8589).yh;const A=r(3994).ReplSet;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class ReplSet extends i{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var i=0;i0?t.socketOptions:t;m=l(m,C);var I=new A(E,m);I.on("reconnect",(function(){r.emit("reconnect");p.execute()}));this.s={coreTopology:I,sCapabilities:null,tag:t.tag,storeOptions:g,clonedOptions:m,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise};if(m.debug){Object.defineProperty(this,"replset",{enumerable:true,get:function(){return I}})}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));var relay=function(e){return function(t,n){r.emit(e,t,n)}};var replsetRelay=function(e){return function(t,n){r.emit(e,t,n.lastIsMaster(),n)}};var relayHa=function(e,t){r.emit("ha",e,t);if(e==="start"){r.emit("ha_connect",e,t)}else if(e==="end"){r.emit("ha_ismaster",e,t)}};r.s.coreTopology.on("joined",replsetRelay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("ping",relay("ping"));r.s.coreTopology.on("ha",relayHa);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r,r)}));r.s.coreTopology.on("all",(function(){r.emit("all",null,r)}));var connectHandler=function(){r.s.coreTopology.once("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.once("close",errorHandler("close"));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var connectErrorHandler=function(){return function(e){["timeout","error","close"].forEach((function(e){r.s.coreTopology.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.s.coreTopology.destroy();try{t(e)}catch(e){if(!r.s.coreTopology.isConnected())process.nextTick((function(){throw e}))}}};r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach((e=>this.removeAllListeners(e)));super.close(e,t)}}Object.defineProperty(ReplSet.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=ReplSet},8421:(e,t,r)=>{"use strict";const n=r(3994).Server;const o=r(7159);const s=r(8589).oF;const i=r(8589).yh;const a=r(3994).MongoError;const A=r(1371).MAX_JS_INT;const c=r(1371).translateOptions;const l=r(1371).filterOptions;const u=r(1371).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","bsonRegExp","compression","promiseLibrary","monitorCommands"];class Server extends s{constructor(e,t,r){super();var s=this;r=l(r,h);const d=r.promiseLibrary;var g={force:false,bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:A};var p=r.store||new i(s,g);if(e.indexOf("/")!==-1){if(t!=null&&typeof t==="object"){r=t;t=null}}else if(t==null){throw a.create({message:"port must be specified",driver:true})}var E=typeof r.auto_reconnect==="boolean"?r.auto_reconnect:true;E=typeof r.autoReconnect==="boolean"?r.autoReconnect:E;var m=u({},{host:e,port:t,disconnectHandler:p,cursorFactory:o,reconnect:E,emitError:typeof r.emitError==="boolean"?r.emitError:true,size:typeof r.poolSize==="number"?r.poolSize:5,monitorCommands:typeof r.monitorCommands==="boolean"?r.monitorCommands:false});m=c(m,r);var C=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;m=c(m,C);this.s={coreTopology:new n(m),sCapabilities:null,clonedOptions:m,reconnect:m.reconnect,emitError:m.emitError,poolSize:m.size,storeOptions:g,store:p,host:e,port:t,options:r,sessionPool:null,sessions:new Set,promiseLibrary:d||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e=this.s.clonedOptions;if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var o=["timeout","error","close"];o.forEach((function(e){r.s.coreTopology.removeListener(e,n[e])}));r.s.coreTopology.removeListener("connect",connectErrorHandler);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect",r);r.s.store.execute()};var reconnectFailedHandler=function(e){r.emit("reconnectFailed",e);r.s.store.flush(e)};var destroyHandler=function(){r.s.store.flush()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){["timeout","error","close","destroy"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("destroy",destroyHandler);r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n={timeout:connectErrorHandler("timeout"),error:connectErrorHandler("error"),close:connectErrorHandler("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.once("timeout",n.timeout);r.s.coreTopology.once("error",n.error);r.s.coreTopology.once("close",n.close);r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.on("reconnectFailed",reconnectFailedHandler);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("attemptReconnect",relay("attemptReconnect"));r.s.coreTopology.on("monitoring",relay("monitoring"));r.s.coreTopology.connect(e)}}Object.defineProperty(Server.prototype,"poolSize",{enumerable:true,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(Server.prototype,"autoReconnect",{enumerable:true,get:function(){return this.s.reconnect}});Object.defineProperty(Server.prototype,"host",{enumerable:true,get:function(){return this.s.host}});Object.defineProperty(Server.prototype,"port",{enumerable:true,get:function(){return this.s.port}});e.exports=Server},8589:(e,t,r)=>{"use strict";const n=r(2361),o=r(3994).MongoError,s=r(3837).format,i=r(3994).ReadPreference,a=r(3994).Sessions.ClientSession;var Store=function(e,t){var r=this;var n=[];t=t||{force:false,bufferMaxEntries:-1};this.s={storedOps:n,storeOptions:t,topology:e};Object.defineProperty(this,"length",{enumerable:true,get:function(){return r.s.storedOps.length}})};Store.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};Store.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};Store.prototype.flush=function(e){while(this.s.storedOps.length>0){this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:true}))}};var A=["primary","primaryPreferred","nearest","secondaryPreferred"];var c=["secondary","secondaryPreferred"];Store.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];var r=typeof e.executePrimary==="boolean"?e.executePrimary:true;var n=typeof e.executeSecondary==="boolean"?e.executeSecondary:true;while(t.length>0){var o=t.shift();if(o.t==="cursor"){if(r&&n){o.o[o.m].apply(o.o,o.p)}else if(r&&o.o.options&&o.o.options.readPreference&&A.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}else if(!r&&n&&o.o.options&&o.o.options.readPreference&&c.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}}else if(o.t==="auth"){this.s.topology[o.t].apply(this.s.topology,o.o)}else{if(r&&n){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(r&&o.op&&o.op.readPreference&&A.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(!r&&n&&o.op&&o.op.readPreference&&c.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}}}};Store.prototype.all=function(){return this.s.storedOps};var ServerCapabilities=function(e){var setup_get_property=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var t=false;var r=false;var n=false;var o=false;var s=false;var i=false;var a=e.maxWriteBatchSize||1e3;var A=false;var c=false;if(e.minWireVersion>=0){n=true}if(e.maxWireVersion>=1){t=true;o=true}if(e.maxWireVersion>=2){r=true}if(e.maxWireVersion>=3){s=true;i=true}if(e.maxWireVersion>=5){A=true;c=true}if(e.minWireVersion==null){e.minWireVersion=0}if(e.maxWireVersion==null){e.maxWireVersion=0}setup_get_property(this,"hasAggregationCursor",t);setup_get_property(this,"hasWriteCommands",r);setup_get_property(this,"hasTextSearch",n);setup_get_property(this,"hasAuthCommands",o);setup_get_property(this,"hasListCollectionsCommand",s);setup_get_property(this,"hasListIndexesCommand",i);setup_get_property(this,"minWireVersion",e.minWireVersion);setup_get_property(this,"maxWireVersion",e.maxWireVersion);setup_get_property(this,"maxNumberOfDocsInBatch",a);setup_get_property(this,"commandsTakeWriteConcern",A);setup_get_property(this,"commandsTakeCollation",c)};class TopologyBase extends n{constructor(){super();this.setMaxListeners(Infinity)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new a(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.s.coreTopology.lastIsMaster()==null)return null;this.s.sCapabilities=new ServerCapabilities(this.s.coreTopology.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){this.s.coreTopology.command(e.toString(),t,i.translate(r),n)}insert(e,t,r,n){this.s.coreTopology.insert(e.toString(),t,r,n)}update(e,t,r,n){this.s.coreTopology.update(e.toString(),t,r,n)}remove(e,t,r,n){this.s.coreTopology.remove(e.toString(),t,r,n)}isConnected(e){e=e||{};e=i.translate(e);return this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,r){r=r||{};r=i.translate(r);r.disconnectHandler=this.s.store;r.topology=this;return this.s.coreTopology.cursor(e,t,r)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,r){return this.s.coreTopology.selectServer(e,t,r)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach((e=>e.endSession()));if(this.s.sessionPool){this.s.sessionPool.endAllPooledSessions()}if(e===true){this.s.storeOptions.force=e;this.s.store.flush()}this.s.coreTopology.destroy({force:typeof e==="boolean"?e:false},t)}}Object.defineProperty(TopologyBase.prototype,"bson",{enumerable:true,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(TopologyBase.prototype,"parserType",{enumerable:true,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(TopologyBase.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(TopologyBase.prototype,"type",{enumerable:true,get:function(){return this.s.coreTopology.type}});t.yh=Store;t.ug=ServerCapabilities;t.oF=TopologyBase},8729:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(7310);const s=r(3837).format;const i=r(3994).Logger;const a=r(7578);const A=r(7289);const c=r(3477);const l=r(3111).MongoParseError;e.exports=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};let n;try{n=o.parse(e,true)}catch(e){return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:"){return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"))}if(n.protocol==="mongodb:"){return parseHandler(e,t,r)}if(n.hostname.split(".").length<3){return r(new Error("URI does not have hostname, domain name and tld"))}n.domainLength=n.hostname.split(".").length;const s=e.substring("mongodb+srv://".length).split("/")[0];if(s.match(",")){return r(new Error("Invalid URI, cannot contain multiple hostnames"))}if(n.port){return r(new Error("Ports not accepted with `mongodb+srv` URIs"))}let i=`_mongodb._tcp.${n.host}`;a.resolveSrv(i,(function(e,o){if(e)return r(e);if(o.length===0){return r(new Error("No addresses found at host"))}for(let e=0;e1){return r(new l("Multiple text records not allowed"))}n=n[0].join("");const e=c.parse(n);const t=Object.keys(e);if(Object.keys(t).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new l("Load balancer mode requires driver version 4+"))}if(t.some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new l("Text record must only set `authSource` or `replicaSet`"))}if(t.length>0){u.push(n)}}if(u.length){A+=`?${u.join("&")}`}parseHandler(A,t,r)}))}))};function matchesParentDomain(e,t){let r=/^.*?\./;let n=`.${e.replace(r,"")}`;let o=`.${t.replace(r,"")}`;if(n.endsWith(o))return true;else return false}function parseHandler(e,t,r){let n,o;try{n=parseConnectionString(e,t)}catch(e){o=e}return o?r(o,null):r(null,n)}function parseConnectionString(e,t){let r="";let a="";let c="";let u="admin";let h=o.parse(e,true);if((h.hostname==null||h.hostname==="")&&e.indexOf(".sock")===-1){throw new Error("No hostname or hostnames provided in connection string")}if(h.port==="0"){throw new Error("Invalid port (zero) with hostname")}if(!isNaN(parseInt(h.port,10))&&parseInt(h.port,10)>65535){throw new Error("Invalid port (larger than 65535) with hostname")}if(h.path&&h.path.length>0&&h.path[0]!=="/"&&e.indexOf(".sock")===-1){throw new Error("Missing delimiting slash between hosts and options")}if(h.query){for(let e in h.query){if(e.indexOf("::")!==-1){throw new Error("Double colon in host identifier")}if(h.query[e]===""){throw new Error("Query parameter "+e+" is an incomplete value pair")}}}if(h.auth){let t=h.auth.split(":");if(e.indexOf(h.auth)!==-1&&t.length>2){throw new Error("Username with password containing an unescaped colon")}if(e.indexOf(h.auth)!==-1&&h.auth.indexOf("@")!==-1){throw new Error("Username containing an unescaped at-sign")}}let d=e.split("?").shift();let g=d.split(",");let p=[];for(let e=0;e1&&t.path.indexOf("::")===-1){throw new Error("Slash in host identifier")}else{throw new Error("Double colon in host identifier")}}}if(e.indexOf("?")!==-1){c=e.substr(e.indexOf("?")+1);r=e.substring("mongodb://".length,e.indexOf("?"))}else{r=e.substring("mongodb://".length)}if(r.indexOf("@")!==-1){a=r.split("@")[0];r=r.split("@")[1]}if(r.split("/").length>2){throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash")}if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){u=r.split(".sock/")[1];if(u.indexOf("/")!==-1){if(u.split("/").length===2&&u.split("/")[1].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}r=r.split("/",r.indexOf(".sock")+".sock".length)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2){if(r.split("/")[2].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}u=r.split("/")[1];r=r.split("/")[0]}r=decodeURIComponent(r);let E={};let m=a||"";let C=m.split(":",2);let I=decodeURIComponent(C[0]);if(C[0]!==encodeURIComponent(I)){throw new Error("Username contains an illegal unescaped character")}C[0]=I;if(C[1]){let e=decodeURIComponent(C[1]);if(C[1]!==encodeURIComponent(e)){throw new Error("Password contains an illegal unescaped character")}C[1]=e}if(C.length===2)E.auth={user:C[0],password:C[1]};if(t&&t.auth!=null)E.auth=t.auth;let y;let B;let Q;let b;let w={socketOptions:{}};let S={read_preference_tags:[]};let v={socketOptions:{}};let R={socketOptions:{}};E.server_options=w;E.db_options=S;E.rs_options=v;E.mongos_options=R;if(e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);if(t.indexOf("@")!==-1)t=t.split("@")[1];t=decodeURIComponent(t);Q=[{domain_socket:t}]}else{y=r;let e={};Q=y.split(",").map((function(t){let r,n,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t)){r=o[1];n=parseInt(o[2],10)||27017}else{let e=t.split(":",2);r=e[0]||"localhost";n=e[1]!=null?parseInt(e[1],10):27017;if(r.indexOf("?")!==-1)r=r.split(/\?/)[0]}if(e[r+"_"+n])return null;e[r+"_"+n]=1;return{host:r,port:n}})).filter((function(e){return e!=null}))}E.dbName=u||"admin";B=(c||"").split(/[&;]/);if(B.some((e=>e.toLowerCase()==="loadbalanced"))){throw new l("Load balancer mode requires driver version 4+")}B.forEach((function(e){if(!e)return;var t=e.split("="),r=t[0],o=t[1];switch(r){case"slaveOk":case"slave_ok":w.slave_ok=o==="true";S.slaveOk=o==="true";break;case"maxPoolSize":case"poolSize":w.poolSize=parseInt(o,10);v.poolSize=parseInt(o,10);break;case"appname":E.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":w.auto_reconnect=o==="true";break;case"ssl":if(o==="prefer"){w.ssl=o;v.ssl=o;R.ssl=o;break}w.ssl=o==="true";v.ssl=o==="true";R.ssl=o==="true";break;case"sslValidate":w.sslValidate=o==="true";v.sslValidate=o==="true";R.sslValidate=o==="true";break;case"replicaSet":case"rs_name":v.rs_name=o;break;case"reconnectWait":v.reconnectWait=parseInt(o,10);break;case"retries":v.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":v.read_secondary=o==="true";break;case"fsync":S.fsync=o==="true";break;case"journal":S.j=o==="true";break;case"safe":S.safe=o==="true";break;case"nativeParser":case"native_parser":S.native_parser=o==="true";break;case"readConcernLevel":S.readConcern=new A(o);break;case"connectTimeoutMS":w.socketOptions.connectTimeoutMS=parseInt(o,10);v.socketOptions.connectTimeoutMS=parseInt(o,10);R.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":w.socketOptions.socketTimeoutMS=parseInt(o,10);v.socketOptions.socketTimeoutMS=parseInt(o,10);R.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":S.w=parseInt(o,10);if(isNaN(S.w))S.w=o;break;case"authSource":S.authSource=o;break;case"gssapiServiceName":S.gssapiServiceName=o;break;case"authMechanism":if(o==="GSSAPI"){if(E.auth==null){let e=decodeURIComponent(m);if(e.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");E.auth={user:e,password:null}}else{E.auth.user=decodeURIComponent(E.auth.user)}}else if(o==="MONGODB-X509"){E.auth={user:decodeURIComponent(m)}}if(o!=="GSSAPI"&&o!=="MONGODB-X509"&&o!=="MONGODB-CR"&&o!=="DEFAULT"&&o!=="SCRAM-SHA-1"&&o!=="SCRAM-SHA-256"&&o!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");S.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(",");let t={};e.forEach((function(e){let r=e.split(":");t[r[0]]=r[1]}));S.authMechanismProperties=t;if(typeof t.SERVICE_NAME==="string")S.gssapiServiceName=t.SERVICE_NAME;if(typeof t.SERVICE_REALM==="string")S.gssapiServiceRealm=t.SERVICE_REALM;if(typeof t.CANONICALIZE_HOST_NAME==="string")S.gssapiCanonicalizeHostName=t.CANONICALIZE_HOST_NAME==="true"?true:false}break;case"wtimeoutMS":S.wtimeout=parseInt(o,10);break;case"readPreference":if(!n.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");S.readPreference=o;break;case"maxStalenessSeconds":S.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{o=decodeURIComponent(o);let e={};if(o==null||o===""){S.read_preference_tags.push(e);break}let t=o.split(/,/);for(let r=0;r9){throw new Error("zlibCompressionLevel must be an integer between -1 and 9")}b.zlibCompressionLevel=e;w.compression=b}break;case"retryWrites":S.retryWrites=o==="true";break;case"minSize":S.minSize=parseInt(o,10);break;default:{let e=i("URL Parser");e.warn(`${r} is not supported as a connection string option`)}break}}));if(S.read_preference_tags.length===0){S.read_preference_tags=null}if((S.w===-1||S.w===0)&&(S.journal===true||S.fsync===true||S.safe===true))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");if(!S.readPreference){S.readPreference="primary"}S=Object.assign(S,t);E.servers=Q;return E}},1371:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(2481);var shallowClone=function(e){var t={};for(var r in e)t[r]=e[r];return t};var getSingleProperty=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var s=t.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){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)']]")}};var i=t.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0){return null}for(var r=0;r{if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!Array.isArray(r)){throw new TypeError("This method requires an array of arguments to apply")}o=o||{};const s=e.s.promiseLibrary;let i=r[r.length-1];let a,A,c;if(!o.skipSessions&&e.hasSessionSupport()){A=r[r.length-2];if(A==null||A.session==null){c=Symbol();a=e.startSession({owner:c});const t=r.length-2;r[t]=Object.assign({},r[t],{session:a})}else if(A.session&&A.session.hasEnded){throw new n("Use of expired sessions is not permitted")}}const makeExecuteCallback=(e,t)=>function executeCallback(r,n){if(a&&a.owner===c&&!o.returnsCursor){a.endSession((()=>{delete A.session;if(r)return t(r);e(n)}))}else{if(r)return t(r);e(n)}};if(typeof i==="function"){i=r.pop();const e=makeExecuteCallback((e=>i(null,e)),(e=>i(e,null)));r.push(e);try{return t.apply(null,r)}catch(t){e(t);throw t}}if(r[r.length-1]!=null){throw new TypeError("final argument to `executeLegacyOperation` must be a callback")}return new s((function(e,n){const o=makeExecuteCallback(e,n);r[r.length-1]=o;try{return t.apply(null,r)}catch(e){o(e)}}))};function applyRetryableWrites(e,t){if(t&&t.s.options.retryWrites){e.retryWrites=true}return e}function applyWriteConcern(e,t,r){r=r||{};const n=t.db;const s=t.collection;if(r.session&&r.session.inTransaction()){if(e.writeConcern){delete e.writeConcern}return e}const i=o.fromOptions(r);if(i){return Object.assign(e,{writeConcern:i})}if(s&&s.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)})}if(n&&n.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)})}return e}function isPromiseLike(e){return e&&typeof e.then==="function"}function decorateWithCollation(e,t,r){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(r.collation&&typeof r.collation==="object"){if(s&&s.commandsTakeCollation){e.collation=r.collation}else{throw new n(`Current topology does not support collation`)}}}function decorateWithReadConcern(e,t,r){if(r&&r.session&&r.session.inTransaction()){return}let n=Object.assign({},e.readConcern||{});if(t.s.readConcern){Object.assign(n,t.s.readConcern)}if(Object.keys(n).length>0){Object.assign(e,{readConcern:n})}}function decorateWithExplain(e,t){if(e.explain){return e}return{explain:e,verbosity:t.verbosity}}const u=+process.version.split(".")[0].substring(1);const emitProcessWarning=e=>u<=6?process.emitWarning(e,"DeprecationWarning",g):process.emitWarning(e,{type:"DeprecationWarning",code:g});const emitConsoleWarning=e=>console.error(e);const h=process.emitWarning?emitProcessWarning:emitConsoleWarning;function defaultMsgHandler(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}function deprecateOptions(e,t){if(process.noDeprecation===true){return t}const r=e.msgHandler?e.msgHandler:defaultMsgHandler;const n=new Set;function deprecated(){const o=arguments[e.optionsIndex];if(!c(o)||Object.keys(o).length===0){return t.apply(this,arguments)}e.deprecatedOptions.forEach((t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!n.has(t)){n.add(t);const o=r(e.name,t);h(o);if(this&&this.getLogger){const e=this.getLogger();if(e){e.warn(o)}}}}));return t.apply(this,arguments)}Object.setPrototypeOf(deprecated,t);if(t.prototype){deprecated.prototype=t.prototype}return deprecated}const d={};try{r(1749);d.ASYNC_ITERATOR=true}catch(e){d.ASYNC_ITERATOR=false}class MongoDBNamespace{constructor(e,t){this.db=e;this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new MongoDBNamespace(this.db,e)}static fromString(e){if(!e){throw new Error(`Cannot parse namespace from "${e}"`)}const t=e.indexOf(".");return new MongoDBNamespace(e.substring(0,t),e.substring(t+1))}}function*makeCounter(e){let t=e||0;while(true){const e=t;t+=1;yield e}}function maybePromise(e,t,r){const n=e&&e.s&&e.s.promiseLibrary||Promise;let o;if(typeof t!=="function"){o=new n(((e,r)=>{t=(t,n)=>{if(t)return r(t);e(n)}}))}r((function(e,r){if(e!=null){try{t(e)}catch(e){return process.nextTick((()=>{throw e}))}return}t(e,r)}));return o}function now(){const e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}function calculateDurationInMs(e){if(typeof e!=="number"){throw TypeError("numeric value required to calculate duration")}const t=now()-e;return t<0?0:t}function makeInterruptableAsyncInterval(e,t){let r;let n;let o;let s=false;t=t||{};const i=t.interval||1e3;const a=t.minInterval||500;const A=typeof t.immediate==="boolean"?t.immediate:false;const c=typeof t.clock==="function"?t.clock:now;function wake(){const e=c();const t=e-o;const r=e-n;const s=i-r;o=e;if(ta){reschedule(a)}if(s<0){executeAndReschedule()}}function stop(){s=true;if(r){clearTimeout(r);r=null}n=0;o=0}function reschedule(e){if(s)return;clearTimeout(r);r=setTimeout(executeAndReschedule,e||i)}function executeAndReschedule(){o=0;n=c();e((e=>{if(e)throw e;reschedule(i)}))}if(A){executeAndReschedule()}else{n=c();reschedule()}return{wake:wake,stop:stop}}function hasAtomicOperators(e){if(Array.isArray(e)){return e.reduce(((e,t)=>e||hasAtomicOperators(t)),null)}return Object.keys(typeof e.toBSON!=="function"?e:e.toBSON()).map((e=>e[0])).indexOf("$")>=0}const g="MONGODB DRIVER";function emitWarning(e){if(process.emitWarning){return u<=6?process.emitWarning(e,undefined,g):process.emitWarning(e,{code:g})}else{return console.error(`[${g}] Warning:`,e)}}const p=new Set;function emitWarningOnce(e){if(!p.has(e)){p.add(e);return emitWarning(e)}}function isSuperset(e,t){e=Array.isArray(e)?new Set(e):e;t=Array.isArray(t)?new Set(t):t;for(const r of t){if(!e.has(r)){return false}}return true}function isRecord(e,t){const r=Object.prototype.toString;const n=Object.prototype.hasOwnProperty;const isObject=e=>r.call(e)==="[object Object]";if(!isObject(e)){return false}const o=e.constructor;if(o&&o.prototype){if(!isObject(o.prototype)){return false}if(!n.call(o.prototype,"isPrototypeOf")){return false}}if(t){const r=Object.keys(e);return isSuperset(r,t)}return true}function deepCopy(e){if(e==null){return e}else if(Array.isArray(e)){return e.map((e=>deepCopy(e)))}else if(isRecord(e)){const t={};for(const r in e){t[r]=deepCopy(e[r])}return t}const t=e.constructor;if(t){switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}}return e}function parsePackageVersion(e){const t=e.version.split(".").map((e=>Number.parseInt(e,10)));return{major:t[0],minor:t[1],patch:t[2]}}e.exports={filterOptions:filterOptions,mergeOptions:mergeOptions,translateOptions:translateOptions,shallowClone:shallowClone,getSingleProperty:getSingleProperty,checkCollectionName:a,toError:toError,formattedOrderClause:i,parseIndexOptions:parseIndexOptions,normalizeHintField:A,handleCallback:handleCallback,decorateCommand:decorateCommand,isObject:c,debugOptions:debugOptions,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:conditionallyMergeWriteConcern,executeLegacyOperation:executeLegacyOperation,applyRetryableWrites:applyRetryableWrites,applyWriteConcern:applyWriteConcern,isPromiseLike:isPromiseLike,decorateWithCollation:decorateWithCollation,decorateWithReadConcern:decorateWithReadConcern,decorateWithExplain:decorateWithExplain,deprecateOptions:deprecateOptions,SUPPORTS:d,MongoDBNamespace:MongoDBNamespace,emitDeprecationWarning:h,makeCounter:makeCounter,maybePromise:maybePromise,now:now,calculateDurationInMs:calculateDurationInMs,makeInterruptableAsyncInterval:makeInterruptableAsyncInterval,hasAtomicOperators:hasAtomicOperators,MONGODB_WARNING_CODE:g,emitWarning:emitWarning,emitWarningOnce:emitWarningOnce,deepCopy:deepCopy,parsePackageVersion:parsePackageVersion}},2481:(e,t,r)=>{"use strict";const n=new Set(["w","wtimeout","j","journal","fsync"]);let o;class WriteConcern{constructor(e,t,r,n){if(e!=null){this.w=e}if(t!=null){this.wtimeout=t}if(r!=null){this.j=r}if(n!=null){this.fsync=n}}static fromOptions(e){if(e==null||e.writeConcern==null&&e.w==null&&e.wtimeout==null&&e.j==null&&e.journal==null&&e.fsync==null){return}if(e.writeConcern){if(typeof e.writeConcern==="string"){return new WriteConcern(e.writeConcern)}if(!Object.keys(e.writeConcern).some((e=>n.has(e)))){return}return new WriteConcern(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}if(!o)o=r(1371);o.emitWarningOnce(`Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.`);return new WriteConcern(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}e.exports=WriteConcern},900:e=>{var t=1e3;var r=t*60;var n=r*60;var o=n*24;var s=o*7;var i=o*365.25;e.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0){return parse(e)}else if(r==="number"&&isFinite(e)){return t.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a){return}var A=parseFloat(a[1]);var c=(a[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return A*i;case"weeks":case"week":case"w":return A*s;case"days":case"day":case"d":return A*o;case"hours":case"hour":case"hrs":case"hr":case"h":return A*n;case"minutes":case"minute":case"mins":case"min":case"m":return A*r;case"seconds":case"second":case"secs":case"sec":case"s":return A*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return undefined}}function fmtShort(e){var s=Math.abs(e);if(s>=o){return Math.round(e/o)+"d"}if(s>=n){return Math.round(e/n)+"h"}if(s>=r){return Math.round(e/r)+"m"}if(s>=t){return Math.round(e/t)+"s"}return e+"ms"}function fmtLong(e){var s=Math.abs(e);if(s>=o){return plural(e,s,o,"day")}if(s>=n){return plural(e,s,n,"hour")}if(s>=r){return plural(e,s,r,"minute")}if(s>=t){return plural(e,s,t,"second")}return e+" ms"}function plural(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}},1156:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.findSync=t.find=t.findAsync=void 0;const n=r(4351);const o=r(1017);const s=r(7147);const i=r(8237);const a=i("new-find-package-json:main");function findAsync(e,t,r){return n.__asyncGenerator(this,arguments,(function*findAsync_1(){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const s=!!r?r:"package.json";const i=!!t||o.isAbsolute(t)?t:process.cwd();let A=o.resolve(i,e);let c=false;while(A){if(A===o.parse(A).root){c=true}const e=o.resolve(A,s);a(`findSync: testing path "${e}"`);const t=yield n.__await(statPathAsync(e));if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield yield n.__await(e);a(`findSync: after yield`)}if(c){break}A=o.resolve(A,"..")}}))}t.findAsync=findAsync;t.find=findAsync;function*findSync(e,t,r){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const n=!!r?r:"package.json";const s=!!t||o.isAbsolute(t)?t:process.cwd();let i=o.resolve(s,e);let A=false;while(i){if(i===o.parse(i).root){A=true}const e=o.resolve(i,n);a(`findSync: testing path "${e}"`);const t=statPathSync(e);if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield e;a(`findSync: after yield`)}if(A){break}i=o.resolve(i,"..")}}t.findSync=findSync;function statPathSync(e){try{return s.statSync(e)}catch(e){if(e.code==="ENOENT"){return undefined}throw e}}function statPathAsync(e){return n.__awaiter(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(e.code==="ENOENT"){return undefined}throw e}))}))}},1223:(e,t,r)=>{var n=r(2940);e.exports=n(once);e.exports.strict=n(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})}));function once(e){var f=function(){if(f.called)return f.value;f.called=true;return f.value=e.apply(this,arguments)};f.called=false;return f}function onceStrict(e){var f=function(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=e.apply(this,arguments)};var t=e.name||"Function wrapped with `once`";f.onceError=t+" shouldn't be called more than once";f.called=false;return f}},9341:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";const n=r(9341);e.exports=function(){return n.makeOptionalRequire.apply(n,arguments)};e.exports.tryRequire=n.tryRequire;e.exports.tryResolve=n.tryResolve;e.exports["try"]=n.tryRequire;e.exports.resolve=n.tryResolve;e.exports.makeOptionalRequire=n.makeOptionalRequire;e.exports.optionalRequire=n.optionalRequire;e.exports.optionalRequireCwd=n.optionalRequireCwd;e.exports.optionalRequireTop=n.optionalRequireTop;let o;Object.defineProperty(e.exports,"log",{set(e){o=e;n.setDefaultLog(e)},get(){return o}})},6978:(e,t,r)=>{"use strict";const n=r(7147);const{promisify:o}=r(3837);const s=o(n.access);e.exports=async e=>{try{await s(e);return true}catch(e){return false}};e.exports.sync=e=>{try{n.accessSync(e);return true}catch(e){return false}}},8714:e=>{"use strict";function posix(e){return e.charAt(0)==="/"}function win32(e){var t=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var r=t.exec(e);var n=r[1]||"";var o=Boolean(n&&n.charAt(1)!==":");return Boolean(r[2]||o)}e.exports=process.platform==="win32"?win32:posix;e.exports.posix=posix;e.exports.win32=win32},4833:e=>{e.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}Pend.prototype.go=function(e){if(this.pending0&&e.pending{"use strict";const n=r(1017);const o=r(1812);const pkgDir=async e=>{const t=await o("package.json",{cwd:e});return t&&n.dirname(t)};e.exports=pkgDir;e.exports["default"]=pkgDir;e.exports.sync=e=>{const t=o.sync("package.json",{cwd:e});return t&&n.dirname(t)}},1812:(e,t,r)=>{"use strict";const n=r(1017);const o=r(5937);const s=r(6978);const i=Symbol("findUp.stop");e.exports=async(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=async t=>{if(typeof e!=="function"){return o(a,t)}const r=await e(t.cwd);if(typeof r==="string"){return o([r],t)}return r};while(true){const e=await runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.sync=(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=t=>{if(typeof e!=="function"){return o.sync(a,t)}const r=e(t.cwd);if(typeof r==="string"){return o.sync([r],t)}return r};while(true){const e=runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.exists=s;e.exports.sync.exists=s.sync;e.exports.stop=i},5937:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const{promisify:s}=r(3837);const i=r(6249);const a=s(o.stat);const A=s(o.lstat);const c={directory:"isDirectory",file:"isFile"};function checkType({type:e}){if(e in c){return}throw new Error(`Invalid type specified: ${e}`)}const matchType=(e,t)=>e===undefined||t[c[e]]();e.exports=async(e,t)=>{t={cwd:process.cwd(),type:"file",allowSymlinks:true,...t};checkType(t);const r=t.allowSymlinks?a:A;return i(e,(async e=>{try{const o=await r(n.resolve(t.cwd,e));return matchType(t.type,o)}catch(e){return false}}),t)};e.exports.sync=(e,t)=>{t={cwd:process.cwd(),allowSymlinks:true,type:"file",...t};checkType(t);const r=t.allowSymlinks?o.statSync:o.lstatSync;for(const o of e){try{const e=r(n.resolve(t.cwd,o));if(matchType(t.type,e)){return o}}catch(e){}}}},4752:(e,t,r)=>{"use strict";const n=r(7471);const pLimit=e=>{if(!((Number.isInteger(e)||e===Infinity)&&e>0)){return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"))}const t=[];let r=0;const next=()=>{r--;if(t.length>0){t.shift()()}};const run=(e,t,...o)=>{r++;const s=n(e,...o);t(s);s.then(next,next)};const enqueue=(n,o,...s)=>{if(rnew Promise((r=>enqueue(e,r,...t)));Object.defineProperties(generator,{activeCount:{get:()=>r},pendingCount:{get:()=>t.length},clearQueue:{value:()=>{t.length=0}}});return generator};e.exports=pLimit;e.exports["default"]=pLimit},6249:(e,t,r)=>{"use strict";const n=r(4752);class EndError extends Error{constructor(e){super();this.value=e}}const testElement=async(e,t)=>t(await e);const finder=async e=>{const t=await Promise.all(e);if(t[1]===true){throw new EndError(t[0])}return false};const pLocate=async(e,t,r)=>{r={concurrency:Infinity,preserveOrder:true,...r};const o=n(r.concurrency);const s=[...e].map((e=>[e,o(testElement,e,t)]));const i=n(r.preserveOrder?1:Infinity);try{await Promise.all(s.map((e=>i(finder,e))))}catch(e){if(e instanceof EndError){return e.value}throw e}};e.exports=pLocate;e.exports["default"]=pLocate},7471:e=>{"use strict";const pTry=(e,...t)=>new Promise((r=>{r(e(...t))}));e.exports=pTry;e.exports["default"]=pTry},7214:e=>{"use strict";const t={};function createErrorType(e,r,n){if(!n){n=Error}function getMessage(e,t,n){if(typeof r==="string"){return r}else{return r(e,t,n)}}class NodeError extends n{constructor(e,t,r){super(getMessage(e,t,r))}}NodeError.prototype.name=n.name;NodeError.prototype.code=e;t[e]=NodeError}function oneOf(e,t){if(Array.isArray(e)){const r=e.length;e=e.map((e=>String(e)));if(r>2){return`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]}else if(r===2){return`one of ${t} ${e[0]} or ${e[1]}`}else{return`of ${t} ${e[0]}`}}else{return`of ${t} ${String(e)}`}}function startsWith(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function endsWith(e,t,r){if(r===undefined||r>e.length){r=e.length}return e.substring(r-t.length,r)===t}function includes(e,t,r){if(typeof r!=="number"){r=0}if(r+t.length>e.length){return false}else{return e.indexOf(t,r)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(e,t,r){let n;if(typeof t==="string"&&startsWith(t,"not ")){n="must not be";t=t.replace(/^not /,"")}else{n="must be"}let o;if(endsWith(e," argument")){o=`The ${e} ${n} ${oneOf(t,"type")}`}else{const r=includes(e,".")?"property":"argument";o=`The "${e}" ${r} ${n} ${oneOf(t,"type")}`}o+=`. Received type ${typeof r}`;return o}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.q=t},1359:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=r(1433);var s=r(6993);r(4124)(Duplex,o);{var i=n(s.prototype);for(var a=0;a{"use strict";e.exports=PassThrough;var n=r(4415);r(4124)(PassThrough,n);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);n.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},1433:(e,t,r)=>{"use strict";e.exports=Readable;var n;Readable.ReadableState=ReadableState;var o=r(2361).EventEmitter;var s=function EElistenerCount(e,t){return e.listeners(t).length};var i=r(2387);var a=r(4300).Buffer;var A=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return a.from(e)}function _isUint8Array(e){return a.isBuffer(e)||e instanceof A}var c=r(3837);var l;if(c&&c.debuglog){l=c.debuglog("stream")}else{l=function debug(){}}var u=r(2746);var h=r(7049);var d=r(9948),g=d.getHighWaterMark;var p=r(7214).q,E=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,C=p.ERR_METHOD_NOT_IMPLEMENTED,I=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var y;var B;var Q;r(4124)(Readable,i);var b=h.errorOrDestroy;var w=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(Array.isArray(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.readableObjectMode;this.highWaterMark=g(this,e,"readableHighWaterMark",o);this.buffer=new u;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(4841).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){n=n||r(1359);if(!(this instanceof Readable))return new Readable(e);var t=this instanceof n;this._readableState=new ReadableState(e,this,t);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}i.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=h.destroy;Readable.prototype._undestroy=h.undestroy;Readable.prototype._destroy=function(e,t){t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var n;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=a.from(e,t);t=""}n=true}}else{n=true}return readableAddChunk(this,e,t,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,n,o){l("readableAddChunk",t);var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var i;if(!o)i=chunkInvalid(s,t);if(i){b(e,i)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==a.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(s.endEmitted)b(e,new I);else addChunk(e,s,t,true)}else if(s.ended){b(e,new m)}else if(s.destroyed){return false}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!n){s.reading=false;maybeReadMore(e,s)}}return!s.ended&&(s.length=S){e=S}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){l("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=t.length<=t.highWaterMark;e=0}else{t.length-=e;t.awaitDrain=0}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){l("onEofChunk");if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.sync){emitReadable(e)}else{t.needReadable=false;if(!t.emittedReadable){t.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable);t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended);if(!t.destroyed&&(t.length||t.ended)){e.emit("readable");t.emittedReadable=false}t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark;flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;process.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){while(!t.reading&&!t.ended&&(t.length1&&indexOf(n.pipes,e)!==-1)&&!A){l("false write response, pause",n.awaitDrain);n.awaitDrain++}r.pause()}}function onerror(t){l("onerror",t);unpipe();e.removeListener("error",onerror);if(s(e,"error")===0)b(e,t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){l("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){l("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!n.flowing){l("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&s(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var n=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;l("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return r};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);if(e==="readable"){process.nextTick(updateReadableListening,this)}return r};Readable.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return t};function updateReadableListening(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0;if(t.resumeScheduled&&!t.paused){t.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){l("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){l("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,t){if(!t.resumeScheduled){t.resumeScheduled=true;process.nextTick(resume_,e,t)}}function resume_(e,t){l("resume",t.reading);if(!t.reading){e.read(0)}t.resumeScheduled=false;e.emit("resume");flow(e);if(t.flowing&&!t.reading)e.read(0)}Readable.prototype.pause=function(){l("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){l("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var t=e._readableState;l("flow",t.flowing);while(t.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var t=this;var r=this._readableState;var n=false;e.on("end",(function(){l("wrapped end");if(r.decoder&&!r.ended){var e=r.decoder.end();if(e&&e.length)t.push(e)}t.push(null)}));e.on("data",(function(o){l("wrapped data");if(r.decoder)o=r.decoder.write(o);if(r.objectMode&&(o===null||o===undefined))return;else if(!r.objectMode&&(!o||!o.length))return;var s=t.push(o);if(!s){n=true;e.pause()}}));for(var o in e){if(this[o]===undefined&&typeof e[o]==="function"){this[o]=function methodWrap(t){return function methodWrapReturnFunction(){return e[t].apply(e,arguments)}}(o)}}for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.first();else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=t.buffer.consume(e,t.decoder)}return r}function endReadable(e){var t=e._readableState;l("endReadable",t.endEmitted);if(!t.endEmitted){t.ended=true;process.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){l("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end");if(e.autoDestroy){var r=t._writableState;if(!r||r.autoDestroy&&r.finished){t.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(e,t){if(Q===undefined){Q=r(9082)}return Q(Readable,e,t)}}function indexOf(e,t){for(var r=0,n=e.length;r{"use strict";e.exports=Transform;var n=r(7214).q,o=n.ERR_METHOD_NOT_IMPLEMENTED,s=n.ERR_MULTIPLE_CALLBACK,i=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=n.ERR_TRANSFORM_WITH_LENGTH_0;var A=r(1359);r(4124)(Transform,A);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null){return this.emit("error",new s)}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);n(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var n;Writable.WritableState=WritableState;var o={deprecate:r(5278)};var s=r(2387);var i=r(4300).Buffer;var a=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return i.from(e)}function _isUint8Array(e){return i.isBuffer(e)||e instanceof a}var A=r(7049);var c=r(9948),l=c.getHighWaterMark;var u=r(7214).q,h=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,g=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,E=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,C=u.ERR_STREAM_WRITE_AFTER_END,I=u.ERR_UNKNOWN_ENCODING;var y=A.errorOrDestroy;r(4124)(Writable,s);function nop(){}function WritableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.writableObjectMode;this.highWaterMark=l(this,e,"writableHighWaterMark",o);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var s=e.decodeStrings===false;this.decodeStrings=!s;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:o.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var B;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){B=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(e){if(B.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{B=function realHasInstance(e){return e instanceof this}}function Writable(e){n=n||r(1359);var t=this instanceof n;if(!t&&!B.call(Writable,this))return new Writable(e);this._writableState=new WritableState(e,this,t);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}s.call(this)}Writable.prototype.pipe=function(){y(this,new p)};function writeAfterEnd(e,t){var r=new C;y(e,r);process.nextTick(t,r)}function validChunk(e,t,r,n){var o;if(r===null){o=new m}else if(typeof r!=="string"&&!t.objectMode){o=new h("chunk",["string","Buffer"],r)}if(o){y(e,o);process.nextTick(n,o);return false}return true}Writable.prototype.write=function(e,t,r){var n=this._writableState;var o=false;var s=!n.objectMode&&_isUint8Array(e);if(s&&!i.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=n.defaultEncoding;if(typeof r!=="function")r=nop;if(n.ending)writeAfterEnd(this,r);else if(s||validChunk(this,n,e,r)){n.pendingcb++;o=writeOrBuffer(this,n,s,e,t,r)}return o};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new I(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=i.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,n,o,s){if(!r){var i=decodeChunk(t,n,o);if(n!==i){r=true;o="buffer";n=i}}var a=t.objectMode?1:n.length;t.length+=a;var A=t.length{"use strict";var n;function _defineProperty(e,t,r){if(t in e){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true})}else{e[t]=r}return e}var o=r(6080);var s=Symbol("lastResolve");var i=Symbol("lastReject");var a=Symbol("error");var A=Symbol("ended");var c=Symbol("lastPromise");var l=Symbol("handlePromise");var u=Symbol("stream");function createIterResult(e,t){return{value:e,done:t}}function readAndResolve(e){var t=e[s];if(t!==null){var r=e[u].read();if(r!==null){e[c]=null;e[s]=null;e[i]=null;t(createIterResult(r,false))}}}function onReadable(e){process.nextTick(readAndResolve,e)}function wrapForNext(e,t){return function(r,n){e.then((function(){if(t[A]){r(createIterResult(undefined,true));return}t[l](r,n)}),n)}}var h=Object.getPrototypeOf((function(){}));var d=Object.setPrototypeOf((n={get stream(){return this[u]},next:function next(){var e=this;var t=this[a];if(t!==null){return Promise.reject(t)}if(this[A]){return Promise.resolve(createIterResult(undefined,true))}if(this[u].destroyed){return new Promise((function(t,r){process.nextTick((function(){if(e[a]){r(e[a])}else{t(createIterResult(undefined,true))}}))}))}var r=this[c];var n;if(r){n=new Promise(wrapForNext(r,this))}else{var o=this[u].read();if(o!==null){return Promise.resolve(createIterResult(o,false))}n=new Promise(this[l])}this[c]=n;return n}},_defineProperty(n,Symbol.asyncIterator,(function(){return this})),_defineProperty(n,"return",(function _return(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){if(e){r(e);return}t(createIterResult(undefined,true))}))}))})),n),h);var g=function createReadableStreamAsyncIterator(e){var t;var r=Object.create(d,(t={},_defineProperty(t,u,{value:e,writable:true}),_defineProperty(t,s,{value:null,writable:true}),_defineProperty(t,i,{value:null,writable:true}),_defineProperty(t,a,{value:null,writable:true}),_defineProperty(t,A,{value:e._readableState.endEmitted,writable:true}),_defineProperty(t,l,{value:function value(e,t){var n=r[u].read();if(n){r[c]=null;r[s]=null;r[i]=null;e(createIterResult(n,false))}else{r[s]=e;r[i]=t}},writable:true}),t));r[c]=null;o(e,(function(e){if(e&&e.code!=="ERR_STREAM_PREMATURE_CLOSE"){var t=r[i];if(t!==null){r[c]=null;r[s]=null;r[i]=null;t(e)}r[a]=e;return}var n=r[s];if(n!==null){r[c]=null;r[s]=null;r[i]=null;n(createIterResult(undefined,true))}r[A]=true}));e.on("readable",onReadable.bind(null,r));return r};e.exports=g},2746:(e,t,r)=>{"use strict";function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t0)this.tail.next=t;else this.head=t;this.tail=t;++this.length}},{key:"unshift",value:function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r}},{key:"concat",value:function concat(e){if(this.length===0)return o.alloc(0);var t=o.allocUnsafe(e>>>0);var r=this.head;var n=0;while(r){copyBuffer(r.data,t,n);n+=r.data.length;r=r.next}return t}},{key:"consume",value:function consume(e,t){var r;if(eo.length?o.length:e;if(s===o.length)n+=o;else n+=o.slice(0,e);e-=s;if(e===0){if(s===o.length){++r;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=o.slice(s)}break}++r}this.length-=r;return n}},{key:"_getBuffer",value:function _getBuffer(e){var t=o.allocUnsafe(e);var r=this.head;var n=1;r.data.copy(t);e-=r.data.length;while(r=r.next){var s=r.data;var i=e>s.length?s.length:e;s.copy(t,t.length-e,0,i);e-=i;if(e===0){if(i===s.length){++n;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=s.slice(i)}break}++n}this.length-=n;return t}},{key:a,value:function value(e,t){return i(this,_objectSpread({},t,{depth:0,customInspect:false}))}}]);return BufferList}()},7049:e=>{"use strict";function destroy(e,t){var r=this;var n=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(n||o){if(t){t(e)}else if(e){if(!this._writableState){process.nextTick(emitErrorNT,this,e)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,e)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){if(!r._writableState){process.nextTick(emitErrorAndCloseNT,r,e)}else if(!r._writableState.errorEmitted){r._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,r,e)}else{process.nextTick(emitCloseNT,r)}}else if(t){process.nextTick(emitCloseNT,r);t(e)}else{process.nextTick(emitCloseNT,r)}}));return this}function emitErrorAndCloseNT(e,t){emitErrorNT(e,t);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}function errorOrDestroy(e,t){var r=e._readableState;var n=e._writableState;if(r&&r.autoDestroy||n&&n.autoDestroy)e.destroy(t);else e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},6080:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_STREAM_PREMATURE_CLOSE;function once(e){var t=false;return function(){if(t)return;t=true;for(var r=arguments.length,n=new Array(r),o=0;o{"use strict";function asyncGeneratorStep(e,t,r,n,o,s,i){try{var a=e[s](i);var A=a.value}catch(e){r(e);return}if(a.done){t(A)}else{Promise.resolve(A).then(n,o)}}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var s=e.apply(t,r);function _next(e){asyncGeneratorStep(s,n,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(s,n,o,_next,_throw,"throw",e)}_next(undefined)}))}}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t{"use strict";var n;function once(e){var t=false;return function(){if(t)return;t=true;e.apply(void 0,arguments)}}var o=r(7214).q,s=o.ERR_MISSING_ARGS,i=o.ERR_STREAM_DESTROYED;function noop(e){if(e)throw e}function isRequest(e){return e.setHeader&&typeof e.abort==="function"}function destroyer(e,t,o,s){s=once(s);var a=false;e.on("close",(function(){a=true}));if(n===undefined)n=r(6080);n(e,{readable:t,writable:o},(function(e){if(e)return s(e);a=true;s()}));var A=false;return function(t){if(a)return;if(A)return;A=true;if(isRequest(e))return e.abort();if(typeof e.destroy==="function")return e.destroy();s(t||new i("pipe"))}}function call(e){e()}function pipe(e,t){return e.pipe(t)}function popCallback(e){if(!e.length)return noop;if(typeof e[e.length-1]!=="function")return noop;return e.pop()}function pipeline(){for(var e=arguments.length,t=new Array(e),r=0;r0;return destroyer(e,s,a,(function(e){if(!o)o=e;if(e)i.forEach(call);if(s)return;i.forEach(call);n(o)}))}));return t.reduce(pipe)}e.exports=pipeline},9948:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function getHighWaterMark(e,t,r,o){var s=highWaterMarkFrom(t,o,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var i=o?r:"highWaterMark";throw new n(i,s)}return Math.floor(s)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},2387:(e,t,r)=>{e.exports=r(2781)},1642:(e,t,r)=>{var n=r(2781);if(process.env.READABLE_STREAM==="disable"&&n){e.exports=n.Readable;Object.assign(e.exports,n);e.exports.Stream=n}else{t=e.exports=r(1433);t.Stream=n||t;t.Readable=t;t.Writable=r(6993);t.Duplex=r(1359);t.Transform=r(4415);t.PassThrough=r(1542);t.finished=r(6080);t.pipeline=r(6989)}},545:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";const Module=__nccwpck_require__(8188);const xrequire=eval("require");const createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{const r=new Module(e);r.filename=e;r.paths=Module._nodeModulePaths(t);function _require(e){return xrequire(resolve(e))}function resolve(e,t){return Module._resolveFilename(e,r,false,t)}_require.resolve=resolve;function paths(e){return Module._resolveLookupPaths(e,r,true)}resolve.paths=paths;_require.main=process.mainModule;_require.extensions=Module._extensions;_require.cache=Module._cache;return _require});module.exports=createRequireFromPath},2058:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(545);const i=new Map;function requireAt(e,t){const makeIt=(r,i)=>{let a=requireAt.cache&&requireAt.cache.get(r);if(!a){let t;try{t=o.statSync(r)}catch(e){throw new Error(`require-at: stat '${r}' failed: ${e.message}`)}if(!t||!t.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return makeIt(n.dirname(r),true)}a=s(n.join(r,"._require-at_"),r);requireAt.cache&&requireAt.cache.set(r,a)}return t?a(t):a};return makeIt(n.resolve(e),false)}requireAt.cache=i;e.exports=requireAt},4959:(e,t,r)=>{const n=r(9491);const o=r(1017);const s=r(7147);let i=undefined;try{i=r(1957)}catch(e){}const a={nosort:true,silent:true};let A=0;const c=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&i===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||a};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof r,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let a=0;const next=e=>{s=s||e;if(--a===0)r(s)};const afterGlob=(e,n)=>{if(e)return r(e);a=n.length;if(a===0)return r();n.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&Arimraf_(e,t,CB)),A++)}if(r.code==="ENOENT")r=null}A=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!i.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,n)=>{if(!r)return afterGlob(null,[e]);i(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.lstat(e,((n,o)=>{if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&c)fixWinEPERM(e,t,n,r);if(o&&o.isDirectory())return rmdir(e,t,n,r);t.unlink(e,(n=>{if(n){if(n.code==="ENOENT")return r(null);if(n.code==="EPERM")return c?fixWinEPERM(e,t,n,r):rmdir(e,t,n,r);if(n.code==="EISDIR")return rmdir(e,t,n,r)}return r(n)}))}))};const fixWinEPERM=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.chmod(e,438,(n=>{if(n)o(n.code==="ENOENT"?null:r);else t.stat(e,((n,s)=>{if(n)o(n.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{n(e);n(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.rmdir(e,(n=>{if(n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM"))rmkids(e,t,o);else if(n&&n.code==="ENOTDIR")o(r);else o(n)}))};const rmkids=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.readdir(e,((n,s)=>{if(n)return r(n);let i=s.length;if(i===0)return t.rmdir(e,r);let a;s.forEach((n=>{rimraf(o.join(e,n),t,(n=>{if(a)return;if(n)return r(a=n);if(--i===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n(t,"rimraf: missing options");n.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!i.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(n){r=i.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{n(e);n(t);try{t.rmdirSync(e)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;if(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{n(e);n(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=c?100:1;let s=0;do{let n=true;try{const r=t.rmdirSync(e,t);n=false;return r}finally{if(++s{var n=r(4300);var o=n.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=o(e);if(t!==undefined){if(typeof r==="string"){n.fill(t,r)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},9178:(e,t,r)=>{"use strict";const{unassigned_code_points:n,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:A}=r(8916);e.exports=saslprep;const c=s;const l=o;const getCodePoint=e=>e.codePointAt(0);const first=e=>e[0];const last=e=>e[e.length-1];function toCodePoints(e){const t=[];const r=e.length;for(let n=0;n=55296&&o<=56319&&r>n+1){const r=e.charCodeAt(n+1);if(r>=56320&&r<=57343){t.push((o-55296)*1024+r-56320+65536);n+=1;continue}}t.push(o)}return t}function saslprep(e,t={}){if(typeof e!=="string"){throw new TypeError("Expected string.")}if(e.length===0){return""}const r=toCodePoints(e).map((e=>c.get(e)?32:e)).filter((e=>!l.get(e)));const o=String.fromCodePoint.apply(null,r).normalize("NFKC");const s=toCodePoints(o);const u=s.some((e=>i.get(e)));if(u){throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3")}if(t.allowUnassigned!==true){const e=s.some((e=>n.get(e)));if(e){throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}}const h=s.some((e=>a.get(e)));const d=s.some((e=>A.get(e)));if(h&&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 g=a.get(getCodePoint(first(o)));const p=a.get(getCodePoint(last(o)));if(h&&!(g&&p)){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}},8916:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const s=r(1453);const i=n.readFileSync(r.ab+"code-points.mem");let a=0;function read(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);a+=e;return s({buffer:t})}const A=read();const c=read();const l=read();const u=read();const h=read();const d=read();e.exports={unassigned_code_points:A,commonly_mapped_to_nothing:c,non_ASCII_space_characters:l,prohibited_characters:u,bidirectional_r_al:h,bidirectional_l:d}},1532:(e,t,r)=>{const n=Symbol("SemVer ANY");class Comparator{static get ANY(){return n}constructor(e,t){t=o(t);if(e instanceof Comparator){if(e.loose===!!t.loose){return e}else{e=e.value}}e=e.trim().split(/\s+/).join(" ");A("comparator",e,t);this.options=t;this.loose=!!t.loose;this.parse(e);if(this.semver===n){this.value=""}else{this.value=this.operator+this.semver.version}A("comp",this)}parse(e){const t=this.options.loose?s[i.COMPARATORLOOSE]:s[i.COMPARATOR];const r=e.match(t);if(!r){throw new TypeError(`Invalid comparator: ${e}`)}this.operator=r[1]!==undefined?r[1]:"";if(this.operator==="="){this.operator=""}if(!r[2]){this.semver=n}else{this.semver=new c(r[2],this.options.loose)}}toString(){return this.value}test(e){A("Comparator.test",e,this.options.loose);if(this.semver===n||e===n){return true}if(typeof e==="string"){try{e=new c(e,this.options)}catch(e){return false}}return a(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator)){throw new TypeError("a Comparator is required")}if(this.operator===""){if(this.value===""){return true}return new l(e.value,t).test(this.value)}else if(e.operator===""){if(e.value===""){return true}return new l(this.value,t).test(e.semver)}t=o(t);if(t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")){return false}if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))){return false}if(this.operator.startsWith(">")&&e.operator.startsWith(">")){return true}if(this.operator.startsWith("<")&&e.operator.startsWith("<")){return true}if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")){return true}if(a(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")){return true}if(a(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")){return true}return false}}e.exports=Comparator;const o=r(785);const{safeRe:s,t:i}=r(9523);const a=r(5098);const A=r(427);const c=r(8088);const l=r(9828)},9828:(e,t,r)=>{class Range{constructor(e,t){t=s(t);if(e instanceof Range){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{return new Range(e.raw,t)}}if(e instanceof i){this.raw=e.value;this.set=[[e]];this.format();return this}this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;this.raw=e.trim().split(/\s+/).join(" ");this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length));if(!this.set.length){throw new TypeError(`Invalid SemVer Range: ${this.raw}`)}if(this.set.length>1){const e=this.set[0];this.set=this.set.filter((e=>!isNullSet(e[0])));if(this.set.length===0){this.set=[e]}else if(this.set.length>1){for(const e of this.set){if(e.length===1&&isAny(e[0])){this.set=[e];break}}}}this.format()}format(){this.range=this.set.map((e=>e.join(" ").trim())).join("||").trim();return this.range}toString(){return this.range}parseRange(e){const t=(this.options.includePrerelease&&g)|(this.options.loose&&p);const r=t+":"+e;const n=o.get(r);if(n){return n}const s=this.options.loose;const A=s?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(A,hyphenReplace(this.options.includePrerelease));a("hyphen replace",e);e=e.replace(c[l.COMPARATORTRIM],u);a("comparator trim",e);e=e.replace(c[l.TILDETRIM],h);a("tilde trim",e);e=e.replace(c[l.CARETTRIM],d);a("caret trim",e);let E=e.split(" ").map((e=>parseComparator(e,this.options))).join(" ").split(/\s+/).map((e=>replaceGTE0(e,this.options)));if(s){E=E.filter((e=>{a("loose invalid filter",e,this.options);return!!e.match(c[l.COMPARATORLOOSE])}))}a("range list",E);const m=new Map;const C=E.map((e=>new i(e,this.options)));for(const e of C){if(isNullSet(e)){return[e]}m.set(e.value,e)}if(m.size>1&&m.has("")){m.delete("")}const I=[...m.values()];o.set(r,I);return I}intersects(e,t){if(!(e instanceof Range)){throw new TypeError("a Range is required")}return this.set.some((r=>isSatisfiable(r,t)&&e.set.some((e=>isSatisfiable(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e){return false}if(typeof e==="string"){try{e=new A(e,this.options)}catch(e){return false}}for(let t=0;te.value==="<0.0.0-0";const isAny=e=>e.value==="";const isSatisfiable=(e,t)=>{let r=true;const n=e.slice();let o=n.pop();while(r&&n.length){r=n.every((e=>o.intersects(e,t)));o=n.pop()}return r};const parseComparator=(e,t)=>{a("comp",e,t);e=replaceCarets(e,t);a("caret",e);e=replaceTildes(e,t);a("tildes",e);e=replaceXRanges(e,t);a("xrange",e);e=replaceStars(e,t);a("stars",e);return e};const isX=e=>!e||e.toLowerCase()==="x"||e==="*";const replaceTildes=(e,t)=>e.trim().split(/\s+/).map((e=>replaceTilde(e,t))).join(" ");const replaceTilde=(e,t)=>{const r=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(r,((t,r,n,o,s)=>{a("tilde",e,t,r,n,o,s);let i;if(isX(r)){i=""}else if(isX(n)){i=`>=${r}.0.0 <${+r+1}.0.0-0`}else if(isX(o)){i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`}else if(s){a("replaceTilde pr",s);i=`>=${r}.${n}.${o}-${s} <${r}.${+n+1}.0-0`}else{i=`>=${r}.${n}.${o} <${r}.${+n+1}.0-0`}a("tilde return",i);return i}))};const replaceCarets=(e,t)=>e.trim().split(/\s+/).map((e=>replaceCaret(e,t))).join(" ");const replaceCaret=(e,t)=>{a("caret",e,t);const r=t.loose?c[l.CARETLOOSE]:c[l.CARET];const n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,o,s,i)=>{a("caret",e,t,r,o,s,i);let A;if(isX(r)){A=""}else if(isX(o)){A=`>=${r}.0.0${n} <${+r+1}.0.0-0`}else if(isX(s)){if(r==="0"){A=`>=${r}.${o}.0${n} <${r}.${+o+1}.0-0`}else{A=`>=${r}.${o}.0${n} <${+r+1}.0.0-0`}}else if(i){a("replaceCaret pr",i);if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}-${i} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}-${i} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s}-${i} <${+r+1}.0.0-0`}}else{a("no pr");if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}${n} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}${n} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s} <${+r+1}.0.0-0`}}a("caret return",A);return A}))};const replaceXRanges=(e,t)=>{a("replaceXRanges",e,t);return e.split(/\s+/).map((e=>replaceXRange(e,t))).join(" ")};const replaceXRange=(e,t)=>{e=e.trim();const r=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(r,((r,n,o,s,i,A)=>{a("xRange",e,r,n,o,s,i,A);const c=isX(o);const l=c||isX(s);const u=l||isX(i);const h=u;if(n==="="&&h){n=""}A=t.includePrerelease?"-0":"";if(c){if(n===">"||n==="<"){r="<0.0.0-0"}else{r="*"}}else if(n&&h){if(l){s=0}i=0;if(n===">"){n=">=";if(l){o=+o+1;s=0;i=0}else{s=+s+1;i=0}}else if(n==="<="){n="<";if(l){o=+o+1}else{s=+s+1}}if(n==="<"){A="-0"}r=`${n+o}.${s}.${i}${A}`}else if(l){r=`>=${o}.0.0${A} <${+o+1}.0.0-0`}else if(u){r=`>=${o}.${s}.0${A} <${o}.${+s+1}.0-0`}a("xRange return",r);return r}))};const replaceStars=(e,t)=>{a("replaceStars",e,t);return e.trim().replace(c[l.STAR],"")};const replaceGTE0=(e,t)=>{a("replaceGTE0",e,t);return e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],"")};const hyphenReplace=e=>(t,r,n,o,s,i,a,A,c,l,u,h)=>{if(isX(n)){r=""}else if(isX(o)){r=`>=${n}.0.0${e?"-0":""}`}else if(isX(s)){r=`>=${n}.${o}.0${e?"-0":""}`}else if(i){r=`>=${r}`}else{r=`>=${r}${e?"-0":""}`}if(isX(c)){A=""}else if(isX(l)){A=`<${+c+1}.0.0-0`}else if(isX(u)){A=`<${c}.${+l+1}.0-0`}else if(h){A=`<=${c}.${l}.${u}-${h}`}else if(e){A=`<${c}.${l}.${+u+1}-0`}else{A=`<=${A}`}return`${r} ${A}`.trim()};const testSet=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch){return true}}}return false}return true}},8088:(e,t,r)=>{const n=r(427);const{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=r(2293);const{safeRe:i,t:a}=r(9523);const A=r(785);const{compareIdentifiers:c}=r(2463);class SemVer{constructor(e,t){t=A(t);if(e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{e=e.version}}else if(typeof e!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`)}if(e.length>o){throw new TypeError(`version is longer than ${o} characters`)}n("SemVer",e,t);this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[a.LOOSE]:i[a.FULL]);if(!r){throw new TypeError(`Invalid Version: ${e}`)}this.raw=e;this.major=+r[1];this.minor=+r[2];this.patch=+r[3];if(this.major>s||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>s||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>s||this.patch<0){throw new TypeError("Invalid patch version")}if(!r[4]){this.prerelease=[]}else{this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0){if(typeof this.prerelease[n]==="number"){this.prerelease[n]++;n=-2}}if(n===-1){if(t===this.prerelease.join(".")&&r===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(e)}}if(t){let n=[t,e];if(r===false){n=[t]}if(c(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1])){this.prerelease=n}}else{this.prerelease=n}}break}default:throw new Error(`invalid increment argument: ${e}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}e.exports=SemVer},8848:(e,t,r)=>{const n=r(5925);const clean=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};e.exports=clean},5098:(e,t,r)=>{const n=r(1898);const o=r(6017);const s=r(4123);const i=r(5522);const a=r(194);const A=r(7520);const cmp=(e,t,r,c)=>{switch(t){case"===":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e===r;case"!==":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e!==r;case"":case"=":case"==":return n(e,r,c);case"!=":return o(e,r,c);case">":return s(e,r,c);case">=":return i(e,r,c);case"<":return a(e,r,c);case"<=":return A(e,r,c);default:throw new TypeError(`Invalid operator: ${t}`)}};e.exports=cmp},3466:(e,t,r)=>{const n=r(8088);const o=r(5925);const{safeRe:s,t:i}=r(9523);const coerce=(e,t)=>{if(e instanceof n){return e}if(typeof e==="number"){e=String(e)}if(typeof e!=="string"){return null}t=t||{};let r=null;if(!t.rtl){r=e.match(t.includePrerelease?s[i.COERCEFULL]:s[i.COERCE])}else{const n=t.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL];let o;while((o=n.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||o.index+o[0].length!==r.index+r[0].length){r=o}n.lastIndex=o.index+o[1].length+o[2].length}n.lastIndex=-1}if(r===null){return null}const a=r[2];const A=r[3]||"0";const c=r[4]||"0";const l=t.includePrerelease&&r[5]?`-${r[5]}`:"";const u=t.includePrerelease&&r[6]?`+${r[6]}`:"";return o(`${a}.${A}.${c}${l}${u}`,t)};e.exports=coerce},2156:(e,t,r)=>{const n=r(8088);const compareBuild=(e,t,r)=>{const o=new n(e,r);const s=new n(t,r);return o.compare(s)||o.compareBuild(s)};e.exports=compareBuild},2804:(e,t,r)=>{const n=r(4309);const compareLoose=(e,t)=>n(e,t,true);e.exports=compareLoose},4309:(e,t,r)=>{const n=r(8088);const compare=(e,t,r)=>new n(e,r).compare(new n(t,r));e.exports=compare},4297:(e,t,r)=>{const n=r(5925);const diff=(e,t)=>{const r=n(e,null,true);const o=n(t,null,true);const s=r.compare(o);if(s===0){return null}const i=s>0;const a=i?r:o;const A=i?o:r;const c=!!a.prerelease.length;const l=!!A.prerelease.length;if(l&&!c){if(!A.patch&&!A.minor){return"major"}if(a.patch){return"patch"}if(a.minor){return"minor"}return"major"}const u=c?"pre":"";if(r.major!==o.major){return u+"major"}if(r.minor!==o.minor){return u+"minor"}if(r.patch!==o.patch){return u+"patch"}return"prerelease"};e.exports=diff},1898:(e,t,r)=>{const n=r(4309);const eq=(e,t,r)=>n(e,t,r)===0;e.exports=eq},4123:(e,t,r)=>{const n=r(4309);const gt=(e,t,r)=>n(e,t,r)>0;e.exports=gt},5522:(e,t,r)=>{const n=r(4309);const gte=(e,t,r)=>n(e,t,r)>=0;e.exports=gte},929:(e,t,r)=>{const n=r(8088);const inc=(e,t,r,o,s)=>{if(typeof r==="string"){s=o;o=r;r=undefined}try{return new n(e instanceof n?e.version:e,r).inc(t,o,s).version}catch(e){return null}};e.exports=inc},194:(e,t,r)=>{const n=r(4309);const lt=(e,t,r)=>n(e,t,r)<0;e.exports=lt},7520:(e,t,r)=>{const n=r(4309);const lte=(e,t,r)=>n(e,t,r)<=0;e.exports=lte},6688:(e,t,r)=>{const n=r(8088);const major=(e,t)=>new n(e,t).major;e.exports=major},8447:(e,t,r)=>{const n=r(8088);const minor=(e,t)=>new n(e,t).minor;e.exports=minor},6017:(e,t,r)=>{const n=r(4309);const neq=(e,t,r)=>n(e,t,r)!==0;e.exports=neq},5925:(e,t,r)=>{const n=r(8088);const parse=(e,t,r=false)=>{if(e instanceof n){return e}try{return new n(e,t)}catch(e){if(!r){return null}throw e}};e.exports=parse},2866:(e,t,r)=>{const n=r(8088);const patch=(e,t)=>new n(e,t).patch;e.exports=patch},4016:(e,t,r)=>{const n=r(5925);const prerelease=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};e.exports=prerelease},6417:(e,t,r)=>{const n=r(4309);const rcompare=(e,t,r)=>n(t,e,r);e.exports=rcompare},8701:(e,t,r)=>{const n=r(2156);const rsort=(e,t)=>e.sort(((e,r)=>n(r,e,t)));e.exports=rsort},6055:(e,t,r)=>{const n=r(9828);const satisfies=(e,t,r)=>{try{t=new n(t,r)}catch(e){return false}return t.test(e)};e.exports=satisfies},1426:(e,t,r)=>{const n=r(2156);const sort=(e,t)=>e.sort(((e,r)=>n(e,r,t)));e.exports=sort},9601:(e,t,r)=>{const n=r(5925);const valid=(e,t)=>{const r=n(e,t);return r?r.version:null};e.exports=valid},1383:(e,t,r)=>{const n=r(9523);const o=r(2293);const s=r(8088);const i=r(2463);const a=r(5925);const A=r(9601);const c=r(8848);const l=r(929);const u=r(4297);const h=r(6688);const d=r(8447);const g=r(2866);const p=r(4016);const E=r(4309);const m=r(6417);const C=r(2804);const I=r(2156);const y=r(1426);const B=r(8701);const Q=r(4123);const b=r(194);const w=r(1898);const S=r(6017);const v=r(5522);const R=r(7520);const k=r(5098);const D=r(3466);const N=r(1532);const T=r(9828);const O=r(6055);const _=r(2706);const M=r(579);const L=r(832);const F=r(4179);const U=r(2098);const P=r(420);const G=r(9380);const Y=r(3323);const V=r(7008);const W=r(5297);const J=r(7863);e.exports={parse:a,valid:A,clean:c,inc:l,diff:u,major:h,minor:d,patch:g,prerelease:p,compare:E,rcompare:m,compareLoose:C,compareBuild:I,sort:y,rsort:B,gt:Q,lt:b,eq:w,neq:S,gte:v,lte:R,cmp:k,coerce:D,Comparator:N,Range:T,satisfies:O,toComparators:_,maxSatisfying:M,minSatisfying:L,minVersion:F,validRange:U,outside:P,gtr:G,ltr:Y,intersects:V,simplifyRange:W,subset:J,SemVer:s,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},2293:e=>{const t="2.0.0";const r=256;const n=Number.MAX_SAFE_INTEGER||9007199254740991;const o=16;const s=r-6;const i=["major","premajor","minor","preminor","patch","prepatch","prerelease"];e.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:i,SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},427:e=>{const t=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},2463:e=>{const t=/^[0-9]+$/;const compareIdentifiers=(e,r)=>{const n=t.test(e);const o=t.test(r);if(n&&o){e=+e;r=+r}return e===r?0:n&&!o?-1:o&&!n?1:ecompareIdentifiers(t,e);e.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},5339:e=>{class LRUCache{constructor(){this.max=1e3;this.map=new Map}get(e){const t=this.map.get(e);if(t===undefined){return undefined}else{this.map.delete(e);this.map.set(e,t);return t}}delete(e){return this.map.delete(e)}set(e,t){const r=this.delete(e);if(!r&&t!==undefined){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}e.exports=LRUCache},785:e=>{const t=Object.freeze({loose:true});const r=Object.freeze({});const parseOptions=e=>{if(!e){return r}if(typeof e!=="object"){return t}return e};e.exports=parseOptions},9523:(e,t,r)=>{const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=r(2293);const i=r(427);t=e.exports={};const a=t.re=[];const A=t.safeRe=[];const c=t.src=[];const l=t.t={};let u=0;const h="[a-zA-Z0-9-]";const d=[["\\s",1],["\\d",s],[h,o]];const makeSafeRegex=e=>{for(const[t,r]of d){e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`)}return e};const createToken=(e,t,r)=>{const n=makeSafeRegex(t);const o=u++;i(e,o,t);l[e]=o;c[o]=t;a[o]=new RegExp(t,r?"g":undefined);A[o]=new RegExp(n,r?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`);createToken("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${h}+`);createToken("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`);createToken("FULL",`^${c[l.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`);createToken("LOOSE",`^${c[l.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${n}})`+`(?:\\.(\\d{1,${n}}))?`+`(?:\\.(\\d{1,${n}}))?`);createToken("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",c[l.COERCE],true);createToken("COERCERTLFULL",c[l.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,true);t.tildeTrimReplace="$1~";createToken("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,true);t.caretTrimReplace="$1^";createToken("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,true);t.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9380:(e,t,r)=>{const n=r(420);const gtr=(e,t,r)=>n(e,t,">",r);e.exports=gtr},7008:(e,t,r)=>{const n=r(9828);const intersects=(e,t,r)=>{e=new n(e,r);t=new n(t,r);return e.intersects(t,r)};e.exports=intersects},3323:(e,t,r)=>{const n=r(420);const ltr=(e,t,r)=>n(e,t,"<",r);e.exports=ltr},579:(e,t,r)=>{const n=r(8088);const o=r(9828);const maxSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===-1){s=e;i=new n(s,r)}}}));return s};e.exports=maxSatisfying},832:(e,t,r)=>{const n=r(8088);const o=r(9828);const minSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===1){s=e;i=new n(s,r)}}}));return s};e.exports=minSatisfying},4179:(e,t,r)=>{const n=r(8088);const o=r(9828);const s=r(4123);const minVersion=(e,t)=>{e=new o(e,t);let r=new n("0.0.0");if(e.test(r)){return r}r=new n("0.0.0-0");if(e.test(r)){return r}r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":if(t.prerelease.length===0){t.patch++}else{t.prerelease.push(0)}t.raw=t.format();case"":case">=":if(!i||s(t,i)){i=t}break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}));if(i&&(!r||s(r,i))){r=i}}if(r&&e.test(r)){return r}return null};e.exports=minVersion},420:(e,t,r)=>{const n=r(8088);const o=r(1532);const{ANY:s}=o;const i=r(9828);const a=r(6055);const A=r(4123);const c=r(194);const l=r(7520);const u=r(5522);const outside=(e,t,r,h)=>{e=new n(e,h);t=new i(t,h);let d,g,p,E,m;switch(r){case">":d=A;g=l;p=c;E=">";m=">=";break;case"<":d=c;g=u;p=A;E="<";m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(e,t,h)){return false}for(let r=0;r{if(e.semver===s){e=new o(">=0.0.0")}i=i||e;a=a||e;if(d(e.semver,i.semver,h)){i=e}else if(p(e.semver,a.semver,h)){a=e}}));if(i.operator===E||i.operator===m){return false}if((!a.operator||a.operator===E)&&g(e,a.semver)){return false}else if(a.operator===m&&p(e,a.semver)){return false}}return true};e.exports=outside},5297:(e,t,r)=>{const n=r(6055);const o=r(4309);e.exports=(e,t,r)=>{const s=[];let i=null;let a=null;const A=e.sort(((e,t)=>o(e,t,r)));for(const e of A){const o=n(e,t,r);if(o){a=e;if(!i){i=e}}else{if(a){s.push([i,a])}a=null;i=null}}if(i){s.push([i,null])}const c=[];for(const[e,t]of s){if(e===t){c.push(e)}else if(!t&&e===A[0]){c.push("*")}else if(!t){c.push(`>=${e}`)}else if(e===A[0]){c.push(`<=${t}`)}else{c.push(`${e} - ${t}`)}}const l=c.join(" || ");const u=typeof t.raw==="string"?t.raw:String(t);return l.length{const n=r(9828);const o=r(1532);const{ANY:s}=o;const i=r(6055);const a=r(4309);const subset=(e,t,r={})=>{if(e===t){return true}e=new n(e,r);t=new n(t,r);let o=false;e:for(const n of e.set){for(const e of t.set){const t=simpleSubset(n,e,r);o=o||t!==null;if(t){continue e}}if(o){return false}}return true};const A=[new o(">=0.0.0-0")];const c=[new o(">=0.0.0")];const simpleSubset=(e,t,r)=>{if(e===t){return true}if(e.length===1&&e[0].semver===s){if(t.length===1&&t[0].semver===s){return true}else if(r.includePrerelease){e=A}else{e=c}}if(t.length===1&&t[0].semver===s){if(r.includePrerelease){return true}else{t=c}}const n=new Set;let o,l;for(const t of e){if(t.operator===">"||t.operator===">="){o=higherGT(o,t,r)}else if(t.operator==="<"||t.operator==="<="){l=lowerLT(l,t,r)}else{n.add(t.semver)}}if(n.size>1){return null}let u;if(o&&l){u=a(o.semver,l.semver,r);if(u>0){return null}else if(u===0&&(o.operator!==">="||l.operator!=="<=")){return null}}for(const e of n){if(o&&!i(e,String(o),r)){return null}if(l&&!i(e,String(l),r)){return null}for(const n of t){if(!i(e,String(n),r)){return false}}return true}let h,d;let g,p;let E=l&&!r.includePrerelease&&l.semver.prerelease.length?l.semver:false;let m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:false;if(E&&E.prerelease.length===1&&l.operator==="<"&&E.prerelease[0]===0){E=false}for(const e of t){p=p||e.operator===">"||e.operator===">=";g=g||e.operator==="<"||e.operator==="<=";if(o){if(m){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===m.major&&e.semver.minor===m.minor&&e.semver.patch===m.patch){m=false}}if(e.operator===">"||e.operator===">="){h=higherGT(o,e,r);if(h===e&&h!==o){return false}}else if(o.operator===">="&&!i(o.semver,String(e),r)){return false}}if(l){if(E){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===E.major&&e.semver.minor===E.minor&&e.semver.patch===E.patch){E=false}}if(e.operator==="<"||e.operator==="<="){d=lowerLT(l,e,r);if(d===e&&d!==l){return false}}else if(l.operator==="<="&&!i(l.semver,String(e),r)){return false}}if(!e.operator&&(l||o)&&u!==0){return false}}if(o&&g&&!l&&u!==0){return false}if(l&&p&&!o&&u!==0){return false}if(m||E){return false}return true};const higherGT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e};const lowerLT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};e.exports=subset},2706:(e,t,r)=>{const n=r(9828);const toComparators=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")));e.exports=toComparators},2098:(e,t,r)=>{const n=r(9828);const validRange=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}};e.exports=validRange},1453:(e,t,r)=>{var n=r(1529);e.exports=Bitfield;function Bitfield(e){if(!(this instanceof Bitfield))return new Bitfield(e);if(!e)e={};if(Buffer.isBuffer(e))e={buffer:e};this.pageOffset=e.pageOffset||0;this.pageSize=e.pageSize||1024;this.pages=e.pages||n(this.pageSize);this.byteLength=this.pages.length*this.pageSize;this.length=8*this.byteLength;if(!powerOfTwo(this.pageSize))throw new Error("The page size should be a power of two");this._trackUpdates=!!e.trackUpdates;this._pageMask=this.pageSize-1;if(e.buffer){for(var t=0;t>t)};Bitfield.prototype.getByte=function(e){var t=e&this._pageMask;var r=(e-t)/this.pageSize;var n=this.pages.get(r,true);return n?n.buffer[t+this.pageOffset]:0};Bitfield.prototype.set=function(e,t){var r=e&7;var n=(e-r)/8;var o=this.getByte(n);return this.setByte(n,t?o|128>>r:o&(255^128>>r))};Bitfield.prototype.toBuffer=function(){var e=alloc(this.pages.length*this.pageSize);for(var t=0;t=this.byteLength){this.byteLength=e+1;this.length=this.byteLength*8}if(this._trackUpdates)this.pages.updated(o);return true};function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function powerOfTwo(e){return!(e&e-1)}},4841:(e,t,r)=>{"use strict";var n=r(1867).Buffer;var o=n.isEncoding||function(e){e=""+e;switch(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 true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){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=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var n=t.length-1;if(n=0){if(o>0)e.lastNeed=o-1;return o}if(--n=0){if(o>0)e.lastNeed=o-2;return o}if(--n=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},9318:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6224);const s=r(1621);const{env:i}=process;let a;if(s("no-color")||s("no-colors")||s("color=false")||s("color=never")){a=0}else if(s("color")||s("colors")||s("color=true")||s("color=always")){a=1}if("FORCE_COLOR"in i){if(i.FORCE_COLOR==="true"){a=1}else if(i.FORCE_COLOR==="false"){a=0}else{a=i.FORCE_COLOR.length===0?1:Math.min(parseInt(i.FORCE_COLOR,10),3)}}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e,t){if(a===0){return 0}if(s("color=16m")||s("color=full")||s("color=truecolor")){return 3}if(s("color=256")){return 2}if(e&&!t&&a===undefined){return 0}const r=a||0;if(i.TERM==="dumb"){return r}if(process.platform==="win32"){const e=n.release().split(".");if(Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in i){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||i.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in i){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0}if(i.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(i.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)){return 1}if("COLORTERM"in i){return 1}return r}function getSupportLevel(e){const t=supportsColor(e,e&&e.isTTY);return translateLevel(t)}e.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(true,o.isatty(1))),stderr:translateLevel(supportsColor(true,o.isatty(2)))}},7882:(e,t,r)=>{var n=r(3837);var o=r(336);var s=r(8860);var i=r(1642).Writable;var a=r(1642).PassThrough;var noop=function(){};var overflow=function(e){e&=511;return e&&512-e};var emptyStream=function(e,t){var r=new Source(e,t);r.end();return r};var mixinPax=function(e,t){if(t.path)e.name=t.path;if(t.linkpath)e.linkname=t.linkpath;if(t.size)e.size=parseInt(t.size,10);e.pax=t;return e};var Source=function(e,t){this._parent=e;this.offset=t;a.call(this,{autoDestroy:false})};n.inherits(Source,a);Source.prototype.destroy=function(e){this._parent.destroy(e)};var Extract=function(e){if(!(this instanceof Extract))return new Extract(e);i.call(this,e);e=e||{};this._offset=0;this._buffer=o();this._missing=0;this._partial=false;this._onparse=noop;this._header=null;this._stream=null;this._overflow=null;this._cb=null;this._locked=false;this._destroyed=false;this._pax=null;this._paxGlobal=null;this._gnuLongPath=null;this._gnuLongLinkPath=null;var t=this;var r=t._buffer;var oncontinue=function(){t._continue()};var onunlock=function(e){t._locked=false;if(e)return t.destroy(e);if(!t._stream)oncontinue()};var onstreamend=function(){t._stream=null;var e=overflow(t._header.size);if(e)t._parse(e,ondrain);else t._parse(512,onheader);if(!t._locked)oncontinue()};var ondrain=function(){t._buffer.consume(overflow(t._header.size));t._parse(512,onheader);oncontinue()};var onpaxglobalheader=function(){var e=t._header.size;t._paxGlobal=s.decodePax(r.slice(0,e));r.consume(e);onstreamend()};var onpaxheader=function(){var e=t._header.size;t._pax=s.decodePax(r.slice(0,e));if(t._paxGlobal)t._pax=Object.assign({},t._paxGlobal,t._pax);r.consume(e);onstreamend()};var ongnulongpath=function(){var n=t._header.size;this._gnuLongPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var ongnulonglinkpath=function(){var n=t._header.size;this._gnuLongLinkPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var onheader=function(){var n=t._offset;var o;try{o=t._header=s.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(e){t.emit("error",e)}r.consume(512);if(!o){t._parse(512,onheader);oncontinue();return}if(o.type==="gnu-long-path"){t._parse(o.size,ongnulongpath);oncontinue();return}if(o.type==="gnu-long-link-path"){t._parse(o.size,ongnulonglinkpath);oncontinue();return}if(o.type==="pax-global-header"){t._parse(o.size,onpaxglobalheader);oncontinue();return}if(o.type==="pax-header"){t._parse(o.size,onpaxheader);oncontinue();return}if(t._gnuLongPath){o.name=t._gnuLongPath;t._gnuLongPath=null}if(t._gnuLongLinkPath){o.linkname=t._gnuLongLinkPath;t._gnuLongLinkPath=null}if(t._pax){t._header=o=mixinPax(o,t._pax);t._pax=null}t._locked=true;if(!o.size||o.type==="directory"){t._parse(512,onheader);t.emit("entry",o,emptyStream(t,n),onunlock);return}t._stream=new Source(t,n);t.emit("entry",o,t._stream,onunlock);t._parse(o.size,onstreamend);oncontinue()};this._onheader=onheader;this._parse(512,onheader)};n.inherits(Extract,i);Extract.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream)this._stream.emit("close")};Extract.prototype._parse=function(e,t){if(this._destroyed)return;this._offset+=e;this._missing=e;if(t===this._onheader)this._partial=false;this._onparse=t};Extract.prototype._continue=function(){if(this._destroyed)return;var e=this._cb;this._cb=noop;if(this._overflow)this._write(this._overflow,undefined,e);else e()};Extract.prototype._write=function(e,t,r){if(this._destroyed)return;var n=this._stream;var o=this._buffer;var s=this._missing;if(e.length)this._partial=true;if(e.lengths){i=e.slice(s);e=e.slice(0,s)}if(n)n.end(e);else o.append(e);this._overflow=i;this._onparse()};Extract.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};e.exports=Extract},8860:(e,t)=>{var r=Buffer.alloc;var n="0000000000000000000";var o="7777777777777777777";var s="0".charCodeAt(0);var i=Buffer.from("ustar\0","binary");var a=Buffer.from("00","binary");var A=Buffer.from("ustar ","binary");var c=Buffer.from(" \0","binary");var l=parseInt("7777",8);var u=257;var h=263;var clamp=function(e,t,r){if(typeof e!=="number")return r;e=~~e;if(e>=t)return t;if(e>=0)return e;e+=t;if(e>=0)return e;return 0};var toType=function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null};var toTypeflag=function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0};var indexOf=function(e,t,r,n){for(;rt)return o.slice(0,t)+" ";else return n.slice(0,t-e.length)+e+" "};function parse256(e){var t;if(e[0]===128)t=true;else if(e[0]===255)t=false;else return null;var r=[];for(var n=e.length-1;n>0;n--){var o=e[n];if(t)r.push(o);else r.push(255-o)}var s=0;var i=r.length;for(n=0;n=Math.pow(10,r))r++;return t+r+e};t.decodeLongPath=function(e,t){return decodeStr(e,0,e.length,t)};t.encodePax=function(e){var t="";if(e.name)t+=addLength(" path="+e.name+"\n");if(e.linkname)t+=addLength(" linkpath="+e.linkname+"\n");var r=e.pax;if(r){for(var n in r){t+=addLength(" "+n+"="+r[n]+"\n")}}return Buffer.from(t)};t.decodePax=function(e){var t={};while(e.length){var r=0;while(r100){var A=n.indexOf("/");if(A===-1)return null;o+=o?"/"+n.slice(0,A):n.slice(0,A);n=n.slice(A+1)}if(Buffer.byteLength(n)>100||Buffer.byteLength(o)>155)return null;if(e.linkname&&Buffer.byteLength(e.linkname)>100)return null;t.write(n);t.write(encodeOct(e.mode&l,6),100);t.write(encodeOct(e.uid,6),108);t.write(encodeOct(e.gid,6),116);t.write(encodeOct(e.size,11),124);t.write(encodeOct(e.mtime.getTime()/1e3|0,11),136);t[156]=s+toTypeflag(e.type);if(e.linkname)t.write(e.linkname,157);i.copy(t,u);a.copy(t,h);if(e.uname)t.write(e.uname,265);if(e.gname)t.write(e.gname,297);t.write(encodeOct(e.devmajor||0,6),329);t.write(encodeOct(e.devminor||0,6),337);if(o)t.write(o,345);t.write(encodeOct(cksum(t),6),148);return t};t.decode=function(e,t,r){var n=e[156]===0?0:e[156]-s;var o=decodeStr(e,0,100,t);var a=decodeOct(e,100,8);var l=decodeOct(e,108,8);var d=decodeOct(e,116,8);var g=decodeOct(e,124,12);var p=decodeOct(e,136,12);var E=toType(n);var m=e[157]===0?null:decodeStr(e,157,100,t);var C=decodeStr(e,265,32);var I=decodeStr(e,297,32);var y=decodeOct(e,329,8);var B=decodeOct(e,337,8);var Q=cksum(e);if(Q===8*32)return null;if(Q!==decodeOct(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(i.compare(e,u,u+6)===0){if(e[345])o=decodeStr(e,345,155,t)+"/"+o}else if(A.compare(e,u,u+6)===0&&c.compare(e,h,h+2)===0){}else{if(!r){throw new Error("Invalid tar header: unknown format.")}}if(n===0&&o&&o[o.length-1]==="/")n=5;return{name:o,mode:a,uid:l,gid:d,size:g,mtime:new Date(1e3*p),type:E,linkname:m,uname:C,gname:I,devmajor:y,devminor:B}}},2283:(e,t,r)=>{t.extract=r(7882);t.pack=r(4930)},4930:(e,t,r)=>{var n=r(3186);var o=r(1205);var s=r(4124);var i=Buffer.alloc;var a=r(1642).Readable;var A=r(1642).Writable;var c=r(1576).StringDecoder;var l=r(8860);var u=parseInt("755",8);var h=parseInt("644",8);var d=i(1024);var noop=function(){};var overflow=function(e,t){t&=511;if(t)e.push(d.slice(0,512-t))};function modeToType(e){switch(e&n.S_IFMT){case n.S_IFBLK:return"block-device";case n.S_IFCHR:return"character-device";case n.S_IFDIR:return"directory";case n.S_IFIFO:return"fifo";case n.S_IFLNK:return"symlink"}return"file"}var Sink=function(e){A.call(this);this.written=0;this._to=e;this._destroyed=false};s(Sink,A);Sink.prototype._write=function(e,t,r){this.written+=e.length;if(this._to.push(e))return r();this._to._drain=r};Sink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var LinkSink=function(){A.call(this);this.linkname="";this._decoder=new c("utf-8");this._destroyed=false};s(LinkSink,A);LinkSink.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e);r()};LinkSink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Void=function(){A.call(this);this._destroyed=false};s(Void,A);Void.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Void.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Pack=function(e){if(!(this instanceof Pack))return new Pack(e);a.call(this,e);this._drain=noop;this._finalized=false;this._finalizing=false;this._destroyed=false;this._stream=null};s(Pack,a);Pack.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(this._finalized||this._destroyed)return;if(typeof t==="function"){r=t;t=null}if(!r)r=noop;var n=this;if(!e.size||e.type==="symlink")e.size=0;if(!e.type)e.type=modeToType(e.mode);if(!e.mode)e.mode=e.type==="directory"?u:h;if(!e.uid)e.uid=0;if(!e.gid)e.gid=0;if(!e.mtime)e.mtime=new Date;if(typeof t==="string")t=Buffer.from(t);if(Buffer.isBuffer(t)){e.size=t.length;this._encode(e);var s=this.push(t);overflow(n,e.size);if(s)process.nextTick(r);else this._drain=r;return new Void}if(e.type==="symlink"&&!e.linkname){var i=new LinkSink;o(i,(function(t){if(t){n.destroy();return r(t)}e.linkname=i.linkname;n._encode(e);r()}));return i}this._encode(e);if(e.type!=="file"&&e.type!=="contiguous-file"){process.nextTick(r);return new Void}var a=new Sink(this);this._stream=a;o(a,(function(t){n._stream=null;if(t){n.destroy();return r(t)}if(a.written!==e.size){n.destroy();return r(new Error("size mismatch"))}overflow(n,e.size);if(n._finalizing)n.finalize();r()}));return a};Pack.prototype.finalize=function(){if(this._stream){this._finalizing=true;return}if(this._finalized)return;this._finalized=true;this.push(d);this.push(null)};Pack.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream&&this._stream.destroy)this._stream.destroy()};Pack.prototype._encode=function(e){if(!e.pax){var t=l.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Pack.prototype._encodePax=function(e){var t=l.encodePax({name:e.name,linkname:e.linkname,pax:e.pax});var r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(l.encode(r));this.push(t);overflow(this,t.length);r.size=e.size;r.type=e.type;this.push(l.encode(r))};Pack.prototype._read=function(e){var t=this._drain;this._drain=noop;t()};e.exports=Pack},8517:(e,t,r)=>{ +(()=>{var __webpack_modules__={924:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var o=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function verb(e){return function(t){return step([e,t])}}function step(i){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,o&&(s=i[0]&2?o["return"]:i[0]?o["throw"]||((s=o["return"])&&s.call(o),0):o.next)&&!(s=s.call(o,i[1])).done)return s;if(o=0,s)i=[i[0]&2,s.value];switch(i[0]){case 0:case 1:s=i;break;case 4:r.label++;return{value:i[1],done:false};case 5:r.label++;o=i[1];i=[0];continue;case 7:i=r.ops.pop();r.trys.pop();continue;default:if(!(s=r.trys,s=s.length>0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0){e+=" ";let t=true;for(const r in this.properties){if(this.properties.hasOwnProperty(r)){const n=this.properties[r];if(n){if(t){t=false}else{e+=","}e+=`${r}=${escapeProperty(n)}`}}}}e+=`${A}${escapeData(this.message)}`;return e}}function escapeData(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},2186:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.getIDToken=t.getState=t.saveState=t.group=t.endGroup=t.startGroup=t.info=t.notice=t.warning=t.error=t.debug=t.isDebug=t.setFailed=t.setCommandEcho=t.setOutput=t.getBooleanInput=t.getMultilineInput=t.getInput=t.addPath=t.setSecret=t.exportVariable=t.ExitCode=void 0;const a=r(7351);const A=r(717);const c=r(6321);const l=s(r(2037));const u=s(r(1017));const h=r(8041);var d;(function(e){e[e["Success"]=0]="Success";e[e["Failure"]=1]="Failure"})(d=t.ExitCode||(t.ExitCode={}));function exportVariable(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env["GITHUB_ENV"]||"";if(n){return A.issueFileCommand("ENV",A.prepareKeyValueMessage(e,t))}a.issueCommand("set-env",{name:e},r)}t.exportVariable=exportVariable;function setSecret(e){a.issueCommand("add-mask",{},e)}t.setSecret=setSecret;function addPath(e){const t=process.env["GITHUB_PATH"]||"";if(t){A.issueFileCommand("PATH",e)}else{a.issueCommand("add-path",{},e)}process.env["PATH"]=`${e}${u.delimiter}${process.env["PATH"]}`}t.addPath=addPath;function getInput(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r){throw new Error(`Input required and not supplied: ${e}`)}if(t&&t.trimWhitespace===false){return r}return r.trim()}t.getInput=getInput;function getMultilineInput(e,t){const r=getInput(e,t).split("\n").filter((e=>e!==""));if(t&&t.trimWhitespace===false){return r}return r.map((e=>e.trim()))}t.getMultilineInput=getMultilineInput;function getBooleanInput(e,t){const r=["true","True","TRUE"];const n=["false","False","FALSE"];const o=getInput(e,t);if(r.includes(o))return true;if(n.includes(o))return false;throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${e}\n`+`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}t.getBooleanInput=getBooleanInput;function setOutput(e,t){const r=process.env["GITHUB_OUTPUT"]||"";if(r){return A.issueFileCommand("OUTPUT",A.prepareKeyValueMessage(e,t))}process.stdout.write(l.EOL);a.issueCommand("set-output",{name:e},c.toCommandValue(t))}t.setOutput=setOutput;function setCommandEcho(e){a.issue("echo",e?"on":"off")}t.setCommandEcho=setCommandEcho;function setFailed(e){process.exitCode=d.Failure;error(e)}t.setFailed=setFailed;function isDebug(){return process.env["RUNNER_DEBUG"]==="1"}t.isDebug=isDebug;function debug(e){a.issueCommand("debug",{},e)}t.debug=debug;function error(e,t={}){a.issueCommand("error",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.error=error;function warning(e,t={}){a.issueCommand("warning",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.warning=warning;function notice(e,t={}){a.issueCommand("notice",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.notice=notice;function info(e){process.stdout.write(e+l.EOL)}t.info=info;function startGroup(e){a.issue("group",e)}t.startGroup=startGroup;function endGroup(){a.issue("endgroup")}t.endGroup=endGroup;function group(e,t){return i(this,void 0,void 0,(function*(){startGroup(e);let r;try{r=yield t()}finally{endGroup()}return r}))}t.group=group;function saveState(e,t){const r=process.env["GITHUB_STATE"]||"";if(r){return A.issueFileCommand("STATE",A.prepareKeyValueMessage(e,t))}a.issueCommand("save-state",{name:e},c.toCommandValue(t))}t.saveState=saveState;function getState(e){return process.env[`STATE_${e}`]||""}t.getState=getState;function getIDToken(e){return i(this,void 0,void 0,(function*(){return yield h.OidcClient.getIDToken(e)}))}t.getIDToken=getIDToken;var g=r(1327);Object.defineProperty(t,"summary",{enumerable:true,get:function(){return g.summary}});var p=r(1327);Object.defineProperty(t,"markdownSummary",{enumerable:true,get:function(){return p.markdownSummary}});var E=r(2981);Object.defineProperty(t,"toPosixPath",{enumerable:true,get:function(){return E.toPosixPath}});Object.defineProperty(t,"toWin32Path",{enumerable:true,get:function(){return E.toWin32Path}});Object.defineProperty(t,"toPlatformPath",{enumerable:true,get:function(){return E.toPlatformPath}})},717:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.prepareKeyValueMessage=t.issueFileCommand=void 0;const i=s(r(7147));const a=s(r(2037));const A=r(5840);const c=r(6321);function issueFileCommand(e,t){const r=process.env[`GITHUB_${e}`];if(!r){throw new Error(`Unable to find environment variable for file command ${e}`)}if(!i.existsSync(r)){throw new Error(`Missing file at path: ${r}`)}i.appendFileSync(r,`${c.toCommandValue(t)}${a.EOL}`,{encoding:"utf8"})}t.issueFileCommand=issueFileCommand;function prepareKeyValueMessage(e,t){const r=`ghadelimiter_${A.v4()}`;const n=c.toCommandValue(t);if(e.includes(r)){throw new Error(`Unexpected input: name should not contain the delimiter "${r}"`)}if(n.includes(r)){throw new Error(`Unexpected input: value should not contain the delimiter "${r}"`)}return`${e}<<${r}${a.EOL}${n}${a.EOL}${r}`}t.prepareKeyValueMessage=prepareKeyValueMessage},8041:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.OidcClient=void 0;const o=r(6255);const s=r(5526);const i=r(2186);class OidcClient{static createHttpClient(e=true,t=10){const r={allowRetries:e,maxRetries:t};return new o.HttpClient("actions/oidc-client",[new s.BearerCredentialHandler(OidcClient.getRequestToken())],r)}static getRequestToken(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable")}return e}static getIDTokenUrl(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable")}return e}static getCall(e){var t;return n(this,void 0,void 0,(function*(){const r=OidcClient.createHttpClient();const n=yield r.getJson(e).catch((e=>{throw new Error(`Failed to get ID Token. \n \n Error Code : ${e.statusCode}\n \n Error Message: ${e.message}`)}));const o=(t=n.result)===null||t===void 0?void 0:t.value;if(!o){throw new Error("Response json body do not have ID Token field")}return o}))}static getIDToken(e){return n(this,void 0,void 0,(function*(){try{let t=OidcClient.getIDTokenUrl();if(e){const r=encodeURIComponent(e);t=`${t}&audience=${r}`}i.debug(`ID token url is ${t}`);const r=yield OidcClient.getCall(t);i.setSecret(r);return r}catch(e){throw new Error(`Error message: ${e.message}`)}}))}}t.OidcClient=OidcClient},2981:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const i=s(r(1017));function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,i.sep)}t.toPlatformPath=toPlatformPath},1327:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.summary=t.markdownSummary=t.SUMMARY_DOCS_URL=t.SUMMARY_ENV_VAR=void 0;const o=r(2037);const s=r(7147);const{access:i,appendFile:a,writeFile:A}=s.promises;t.SUMMARY_ENV_VAR="GITHUB_STEP_SUMMARY";t.SUMMARY_DOCS_URL="https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";class Summary{constructor(){this._buffer=""}filePath(){return n(this,void 0,void 0,(function*(){if(this._filePath){return this._filePath}const e=process.env[t.SUMMARY_ENV_VAR];if(!e){throw new Error(`Unable to find environment variable for $${t.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`)}try{yield i(e,s.constants.R_OK|s.constants.W_OK)}catch(t){throw new Error(`Unable to access summary file: '${e}'. Check if the file has correct read/write permissions.`)}this._filePath=e;return this._filePath}))}wrap(e,t,r={}){const n=Object.entries(r).map((([e,t])=>` ${e}="${t}"`)).join("");if(!t){return`<${e}${n}>`}return`<${e}${n}>${t}`}write(e){return n(this,void 0,void 0,(function*(){const t=!!(e===null||e===void 0?void 0:e.overwrite);const r=yield this.filePath();const n=t?A:a;yield n(r,this._buffer,{encoding:"utf8"});return this.emptyBuffer()}))}clear(){return n(this,void 0,void 0,(function*(){return this.emptyBuffer().write({overwrite:true})}))}stringify(){return this._buffer}isEmptyBuffer(){return this._buffer.length===0}emptyBuffer(){this._buffer="";return this}addRaw(e,t=false){this._buffer+=e;return t?this.addEOL():this}addEOL(){return this.addRaw(o.EOL)}addCodeBlock(e,t){const r=Object.assign({},t&&{lang:t});const n=this.wrap("pre",this.wrap("code",e),r);return this.addRaw(n).addEOL()}addList(e,t=false){const r=t?"ol":"ul";const n=e.map((e=>this.wrap("li",e))).join("");const o=this.wrap(r,n);return this.addRaw(o).addEOL()}addTable(e){const t=e.map((e=>{const t=e.map((e=>{if(typeof e==="string"){return this.wrap("td",e)}const{header:t,data:r,colspan:n,rowspan:o}=e;const s=t?"th":"td";const i=Object.assign(Object.assign({},n&&{colspan:n}),o&&{rowspan:o});return this.wrap(s,r,i)})).join("");return this.wrap("tr",t)})).join("");const r=this.wrap("table",t);return this.addRaw(r).addEOL()}addDetails(e,t){const r=this.wrap("details",this.wrap("summary",e)+t);return this.addRaw(r).addEOL()}addImage(e,t,r){const{width:n,height:o}=r||{};const s=Object.assign(Object.assign({},n&&{width:n}),o&&{height:o});const i=this.wrap("img",null,Object.assign({src:e,alt:t},s));return this.addRaw(i).addEOL()}addHeading(e,t){const r=`h${t}`;const n=["h1","h2","h3","h4","h5","h6"].includes(r)?r:"h1";const o=this.wrap(n,e);return this.addRaw(o).addEOL()}addSeparator(){const e=this.wrap("hr",null);return this.addRaw(e).addEOL()}addBreak(){const e=this.wrap("br",null);return this.addRaw(e).addEOL()}addQuote(e,t){const r=Object.assign({},t&&{cite:t});const n=this.wrap("blockquote",e,r);return this.addRaw(n).addEOL()}addLink(e,t){const r=this.wrap("a",e,{href:t});return this.addRaw(r).addEOL()}}const c=new Summary;t.markdownSummary=c;t.summary=c},6321:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.toCommandProperties=t.toCommandValue=void 0;function toCommandValue(e){if(e===null||e===undefined){return""}else if(typeof e==="string"||e instanceof String){return e}return JSON.stringify(e)}t.toCommandValue=toCommandValue;function toCommandProperties(e){if(!Object.keys(e).length){return{}}return{title:e.title,file:e.file,line:e.startLine,endLine:e.endLine,col:e.startColumn,endColumn:e.endColumn}}t.toCommandProperties=toCommandProperties},5526:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.PersonalAccessTokenCredentialHandler=t.BearerCredentialHandler=t.BasicCredentialHandler=void 0;class BasicCredentialHandler{constructor(e,t){this.username=e;this.password=t}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BasicCredentialHandler=BasicCredentialHandler;class BearerCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Bearer ${this.token}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BearerCredentialHandler=BearerCredentialHandler;class PersonalAccessTokenCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.PersonalAccessTokenCredentialHandler=PersonalAccessTokenCredentialHandler},6255:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable)){o={enumerable:true,get:function(){return t[r]}}}Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.HttpClient=t.isHttps=t.HttpClientResponse=t.HttpClientError=t.getProxyUrl=t.MediaTypes=t.Headers=t.HttpCodes=void 0;const a=s(r(3685));const A=s(r(5687));const c=s(r(9835));const l=s(r(4294));const u=r(1773);var h;(function(e){e[e["OK"]=200]="OK";e[e["MultipleChoices"]=300]="MultipleChoices";e[e["MovedPermanently"]=301]="MovedPermanently";e[e["ResourceMoved"]=302]="ResourceMoved";e[e["SeeOther"]=303]="SeeOther";e[e["NotModified"]=304]="NotModified";e[e["UseProxy"]=305]="UseProxy";e[e["SwitchProxy"]=306]="SwitchProxy";e[e["TemporaryRedirect"]=307]="TemporaryRedirect";e[e["PermanentRedirect"]=308]="PermanentRedirect";e[e["BadRequest"]=400]="BadRequest";e[e["Unauthorized"]=401]="Unauthorized";e[e["PaymentRequired"]=402]="PaymentRequired";e[e["Forbidden"]=403]="Forbidden";e[e["NotFound"]=404]="NotFound";e[e["MethodNotAllowed"]=405]="MethodNotAllowed";e[e["NotAcceptable"]=406]="NotAcceptable";e[e["ProxyAuthenticationRequired"]=407]="ProxyAuthenticationRequired";e[e["RequestTimeout"]=408]="RequestTimeout";e[e["Conflict"]=409]="Conflict";e[e["Gone"]=410]="Gone";e[e["TooManyRequests"]=429]="TooManyRequests";e[e["InternalServerError"]=500]="InternalServerError";e[e["NotImplemented"]=501]="NotImplemented";e[e["BadGateway"]=502]="BadGateway";e[e["ServiceUnavailable"]=503]="ServiceUnavailable";e[e["GatewayTimeout"]=504]="GatewayTimeout"})(h||(t.HttpCodes=h={}));var d;(function(e){e["Accept"]="accept";e["ContentType"]="content-type"})(d||(t.Headers=d={}));var g;(function(e){e["ApplicationJson"]="application/json"})(g||(t.MediaTypes=g={}));function getProxyUrl(e){const t=c.getProxyUrl(new URL(e));return t?t.href:""}t.getProxyUrl=getProxyUrl;const p=[h.MovedPermanently,h.ResourceMoved,h.SeeOther,h.TemporaryRedirect,h.PermanentRedirect];const E=[h.BadGateway,h.ServiceUnavailable,h.GatewayTimeout];const m=["OPTIONS","GET","DELETE","HEAD"];const C=10;const I=5;class HttpClientError extends Error{constructor(e,t){super(e);this.name="HttpClientError";this.statusCode=t;Object.setPrototypeOf(this,HttpClientError.prototype)}}t.HttpClientError=HttpClientError;class HttpClientResponse{constructor(e){this.message=e}readBody(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){let t=Buffer.alloc(0);this.message.on("data",(e=>{t=Buffer.concat([t,e])}));this.message.on("end",(()=>{e(t.toString())}))}))))}))}readBodyBuffer(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){const t=[];this.message.on("data",(e=>{t.push(e)}));this.message.on("end",(()=>{e(Buffer.concat(t))}))}))))}))}}t.HttpClientResponse=HttpClientResponse;function isHttps(e){const t=new URL(e);return t.protocol==="https:"}t.isHttps=isHttps;class HttpClient{constructor(e,t,r){this._ignoreSslError=false;this._allowRedirects=true;this._allowRedirectDowngrade=false;this._maxRedirects=50;this._allowRetries=false;this._maxRetries=1;this._keepAlive=false;this._disposed=false;this.userAgent=e;this.handlers=t||[];this.requestOptions=r;if(r){if(r.ignoreSslError!=null){this._ignoreSslError=r.ignoreSslError}this._socketTimeout=r.socketTimeout;if(r.allowRedirects!=null){this._allowRedirects=r.allowRedirects}if(r.allowRedirectDowngrade!=null){this._allowRedirectDowngrade=r.allowRedirectDowngrade}if(r.maxRedirects!=null){this._maxRedirects=Math.max(r.maxRedirects,0)}if(r.keepAlive!=null){this._keepAlive=r.keepAlive}if(r.allowRetries!=null){this._allowRetries=r.allowRetries}if(r.maxRetries!=null){this._maxRetries=r.maxRetries}}}options(e,t){return i(this,void 0,void 0,(function*(){return this.request("OPTIONS",e,null,t||{})}))}get(e,t){return i(this,void 0,void 0,(function*(){return this.request("GET",e,null,t||{})}))}del(e,t){return i(this,void 0,void 0,(function*(){return this.request("DELETE",e,null,t||{})}))}post(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("POST",e,t,r||{})}))}patch(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PATCH",e,t,r||{})}))}put(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PUT",e,t,r||{})}))}head(e,t){return i(this,void 0,void 0,(function*(){return this.request("HEAD",e,null,t||{})}))}sendStream(e,t,r,n){return i(this,void 0,void 0,(function*(){return this.request(e,t,r,n)}))}getJson(e,t={}){return i(this,void 0,void 0,(function*(){t[d.Accept]=this._getExistingOrDefaultHeader(t,d.Accept,g.ApplicationJson);const r=yield this.get(e,t);return this._processResponse(r,this.requestOptions)}))}postJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.post(e,n,r);return this._processResponse(o,this.requestOptions)}))}putJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.put(e,n,r);return this._processResponse(o,this.requestOptions)}))}patchJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.patch(e,n,r);return this._processResponse(o,this.requestOptions)}))}request(e,t,r,n){return i(this,void 0,void 0,(function*(){if(this._disposed){throw new Error("Client has already been disposed.")}const o=new URL(t);let s=this._prepareRequest(e,o,n);const i=this._allowRetries&&m.includes(e)?this._maxRetries+1:1;let a=0;let A;do{A=yield this.requestRaw(s,r);if(A&&A.message&&A.message.statusCode===h.Unauthorized){let e;for(const t of this.handlers){if(t.canHandleAuthentication(A)){e=t;break}}if(e){return e.handleAuthentication(this,s,r)}else{return A}}let t=this._maxRedirects;while(A.message.statusCode&&p.includes(A.message.statusCode)&&this._allowRedirects&&t>0){const i=A.message.headers["location"];if(!i){break}const a=new URL(i);if(o.protocol==="https:"&&o.protocol!==a.protocol&&!this._allowRedirectDowngrade){throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.")}yield A.readBody();if(a.hostname!==o.hostname){for(const e in n){if(e.toLowerCase()==="authorization"){delete n[e]}}}s=this._prepareRequest(e,a,n);A=yield this.requestRaw(s,r);t--}if(!A.message.statusCode||!E.includes(A.message.statusCode)){return A}a+=1;if(a{function callbackForResult(e,t){if(e){n(e)}else if(!t){n(new Error("Unknown error"))}else{r(t)}}this.requestRawWithCallback(e,t,callbackForResult)}))}))}requestRawWithCallback(e,t,r){if(typeof t==="string"){if(!e.options.headers){e.options.headers={}}e.options.headers["Content-Length"]=Buffer.byteLength(t,"utf8")}let n=false;function handleResult(e,t){if(!n){n=true;r(e,t)}}const o=e.httpModule.request(e.options,(e=>{const t=new HttpClientResponse(e);handleResult(undefined,t)}));let s;o.on("socket",(e=>{s=e}));o.setTimeout(this._socketTimeout||3*6e4,(()=>{if(s){s.end()}handleResult(new Error(`Request timeout: ${e.options.path}`))}));o.on("error",(function(e){handleResult(e)}));if(t&&typeof t==="string"){o.write(t,"utf8")}if(t&&typeof t!=="string"){t.on("close",(function(){o.end()}));t.pipe(o)}else{o.end()}}getAgent(e){const t=new URL(e);return this._getAgent(t)}getAgentDispatcher(e){const t=new URL(e);const r=c.getProxyUrl(t);const n=r&&r.hostname;if(!n){return}return this._getProxyAgentDispatcher(t,r)}_prepareRequest(e,t,r){const n={};n.parsedUrl=t;const o=n.parsedUrl.protocol==="https:";n.httpModule=o?A:a;const s=o?443:80;n.options={};n.options.host=n.parsedUrl.hostname;n.options.port=n.parsedUrl.port?parseInt(n.parsedUrl.port):s;n.options.path=(n.parsedUrl.pathname||"")+(n.parsedUrl.search||"");n.options.method=e;n.options.headers=this._mergeHeaders(r);if(this.userAgent!=null){n.options.headers["user-agent"]=this.userAgent}n.options.agent=this._getAgent(n.parsedUrl);if(this.handlers){for(const e of this.handlers){e.prepareRequest(n.options)}}return n}_mergeHeaders(e){if(this.requestOptions&&this.requestOptions.headers){return Object.assign({},lowercaseKeys(this.requestOptions.headers),lowercaseKeys(e||{}))}return lowercaseKeys(e||{})}_getExistingOrDefaultHeader(e,t,r){let n;if(this.requestOptions&&this.requestOptions.headers){n=lowercaseKeys(this.requestOptions.headers)[t]}return e[t]||n||r}_getAgent(e){let t;const r=c.getProxyUrl(e);const n=r&&r.hostname;if(this._keepAlive&&n){t=this._proxyAgent}if(!n){t=this._agent}if(t){return t}const o=e.protocol==="https:";let s=100;if(this.requestOptions){s=this.requestOptions.maxSockets||a.globalAgent.maxSockets}if(r&&r.hostname){const e={maxSockets:s,keepAlive:this._keepAlive,proxy:Object.assign(Object.assign({},(r.username||r.password)&&{proxyAuth:`${r.username}:${r.password}`}),{host:r.hostname,port:r.port})};let n;const i=r.protocol==="https:";if(o){n=i?l.httpsOverHttps:l.httpsOverHttp}else{n=i?l.httpOverHttps:l.httpOverHttp}t=n(e);this._proxyAgent=t}if(!t){const e={keepAlive:this._keepAlive,maxSockets:s};t=o?new A.Agent(e):new a.Agent(e);this._agent=t}if(o&&this._ignoreSslError){t.options=Object.assign(t.options||{},{rejectUnauthorized:false})}return t}_getProxyAgentDispatcher(e,t){let r;if(this._keepAlive){r=this._proxyAgentDispatcher}if(r){return r}const n=e.protocol==="https:";r=new u.ProxyAgent(Object.assign({uri:t.href,pipelining:!this._keepAlive?0:1},(t.username||t.password)&&{token:`${t.username}:${t.password}`}));this._proxyAgentDispatcher=r;if(n&&this._ignoreSslError){r.options=Object.assign(r.options.requestTls||{},{rejectUnauthorized:false})}return r}_performExponentialBackoff(e){return i(this,void 0,void 0,(function*(){e=Math.min(C,e);const t=I*Math.pow(2,e);return new Promise((e=>setTimeout((()=>e()),t)))}))}_processResponse(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((r,n)=>i(this,void 0,void 0,(function*(){const o=e.message.statusCode||0;const s={statusCode:o,result:null,headers:{}};if(o===h.NotFound){r(s)}function dateTimeDeserializer(e,t){if(typeof t==="string"){const e=new Date(t);if(!isNaN(e.valueOf())){return e}}return t}let i;let a;try{a=yield e.readBody();if(a&&a.length>0){if(t&&t.deserializeDates){i=JSON.parse(a,dateTimeDeserializer)}else{i=JSON.parse(a)}s.result=i}s.headers=e.message.headers}catch(e){}if(o>299){let e;if(i&&i.message){e=i.message}else if(a&&a.length>0){e=a}else{e=`Failed request: (${o})`}const t=new HttpClientError(e,o);t.result=s.result;n(t)}else{r(s)}}))))}))}}t.HttpClient=HttpClient;const lowercaseKeys=e=>Object.keys(e).reduce(((t,r)=>(t[r.toLowerCase()]=e[r],t)),{})},9835:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.checkBypass=t.getProxyUrl=void 0;function getProxyUrl(e){const t=e.protocol==="https:";if(checkBypass(e)){return undefined}const r=(()=>{if(t){return process.env["https_proxy"]||process.env["HTTPS_PROXY"]}else{return process.env["http_proxy"]||process.env["HTTP_PROXY"]}})();if(r){try{return new URL(r)}catch(e){if(!r.startsWith("http://")&&!r.startsWith("https://"))return new URL(`http://${r}`)}}else{return undefined}}t.getProxyUrl=getProxyUrl;function checkBypass(e){if(!e.hostname){return false}const t=e.hostname;if(isLoopbackAddress(t)){return true}const r=process.env["no_proxy"]||process.env["NO_PROXY"]||"";if(!r){return false}let n;if(e.port){n=Number(e.port)}else if(e.protocol==="http:"){n=80}else if(e.protocol==="https:"){n=443}const o=[e.hostname.toUpperCase()];if(typeof n==="number"){o.push(`${o[0]}:${n}`)}for(const e of r.split(",").map((e=>e.trim().toUpperCase())).filter((e=>e))){if(e==="*"||o.some((t=>t===e||t.endsWith(`.${e}`)||e.startsWith(".")&&t.endsWith(`${e}`)))){return true}}return false}t.checkBypass=checkBypass;function isLoopbackAddress(e){const t=e.toLowerCase();return t==="localhost"||t.startsWith("127.")||t.startsWith("[::1]")||t.startsWith("[0:0:0:0:0:0:0:1]")}},9690:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2361);const s=n(r(8237));const i=n(r(6570));const a=s.default("agent-base");function isAgent(e){return Boolean(e)&&typeof e.addRequest==="function"}function isSecureEndpoint(){const{stack:e}=new Error;if(typeof e!=="string")return false;return e.split("\n").some((e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1))}function createAgent(e,t){return new createAgent.Agent(e,t)}(function(e){class Agent extends o.EventEmitter{constructor(e,t){super();let r=t;if(typeof e==="function"){this.callback=e}else if(e){r=e}this.timeout=null;if(r&&typeof r.timeout==="number"){this.timeout=r.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,r){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const r=Object.assign({},t);if(typeof r.secureEndpoint!=="boolean"){r.secureEndpoint=isSecureEndpoint()}if(r.host==null){r.host="localhost"}if(r.port==null){r.port=r.secureEndpoint?443:80}if(r.protocol==null){r.protocol=r.secureEndpoint?"https:":"http:"}if(r.host&&r.path){delete r.path}delete r.agent;delete r.hostname;delete r._defaultAgent;delete r.defaultPort;delete r.createConnection;e._last=true;e.shouldKeepAlive=false;let n=false;let o=null;const s=r.timeout||this.timeout;const onerror=t=>{if(e._hadError)return;e.emit("error",t);e._hadError=true};const ontimeout=()=>{o=null;n=true;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT";onerror(e)};const callbackError=e=>{if(n)return;if(o!==null){clearTimeout(o);o=null}onerror(e)};const onsocket=t=>{if(n)return;if(o!=null){clearTimeout(o);o=null}if(isAgent(t)){a("Callback returned another Agent instance %o",t.constructor.name);t.addRequest(e,r);return}if(t){t.once("free",(()=>{this.freeSocket(t,r)}));e.onSocket(t);return}const s=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);onerror(s)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){a("Converting legacy callback function to promise");this.promisifiedCallback=i.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof s==="number"&&s>0){o=setTimeout(ontimeout,s)}if("port"in r&&typeof r.port!=="number"){r.port=Number(r.port)}try{a("Resolving socket for %o request: %o",r.protocol,`${e.method} ${e.path}`);Promise.resolve(this.promisifiedCallback(e,r)).then(onsocket,callbackError)}catch(e){Promise.reject(e).catch(callbackError)}}freeSocket(e,t){a("Freeing socket %o %o",e.constructor.name,t);e.destroy()}destroy(){a("Destroying agent %o",this.constructor.name)}}e.Agent=Agent;e.prototype=e.Agent.prototype})(createAgent||(createAgent={}));e.exports=createAgent},6570:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function promisify(e){return function(t,r){return new Promise(((n,o)=>{e.call(this,t,r,((e,t)=>{if(e){o(e)}else{n(t)}}))}))}}t["default"]=promisify},4855:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6006);var s=function(){function Mutex(e){this._semaphore=new o.default(1,e)}Mutex.prototype.acquire=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,n.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._semaphore.acquire()];case 1:e=r.sent(),t=e[1];return[2,t]}}))}))};Mutex.prototype.runExclusive=function(e){return this._semaphore.runExclusive((function(){return e()}))};Mutex.prototype.isLocked=function(){return this._semaphore.isLocked()};Mutex.prototype.waitForUnlock=function(){return this._semaphore.waitForUnlock()};Mutex.prototype.release=function(){this._semaphore.release()};Mutex.prototype.cancel=function(){return this._semaphore.cancel()};return Mutex}();t["default"]=s},6006:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6984);var s=function(){function Semaphore(e,t){if(t===void 0){t=o.E_CANCELED}this._maxConcurrency=e;this._cancelError=t;this._queue=[];this._waiters=[];if(e<=0){throw new Error("semaphore must be initialized to a positive value")}this._value=e}Semaphore.prototype.acquire=function(){var e=this;var t=this.isLocked();var r=new Promise((function(t,r){return e._queue.push({resolve:t,reject:r})}));if(!t)this._dispatch();return r};Semaphore.prototype.runExclusive=function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r,o;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.acquire()];case 1:t=n.sent(),r=t[0],o=t[1];n.label=2;case 2:n.trys.push([2,,4,5]);return[4,e(r)];case 3:return[2,n.sent()];case 4:o();return[7];case 5:return[2]}}))}))};Semaphore.prototype.waitForUnlock=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e;var t=this;return(0,n.__generator)(this,(function(r){if(!this.isLocked()){return[2,Promise.resolve()]}e=new Promise((function(e){return t._waiters.push({resolve:e})}));return[2,e]}))}))};Semaphore.prototype.isLocked=function(){return this._value<=0};Semaphore.prototype.release=function(){if(this._maxConcurrency>1){throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead")}if(this._currentReleaser){var e=this._currentReleaser;this._currentReleaser=undefined;e()}};Semaphore.prototype.cancel=function(){var e=this;this._queue.forEach((function(t){return t.reject(e._cancelError)}));this._queue=[]};Semaphore.prototype._dispatch=function(){var e=this;var t=this._queue.shift();if(!t)return;var r=false;this._currentReleaser=function(){if(r)return;r=true;e._value++;e._resolveWaiters();e._dispatch()};t.resolve([this._value--,this._currentReleaser])};Semaphore.prototype._resolveWaiters=function(){this._waiters.forEach((function(e){return e.resolve()}));this._waiters=[]};return Semaphore}();t["default"]=s},6984:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.E_CANCELED=t.E_ALREADY_LOCKED=t.E_TIMEOUT=void 0;t.E_TIMEOUT=new Error("timeout while waiting for mutex to become available");t.E_ALREADY_LOCKED=new Error("mutex already locked");t.E_CANCELED=new Error("request for lock canceled")},4038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=t.withTimeout=t.Semaphore=t.Mutex=void 0;var n=r(4351);var o=r(4855);Object.defineProperty(t,"Mutex",{enumerable:true,get:function(){return o.default}});var s=r(6006);Object.defineProperty(t,"Semaphore",{enumerable:true,get:function(){return s.default}});var i=r(5124);Object.defineProperty(t,"withTimeout",{enumerable:true,get:function(){return i.withTimeout}});var a=r(2621);Object.defineProperty(t,"tryAcquire",{enumerable:true,get:function(){return a.tryAcquire}});(0,n.__exportStar)(r(6984),t)},2621:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=void 0;var n=r(6984);var o=r(5124);function tryAcquire(e,t){if(t===void 0){t=n.E_ALREADY_LOCKED}return(0,o.withTimeout)(e,0,t)}t.tryAcquire=tryAcquire},5124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.withTimeout=void 0;var n=r(4351);var o=r(6984);function withTimeout(e,t,r){var s=this;if(r===void 0){r=o.E_TIMEOUT}return{acquire:function(){return new Promise((function(o,i){return(0,n.__awaiter)(s,void 0,void 0,(function(){var s,a,A,c,l;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:s=false;a=setTimeout((function(){s=true;i(r)}),t);n.label=1;case 1:n.trys.push([1,3,,4]);return[4,e.acquire()];case 2:A=n.sent();if(s){c=Array.isArray(A)?A[1]:A;c()}else{clearTimeout(a);o(A)}return[3,4];case 3:l=n.sent();if(!s){clearTimeout(a);i(l)}return[3,4];case 4:return[2]}}))}))}))},runExclusive:function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:t=function(){return undefined};n.label=1;case 1:n.trys.push([1,,7,8]);return[4,this.acquire()];case 2:r=n.sent();if(!Array.isArray(r))return[3,4];t=r[1];return[4,e(r[0])];case 3:return[2,n.sent()];case 4:t=r;return[4,e()];case 5:return[2,n.sent()];case 6:return[3,8];case 7:t();return[7];case 8:return[2]}}))}))},release:function(){e.release()},cancel:function(){return e.cancel()},waitForUnlock:function(){return e.waitForUnlock()},isLocked:function(){return e.isLocked()}}}t.withTimeout=withTimeout},9417:e=>{"use strict";e.exports=balanced;function balanced(e,t,r){if(e instanceof RegExp)e=maybeMatch(e,r);if(t instanceof RegExp)t=maybeMatch(t,r);var n=range(e,t,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+e.length,n[1]),post:r.slice(n[1]+t.length)}}function maybeMatch(e,t){var r=t.match(e);return r?r[0]:null}balanced.range=range;function range(e,t,r){var n,o,s,i,a;var A=r.indexOf(e);var c=r.indexOf(t,A+1);var l=A;if(A>=0&&c>0){if(e===t){return[A,c]}n=[];s=r.length;while(l>=0&&!a){if(l==A){n.push(l);A=r.indexOf(e,l+1)}else if(n.length==1){a=[n.pop(),c]}else{o=n.pop();if(o=0?A:c}if(n.length){a=[s,i]}}return a}},336:(e,t,r)=>{"use strict";var n=r(1642).Duplex,o=r(3837),s=r(1867).Buffer;function BufferList(e){if(!(this instanceof BufferList))return new BufferList(e);this._bufs=[];this.length=0;if(typeof e=="function"){this._callback=e;var t=function piper(e){if(this._callback){this._callback(e);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(e){e.on("error",t)}));this.on("unpipe",(function onUnpipe(e){e.removeListener("error",t)}))}else{this.append(e)}n.call(this)}o.inherits(BufferList,n);BufferList.prototype._offset=function _offset(e){var t=0,r=0,n;if(e===0)return[0,0];for(;rthis.length||e<0){return undefined}var t=this._offset(e);return this._bufs[t[0]][t[1]]};BufferList.prototype.slice=function slice(e,t){if(typeof e=="number"&&e<0)e+=this.length;if(typeof t=="number"&&t<0)t+=this.length;return this.copy(null,0,e,t)};BufferList.prototype.copy=function copy(e,t,r,n){if(typeof r!="number"||r<0)r=0;if(typeof n!="number"||n>this.length)n=this.length;if(r>=this.length)return e||s.alloc(0);if(n<=0)return e||s.alloc(0);var copy=!!e,o=this._offset(r),i=n-r,a=i,A=copy&&t||0,c=o[1],l,u;if(r===0&&n==this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length)}for(u=0;ul){this._bufs[u].copy(e,A,c);A+=l}else{this._bufs[u].copy(e,A,c,c+a);A+=l;break}a-=l;if(c)c=0}if(e.length>A)return e.slice(0,A);return e};BufferList.prototype.shallowSlice=function shallowSlice(e,t){e=e||0;t=typeof t!=="number"?this.length:t;if(e<0)e+=this.length;if(t<0)t+=this.length;if(e===t){return new BufferList}var r=this._offset(e),n=this._offset(t),o=this._bufs.slice(r[0],n[0]+1);if(n[1]==0)o.pop();else o[o.length-1]=o[o.length-1].slice(0,n[1]);if(r[1]!=0)o[0]=o[0].slice(r[1]);return new BufferList(o)};BufferList.prototype.toString=function toString(e,t,r){return this.slice(t,r).toString(e)};BufferList.prototype.consume=function consume(e){e=Math.trunc(e);if(Number.isNaN(e)||e<=0)return this;while(this._bufs.length){if(e>=this._bufs[0].length){e-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(e);this.length-=e;break}}return this};BufferList.prototype.duplicate=function duplicate(){var e=0,t=new BufferList;for(;ethis.length?this.length:t}var n=this._offset(t);var o=n[0];var i=n[1];for(o;o=e.length){var c=a.indexOf(e,i);if(c!==-1){return this._reverseOffset([o,c])}i=a.length-e.length+1}else{var l=this._reverseOffset([o,i]);if(this._match(l,e)){return l}i++}}i=0}return-1};BufferList.prototype._match=function(e,t){if(this.length-e{var n=r(6891);var o=r(9417);e.exports=expandTop;var s="\0SLASH"+Math.random()+"\0";var i="\0OPEN"+Math.random()+"\0";var a="\0CLOSE"+Math.random()+"\0";var A="\0COMMA"+Math.random()+"\0";var c="\0PERIOD"+Math.random()+"\0";function numeric(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function escapeBraces(e){return e.split("\\\\").join(s).split("\\{").join(i).split("\\}").join(a).split("\\,").join(A).split("\\.").join(c)}function unescapeBraces(e){return e.split(s).join("\\").split(i).join("{").split(a).join("}").split(A).join(",").split(c).join(".")}function parseCommaParts(e){if(!e)return[""];var t=[];var r=o("{","}",e);if(!r)return e.split(",");var n=r.pre;var s=r.body;var i=r.post;var a=n.split(",");a[a.length-1]+="{"+s+"}";var A=parseCommaParts(i);if(i.length){a[a.length-1]+=A.shift();a.push.apply(a,A)}t.push.apply(t,a);return t}function expandTop(e){if(!e)return[];if(e.substr(0,2)==="{}"){e="\\{\\}"+e.substr(2)}return expand(escapeBraces(e),true).map(unescapeBraces)}function identity(e){return e}function embrace(e){return"{"+e+"}"}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand(e,t){var r=[];var s=o("{","}",e);if(!s||/\$$/.test(s.pre))return[e];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);var A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);var c=i||A;var l=s.body.indexOf(",")>=0;if(!c&&!l){if(s.post.match(/,.*\}/)){e=s.pre+"{"+s.body+a+s.post;return expand(e)}return[e]}var u;if(c){u=s.body.split(/\.\./)}else{u=parseCommaParts(s.body);if(u.length===1){u=expand(u[0],false).map(embrace);if(u.length===1){var h=s.post.length?expand(s.post,false):[""];return h.map((function(e){return s.pre+u[0]+e}))}}}var d=s.pre;var h=s.post.length?expand(s.post,false):[""];var g;if(c){var p=numeric(u[0]);var E=numeric(u[1]);var m=Math.max(u[0].length,u[1].length);var C=u.length==3?Math.abs(numeric(u[2])):1;var I=lte;var y=E0){var S=new Array(w+1).join("0");if(Q<0)b="-"+S+b.slice(1);else b=S+b}}}g.push(b)}}else{g=n(u,(function(e){return expand(e,false)}))}for(var v=0;v{var n=r(6800),o=r(5497),s=r(7113),i=r(3797),a=r(414),A=r(972),c=r(6142),l=r(8522),u=r(3639),h=r(5846),d=r(5325),g=r(9502),p=r(4636),E=r(2259),m=r(1031);n.BSON_INT32_MAX=2147483647;n.BSON_INT32_MIN=-2147483648;n.BSON_INT64_MAX=Math.pow(2,63)-1;n.BSON_INT64_MIN=-Math.pow(2,63);n.JS_INT_MAX=9007199254740992;n.JS_INT_MIN=-9007199254740992;n.Binary=o;n.Code=s;n.DBRef=i;n.Decimal128=a;n.Double=A;n.Int32=c;n.Long=l;n.Map=u;n.MaxKey=h;n.MinKey=d;n.ObjectId=g;n.ObjectID=g;n.BSONRegExp=p;n.Symbol=E;n.Timestamp=m;e.exports=n},5497:(e,t,r)=>{if(typeof global!=="undefined"){var n=r(4300).Buffer}var o=r(2863);function Binary(e,t){if(!(this instanceof Binary))return new Binary(e,t);if(e!=null&&!(typeof e==="string")&&!n.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e)){throw new Error("only String, Buffer, Uint8Array or Array accepted")}this._bsontype="Binary";if(e instanceof Number){this.sub_type=e;this.position=0}else{this.sub_type=t==null?s:t;this.position=0}if(e!=null&&!(e instanceof Number)){if(typeof e==="string"){if(typeof n!=="undefined"){this.buffer=o.toBuffer(e)}else if(typeof Uint8Array!=="undefined"||Object.prototype.toString.call(e)==="[object Array]"){this.buffer=writeStringToArray(e)}else{throw new Error("only String, Buffer, Uint8Array or Array accepted")}}else{this.buffer=e}this.position=e.length}else{if(typeof n!=="undefined"){this.buffer=o.allocBuffer(Binary.BUFFER_SIZE)}else if(typeof Uint8Array!=="undefined"){this.buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE))}else{this.buffer=new Array(Binary.BUFFER_SIZE)}this.position=0}}Binary.prototype.put=function put(e){if(e["length"]!=null&&typeof e!=="number"&&e.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof e!=="number"&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(typeof e==="string"){t=e.charCodeAt(0)}else if(e["length"]!=null){t=e[0]}else{t=e}if(this.buffer.length>this.position){this.buffer[this.position++]=t}else{if(typeof n!=="undefined"&&n.isBuffer(this.buffer)){var r=o.allocBuffer(Binary.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length);this.buffer=r;this.buffer[this.position++]=t}else{r=null;if(Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"){r=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE+this.buffer.length))}else{r=new Array(Binary.BUFFER_SIZE+this.buffer.length)}for(var s=0;sthis.position?t+e.length:this.position}else if(typeof n!=="undefined"&&typeof e==="string"&&n.isBuffer(this.buffer)){this.buffer.write(e,t,"binary");this.position=t+e.length>this.position?t+e.length:this.position}else if(Object.prototype.toString.call(e)==="[object Uint8Array]"||Object.prototype.toString.call(e)==="[object Array]"&&typeof e!=="string"){for(s=0;sthis.position?t:this.position}else if(typeof e==="string"){for(s=0;sthis.position?t:this.position}};Binary.prototype.read=function read(e,t){t=t&&t>0?t:this.position;if(this.buffer["slice"]){return this.buffer.slice(e,e+t)}else{var r=typeof Uint8Array!=="undefined"?new Uint8Array(new ArrayBuffer(t)):new Array(t);for(var n=0;n{"use strict";var n=r(3639),o=r(8522),s=r(972),i=r(1031),a=r(9502),A=r(4636),c=r(2259),l=r(6142),u=r(7113),h=r(414),d=r(5325),g=r(5846),p=r(3797),E=r(5497);var m=r(2139),C=r(9290),I=r(1273),y=r(2863);var B=1024*1024*17;var Q=y.allocBuffer(B);var BSON=function(){};BSON.prototype.serialize=function serialize(e,t){t=t||{};var r=typeof t.checkKeys==="boolean"?t.checkKeys:false;var n=typeof t.serializeFunctions==="boolean"?t.serializeFunctions:false;var o=typeof t.ignoreUndefined==="boolean"?t.ignoreUndefined:true;var s=typeof t.minInternalBufferSize==="number"?t.minInternalBufferSize:B;if(Q.length{var t=function Code(e,t){if(!(this instanceof Code))return new Code(e,t);this._bsontype="Code";this.code=e;this.scope=t};t.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};e.exports=t;e.exports.Code=t},3797:e=>{function DBRef(e,t,r){if(!(this instanceof DBRef))return new DBRef(e,t,r);this._bsontype="DBRef";this.namespace=e;this.oid=t;this.db=r}DBRef.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};e.exports=DBRef;e.exports.DBRef=DBRef},414:(e,t,r)=>{"use strict";var n=r(8522);var o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var s=/^(\+|-)?(Infinity|inf)$/i;var i=/^(\+|-)?NaN$/i;var a=6111;var A=-6176;var c=6176;var l=34;var u=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var h=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var d=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var g=/^([-+])?(\d+)?$/;var p=r(2863);var isDigit=function(e){return!isNaN(parseInt(e,10))};var divideu128=function(e){var t=n.fromNumber(1e3*1e3*1e3);var r=n.fromNumber(0);var o=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3]){return{quotient:e,rem:r}}for(o=0;o<=3;o++){r=r.shiftLeft(32);r=r.add(new n(e.parts[o],0));e.parts[o]=r.div(t).low_;r=r.modulo(t)}return{quotient:e,rem:r}};var multiply64x2=function(e,t){if(!e&&!t){return{high:n.fromNumber(0),low:n.fromNumber(0)}}var r=e.shiftRightUnsigned(32);var o=new n(e.getLowBits(),0);var s=t.shiftRightUnsigned(32);var i=new n(t.getLowBits(),0);var a=r.multiply(s);var A=r.multiply(i);var c=o.multiply(s);var l=o.multiply(i);a=a.add(A.shiftRightUnsigned(32));A=new n(A.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32));a=a.add(A.shiftRightUnsigned(32));l=A.shiftLeft(32).add(new n(l.getLowBits(),0));return{high:a,low:l}};var lessThan=function(e,t){var r=e.high_>>>0;var n=t.high_>>>0;if(r>>0;var s=t.low_>>>0;if(o=7e3){throw new Error(""+e+" not a valid Decimal128 string")}var _=e.match(o);var M=e.match(s);var L=e.match(i);if(!_&&!M&&!L||e.length===0){throw new Error(""+e+" not a valid Decimal128 string")}if(_&&_[4]&&_[2]===undefined){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="+"||e[O]==="-"){t=e[O++]==="-"}if(!isDigit(e[O])&&e[O]!=="."){if(e[O]==="i"||e[O]==="I"){return new Decimal128(p.toBuffer(t?h:d))}else if(e[O]==="N"){return new Decimal128(p.toBuffer(u))}}while(isDigit(e[O])||e[O]==="."){if(e[O]==="."){if(r){return new Decimal128(p.toBuffer(u))}r=true;O=O+1;continue}if(b<34){if(e[O]!=="0"||E){if(!E){B=C}E=true;Q[w++]=parseInt(e[O],10);b=b+1}}if(E){I=I+1}if(r){y=y+1}C=C+1;O=O+1}if(r&&!C){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="e"||e[O]==="E"){var F=e.substr(++O).match(g);if(!F||!F[2]){return new Decimal128(p.toBuffer(u))}R=parseInt(F[0],10);O=O+F[0].length}if(e[O]){return new Decimal128(p.toBuffer(u))}S=0;if(!b){S=0;v=0;Q[0]=0;I=1;b=1;m=0}else{v=b-1;m=I;if(R!==0&&m!==1){while(e[B+m-1]==="0"){m=m-1}}}if(R<=y&&y-R>1<<14){R=A}else{R=R-y}while(R>a){v=v+1;if(v-S>l){var U=Q.join("");if(U.match(/^0+$/)){R=a;break}else{return new Decimal128(p.toBuffer(t?h:d))}}R=R-1}while(R=5){Y=1;if(G===5){Y=Q[v]%2===1;for(k=B+v+2;k=0;V--){if(++Q[V]>9){Q[V]=0;if(V===0){if(R>8&255;q[O++]=J.low.low_>>16&255;q[O++]=J.low.low_>>24&255;q[O++]=J.low.high_&255;q[O++]=J.low.high_>>8&255;q[O++]=J.low.high_>>16&255;q[O++]=J.low.high_>>24&255;q[O++]=J.high.low_&255;q[O++]=J.high.low_>>8&255;q[O++]=J.high.low_>>16&255;q[O++]=J.high.low_>>24&255;q[O++]=J.high.high_&255;q[O++]=J.high.high_>>8&255;q[O++]=J.high.high_>>16&255;q[O++]=J.high.high_>>24&255;return new Decimal128(q)};var E=31;var m=16383;var C=30;var I=31;c=6176;Decimal128.prototype.toString=function(){var e;var t;var r;var o;var s;var i;var a=0;var A=new Array(36);for(var l=0;l>26&E;if(s>>3===3){if(s===C){return b.join("")+"Infinity"}else if(s===I){return"NaN"}else{i=e>>15&m;p=8+(e>>14&1)}}else{p=e>>14&7;i=e>>17&m}h=i-c;y.parts[0]=(e&16383)+((p&15)<<14);y.parts[1]=t;y.parts[2]=r;y.parts[3]=o;if(y.parts[0]===0&&y.parts[1]===0&&y.parts[2]===0&&y.parts[3]===0){g=true}else{for(Q=3;Q>=0;Q--){var v=0;var R=divideu128(y);y=R.quotient;v=R.rem.low_;if(!v)continue;for(B=8;B>=0;B--){A[Q*9+B]=v%10;v=Math.floor(v/10)}}}if(g){a=1;A[u]=0}else{a=36;l=0;while(!A[u]){l++;a=a-1;u=u+1}}d=a-1+h;if(d>=34||d<=-7||h>0){b.push(A[u++]);a=a-1;if(a){b.push(".")}for(l=0;l0){b.push("+"+d)}else{b.push(d)}}else{if(h>=0){for(l=0;l0){for(l=0;l{function Double(e){if(!(this instanceof Double))return new Double(e);this._bsontype="Double";this.value=e}Double.prototype.valueOf=function(){return this.value};Double.prototype.toJSON=function(){return this.value};e.exports=Double;e.exports.Double=Double},7998:(e,t)=>{var r;var readIEEE754=function(e,t,r,n,o){var s,i,a=r==="big",A=o*8-n-1,c=(1<>1,u=-7,h=a?0:o-1,d=a?1:-1,g=e[t+h];h+=d;s=g&(1<<-u)-1;g>>=-u;u+=A;for(;u>0;s=s*256+e[t+h],h+=d,u-=8);i=s&(1<<-u)-1;s>>=-u;u+=n;for(;u>0;i=i*256+e[t+h],h+=d,u-=8);if(s===0){s=1-l}else if(s===c){return i?NaN:(g?-1:1)*Infinity}else{i=i+Math.pow(2,n);s=s-l}return(g?-1:1)*i*Math.pow(2,s-n)};var writeIEEE754=function(e,t,r,n,o,s){var i,a,A,c=n==="big",l=s*8-o-1,u=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=c?s-1:0,p=c?-1:1,E=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;i=u}else{i=Math.floor(Math.log(t)/Math.LN2);if(t*(A=Math.pow(2,-i))<1){i--;A*=2}if(i+h>=1){t+=d/A}else{t+=d*Math.pow(2,1-h)}if(t*A>=2){i++;A/=2}if(i+h>=u){a=0;i=u}else if(i+h>=1){a=(t*A-1)*Math.pow(2,o);i=i+h}else{a=t*Math.pow(2,h-1)*Math.pow(2,o);i=0}}for(;o>=8;e[r+g]=a&255,g+=p,a/=256,o-=8);i=i<0;e[r+g]=i&255,g+=p,i/=256,l-=8);e[r+g-p]|=E*128};r=readIEEE754;t.P=writeIEEE754},6142:e=>{var Int32=function(e){if(!(this instanceof Int32))return new Int32(e);this._bsontype="Int32";this.value=e};Int32.prototype.valueOf=function(){return this.value};Int32.prototype.toJSON=function(){return this.value};e.exports=Int32;e.exports.Int32=Int32},8522:e=>{function Long(e,t){if(!(this instanceof Long))return new Long(e,t);this._bsontype="Long";this.low_=e|0;this.high_=t|0}Long.prototype.toInt=function(){return this.low_};Long.prototype.toNumber=function(){return this.high_*Long.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Long.prototype.toBigInt=function(){return BigInt(this.toString())};Long.prototype.toJSON=function(){return this.toString()};Long.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Long.TWO_PWR_32_DBL_+this.low_};Long.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Long.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Long.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Long.prototype.negate=function(){if(this.equals(Long.MIN_VALUE)){return Long.MIN_VALUE}else{return this.not().add(Long.ONE)}};Long.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.subtract=function(e){return this.add(e.negate())};Long.prototype.multiply=function(e){if(this.isZero()){return Long.ZERO}else if(e.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){return e.isOdd()?Long.MIN_VALUE:Long.ZERO}else if(e.equals(Long.MIN_VALUE)){return this.isOdd()?Long.MIN_VALUE:Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Long.TWO_PWR_24_)&&e.lessThan(Long.TWO_PWR_24_)){return Long.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){if(e.equals(Long.ONE)||e.equals(Long.NEG_ONE)){return Long.MIN_VALUE}else if(e.equals(Long.MIN_VALUE)){return Long.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Long.ZERO)){return e.isNegative()?Long.ONE:Long.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Long.MIN_VALUE)){return Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Long.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Long.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Long.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Long.ONE}s=s.add(A);n=n.subtract(c)}return s};Long.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Long.prototype.not=function(){return Long.fromBits(~this.low_,~this.high_)};Long.prototype.and=function(e){return Long.fromBits(this.low_&e.low_,this.high_&e.high_)};Long.prototype.or=function(e){return Long.fromBits(this.low_|e.low_,this.high_|e.high_)};Long.prototype.xor=function(e){return Long.fromBits(this.low_^e.low_,this.high_^e.high_)};Long.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Long.fromBits(t<>>32-e)}else{return Long.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Long.fromBits(t>>e-32,t>=0?0:-1)}}};Long.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Long.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Long.fromBits(t,0)}else{return Long.fromBits(t>>>e-32,0)}}};Long.fromInt=function(e){if(-128<=e&&e<128){var t=Long.INT_CACHE_[e];if(t){return t}}var r=new Long(e|0,e<0?-1:0);if(-128<=e&&e<128){Long.INT_CACHE_[e]=r}return r};Long.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Long.ZERO}else if(e<=-Long.TWO_PWR_63_DBL_){return Long.MIN_VALUE}else if(e+1>=Long.TWO_PWR_63_DBL_){return Long.MAX_VALUE}else if(e<0){return Long.fromNumber(-e).negate()}else{return new Long(e%Long.TWO_PWR_32_DBL_|0,e/Long.TWO_PWR_32_DBL_|0)}};Long.fromBigInt=function(e){return Long.fromString(e.toString(10),10)};Long.fromBits=function(e,t){return new Long(e,t)};Long.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Long.fromNumber(Math.pow(r,8));var o=Long.ZERO;for(var s=0;s{"use strict";if(typeof global.Map!=="undefined"){e.exports=global.Map;e.exports.Map=global.Map}else{var Map=function(e){this._keys=[];this._values={};for(var t=0;t{function MaxKey(){if(!(this instanceof MaxKey))return new MaxKey;this._bsontype="MaxKey"}e.exports=MaxKey;e.exports.MaxKey=MaxKey},5325:e=>{function MinKey(){if(!(this instanceof MinKey))return new MinKey;this._bsontype="MinKey"}e.exports=MinKey;e.exports.MinKey=MinKey},9502:(e,t,r)=>{var n="inspect";var o=r(2863);var s=parseInt(Math.random()*16777215,10);var i=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=true;n=r(3837).inspect.custom||"inspect"}}catch(e){a=false}var A=function ObjectID(e){if(e instanceof ObjectID)return e;if(!(this instanceof ObjectID))return new ObjectID(e);this._bsontype="ObjectID";if(e==null||typeof e==="number"){this.id=this.generate(e);if(ObjectID.cacheHexString)this.__id=this.toString("hex");return}var t=ObjectID.isValid(e);if(!t&&e!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(t&&typeof e==="string"&&e.length===24&&a){return new ObjectID(o.toBuffer(e,"hex"))}else if(t&&typeof e==="string"&&e.length===24){return ObjectID.createFromHexString(e)}else if(e!=null&&e.length===12){this.id=e}else if(e!=null&&typeof e.toHexString==="function"){return e}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}if(ObjectID.cacheHexString)this.__id=this.toString("hex")};var c=[];for(var l=0;l<256;l++){c[l]=(l<=15?"0":"")+l.toString(16)}A.prototype.toHexString=function(){if(A.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id instanceof h){e=convertToHex(this.id);if(A.cacheHexString)this.__id=e;return e}for(var t=0;t>8&255;n[1]=e>>16&255;n[0]=e>>24&255;n[6]=s&255;n[5]=s>>8&255;n[4]=s>>16&255;n[8]=t&255;n[7]=t>>8&255;n[11]=r&255;n[10]=r>>8&255;n[9]=r>>16&255;return n};A.prototype.toString=function(e){if(this.id&&this.id.copy){return this.id.toString(typeof e==="string"?e:"hex")}return this.toHexString()};A.prototype[n]=A.prototype.toString;A.prototype.toJSON=function(){return this.toHexString()};A.prototype.equals=function equals(e){if(e instanceof A){return this.toString()===e.toString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12&&this.id instanceof h){return e===this.id.toString("binary")}else if(typeof e==="string"&&A.isValid(e)&&e.length===24){return e.toLowerCase()===this.toHexString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12){return e===this.id}else if(e!=null&&(e instanceof A||e.toHexString)){return e.toHexString()===this.toHexString()}else{return false}};A.prototype.getTimestamp=function(){var e=new Date;var t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;e.setTime(Math.floor(t)*1e3);return e};A.index=~~(Math.random()*16777215);A.createPk=function createPk(){return new A};A.createFromTime=function createFromTime(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);t[3]=e&255;t[2]=e>>8&255;t[1]=e>>16&255;t[0]=e>>24&255;return new A(t)};var u=[];l=0;while(l<10)u[48+l]=l++;while(l<16)u[65-10+l]=u[97-10+l]=l++;var h=Buffer;var convertToHex=function(e){return e.toString("hex")};A.createFromHexString=function createFromHexString(e){if(typeof e==="undefined"||e!=null&&e.length!==24){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 A(o.toBuffer(e,"hex"));var t=new h(12);var r=0;var n=0;while(n<24){t[r++]=u[e.charCodeAt(n++)]<<4|u[e.charCodeAt(n++)]}return new A(t)};A.isValid=function isValid(e){if(e==null)return false;if(typeof e==="number"){return true}if(typeof e==="string"){return e.length===12||e.length===24&&i.test(e)}if(e instanceof A){return true}if(e instanceof h){return true}if(typeof e.toHexString==="function"&&(e.id instanceof h||typeof e.id==="string")){return e.id.length===12||e.id.length===24&&i.test(e.id)}return false};Object.defineProperty(A.prototype,"generationTime",{enumerable:true,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255;this.id[2]=e>>8&255;this.id[1]=e>>16&255;this.id[0]=e>>24&255}});e.exports=A;e.exports.ObjectID=A;e.exports.ObjectId=A},1273:(e,t,r)=>{"use strict";var n=r(8522).Long,o=r(972).Double,s=r(1031).Timestamp,i=r(9502).ObjectID,a=r(2259).Symbol,A=r(4636).BSONRegExp,c=r(7113).Code,l=r(414),u=r(5325).MinKey,h=r(5846).MaxKey,d=r(3797).DBRef,g=r(5497).Binary;var p=r(2863).normalizedFunctionString;var E=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var m=function calculateObjectSize(e,t,r){var n=4+1;if(Array.isArray(e)){for(var o=0;o=C.JS_INT_MIN&&t<=C.JS_INT_MAX){if(t>=C.BSON_INT32_MIN&&t<=C.BSON_INT32_MAX){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}case"undefined":if(I||!y)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;return 0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof u||t instanceof h||t["_bsontype"]==="MinKey"||t["_bsontype"]==="MaxKey"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1}else if(t instanceof i||t["_bsontype"]==="ObjectID"||t["_bsontype"]==="ObjectId"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1)}else if(t instanceof Date||E(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(typeof Buffer!=="undefined"&&Buffer.isBuffer(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length}else if(t instanceof n||t instanceof o||t instanceof s||t["_bsontype"]==="Long"||t["_bsontype"]==="Double"||t["_bsontype"]==="Timestamp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(t instanceof l||t["_bsontype"]==="Decimal128"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1)}else if(t instanceof c||t["_bsontype"]==="Code"){if(t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+m(t.scope,r,y)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1}}else if(t instanceof g||t["_bsontype"]==="Binary"){if(t.sub_type===g.SUBTYPE_BYTE_ARRAY){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1)}}else if(t instanceof a||t["_bsontype"]==="Symbol"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1}else if(t instanceof d||t["_bsontype"]==="DBRef"){var B={$ref:t.namespace,$id:t.oid};if(null!=t.db){B["$db"]=t.db}return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+m(B,r,y)}else if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"){return(e!=null?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}else if(t instanceof A||t["_bsontype"]==="BSONRegExp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+m(t,r,y)+1}case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]"){return(e!=null?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}else{if(r&&t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(p(t),"utf8")+1+m(t.scope,r,y)}else if(r){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(p(t),"utf8")+1}}}return 0}var C={};C.BSON_INT32_MAX=2147483647;C.BSON_INT32_MIN=-2147483648;C.JS_INT_MAX=9007199254740992;C.JS_INT_MIN=-9007199254740992;e.exports=m},2139:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";var Long=__nccwpck_require__(8522).Long,Double=__nccwpck_require__(972).Double,Timestamp=__nccwpck_require__(1031).Timestamp,ObjectID=__nccwpck_require__(9502).ObjectID,Symbol=__nccwpck_require__(2259).Symbol,Code=__nccwpck_require__(7113).Code,MinKey=__nccwpck_require__(5325).MinKey,MaxKey=__nccwpck_require__(5846).MaxKey,Decimal128=__nccwpck_require__(414),Int32=__nccwpck_require__(6142),DBRef=__nccwpck_require__(3797).DBRef,BSONRegExp=__nccwpck_require__(4636).BSONRegExp,Binary=__nccwpck_require__(5497).Binary;var utils=__nccwpck_require__(2863);var deserialize=function(e,t,r){t=t==null?{}:t;var n=t&&t.index?t.index:0;var o=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(o<5||e.lengthe.length){throw new Error("corrupt bson message")}if(e[n+o-1]!==0){throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(e,n,t,r)};var deserializeObject=function(e,t,r,n){var o=r["evalFunctions"]==null?false:r["evalFunctions"];var s=r["cacheFunctions"]==null?false:r["cacheFunctions"];var i=r["cacheFunctionsCrc32"]==null?false:r["cacheFunctionsCrc32"];if(!i)var a=null;var A=r["fieldsAsRaw"]==null?null:r["fieldsAsRaw"];var c=r["raw"]==null?false:r["raw"];var l=typeof r["bsonRegExp"]==="boolean"?r["bsonRegExp"]:false;var u=r["promoteBuffers"]==null?false:r["promoteBuffers"];var h=r["promoteLongs"]==null?true:r["promoteLongs"];var d=r["promoteValues"]==null?true:r["promoteValues"];var g=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var p=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(p<5||p>e.length)throw new Error("corrupt bson message");var E=n?[]:{};var m=0;var C=false;while(!C){var I=e[t++];if(I===0)break;var y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var B=n?m++:e.toString("utf8",t,y);t=y+1;if(I===BSON.BSON_DATA_STRING){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=e.toString("utf8",t,t+Q-1);t=t+Q}else if(I===BSON.BSON_DATA_OID){var b=utils.allocBuffer(12);e.copy(b,0,t,t+12);E[B]=new ObjectID(b);t=t+12}else if(I===BSON.BSON_DATA_INT&&d===false){E[B]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)}else if(I===BSON.BSON_DATA_INT){E[B]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}else if(I===BSON.BSON_DATA_NUMBER&&d===false){E[B]=new Double(e.readDoubleLE(t));t=t+8}else if(I===BSON.BSON_DATA_NUMBER){E[B]=e.readDoubleLE(t);t=t+8}else if(I===BSON.BSON_DATA_DATE){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Date(new Long(w,S).toNumber())}else if(I===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");E[B]=e[t++]===1}else if(I===BSON.BSON_DATA_OBJECT){var v=t;var R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(R<=0||R>e.length-t)throw new Error("bad embedded document length in bson");if(c){E[B]=e.slice(t,t+R)}else{E[B]=deserializeObject(e,v,r,false)}t=t+R}else if(I===BSON.BSON_DATA_ARRAY){v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var k=r;var D=t+R;if(A&&A[B]){k={};for(var N in r)k[N]=r[N];k["raw"]=true}E[B]=deserializeObject(e,v,k,true);t=t+R;if(e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==D)throw new Error("corrupted array bson")}else if(I===BSON.BSON_DATA_UNDEFINED){E[B]=undefined}else if(I===BSON.BSON_DATA_NULL){E[B]=null}else if(I===BSON.BSON_DATA_LONG){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var T=new Long(w,S);if(h&&d===true){E[B]=T.lessThanOrEqual(JS_INT_MAX_LONG)&&T.greaterThanOrEqual(JS_INT_MIN_LONG)?T.toNumber():T}else{E[B]=T}}else if(I===BSON.BSON_DATA_DECIMAL128){var O=utils.allocBuffer(16);e.copy(O,0,t,t+16);t=t+16;var _=new Decimal128(O);E[B]=_.toObject?_.toObject():_}else if(I===BSON.BSON_DATA_BINARY){var M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var L=M;var F=e[t++];if(M<0)throw new Error("Negative binary type element size found");if(M>e.length)throw new Error("Binary type size larger than document size");if(e["slice"]!=null){if(F===Binary.SUBTYPE_BYTE_ARRAY){M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(M<0)throw new Error("Negative binary type element size found for subtype 0x02");if(M>L-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(ML-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(M=e.length)throw new Error("Bad BSON Document: illegal CString");var P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var G=e.toString("utf8",t,y);t=y+1;var Y=new Array(G.length);for(y=0;y=e.length)throw new Error("Bad BSON Document: illegal CString");P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");G=e.toString("utf8",t,y);t=y+1;E[B]=new BSONRegExp(P,G)}else if(I===BSON.BSON_DATA_SYMBOL){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=new Symbol(e.toString("utf8",t,t+Q-1));t=t+Q}else if(I===BSON.BSON_DATA_TIMESTAMP){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Timestamp(w,S)}else if(I===BSON.BSON_DATA_MIN_KEY){E[B]=new MinKey}else if(I===BSON.BSON_DATA_MAX_KEY){E[B]=new MaxKey}else if(I===BSON.BSON_DATA_CODE){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var V=e.toString("utf8",t,t+Q-1);if(o){if(s){var W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}}else{E[B]=new Code(V)}t=t+Q}else if(I===BSON.BSON_DATA_CODE_W_SCOPE){var J=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(J<4+4+4+1){throw new Error("code_w_scope total size shorter minimum expected length")}Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");V=e.toString("utf8",t,t+Q-1);t=t+Q;v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,v,r,false);t=t+R;if(J<4+4+R+Q){throw new Error("code_w_scope total size is to short, truncating scope")}if(J>4+4+R+Q){throw new Error("code_w_scope total size is to long, clips outer document")}if(o){if(s){W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}E[B].scope=q}else{E[B]=new Code(V,q)}}else if(I===BSON.BSON_DATA_DBPOINTER){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var j=e.toString("utf8",t,t+Q-1);t=t+Q;var z=utils.allocBuffer(12);e.copy(z,0,t,t+12);b=new ObjectID(z);t=t+12;var $=j.split(".");var K=$.shift();var X=$.join(".");E[B]=new DBRef(X,b,K)}else{throw new Error("Detected unknown BSON type "+I.toString(16)+' for fieldname "'+B+'", are you using the latest BSON parser')}}if(p!==t-g){if(n)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}if(E["$id"]!=null)E=new DBRef(E["$ref"],E["$id"],E["$db"]);return E};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;if(functionCache[hash]==null){eval("value = "+functionString);functionCache[hash]=value}return functionCache[hash].bind(object)};var isolateEval=function(functionString){var value=null;eval("value = "+functionString);return value};var BSON={};var 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);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},9290:(e,t,r)=>{"use strict";var n=r(7998).P,o=r(8522).Long,s=r(3639),i=r(5497).Binary;var a=r(2863).normalizedFunctionString;var A=/\x00/;var c=["$db","$ref","$id","$clusterTime"];var l=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var u=function isRegExp(e){return Object.prototype.toString.call(e)==="[object RegExp]"};var serializeString=function(e,t,r,n,o){e[n++]=d.BSON_DATA_STRING;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s+1;e[n-1]=0;var i=e.write(r,n+4,"utf8");e[n+3]=i+1>>24&255;e[n+2]=i+1>>16&255;e[n+1]=i+1>>8&255;e[n]=i+1&255;n=n+4+i;e[n++]=0;return n};var serializeNumber=function(e,t,r,s,i){if(Math.floor(r)===r&&r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){if(r>=d.BSON_INT32_MIN&&r<=d.BSON_INT32_MAX){e[s++]=d.BSON_DATA_INT;var a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;e[s++]=r&255;e[s++]=r>>8&255;e[s++]=r>>16&255;e[s++]=r>>24&255}else if(r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}else{e[s++]=d.BSON_DATA_LONG;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;var A=o.fromNumber(r);var c=A.getLowBits();var l=A.getHighBits();e[s++]=c&255;e[s++]=c>>8&255;e[s++]=c>>16&255;e[s++]=c>>24&255;e[s++]=l&255;e[s++]=l>>8&255;e[s++]=l>>16&255;e[s++]=l>>24&255}}else{e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}return s};var serializeNull=function(e,t,r,n,o){e[n++]=d.BSON_DATA_NULL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeBoolean=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BOOLEAN;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r?1:0;return n};var serializeDate=function(e,t,r,n,s){e[n++]=d.BSON_DATA_DATE;var i=!s?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+i;e[n++]=0;var a=o.fromNumber(r.getTime());var A=a.getLowBits();var c=a.getHighBits();e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=c&255;e[n++]=c>>8&255;e[n++]=c>>16&255;e[n++]=c>>24&255;return n};var serializeRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.source&&r.source.match(A)!=null){throw Error("value "+r.source+" must not contain null bytes")}n=n+e.write(r.source,n,"utf8");e[n++]=0;if(r.global)e[n++]=115;if(r.ignoreCase)e[n++]=105;if(r.multiline)e[n++]=109;e[n++]=0;return n};var serializeBSONRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.pattern.match(A)!=null){throw Error("pattern "+r.pattern+" must not contain null bytes")}n=n+e.write(r.pattern,n,"utf8");e[n++]=0;n=n+e.write(r.options.split("").sort().join(""),n,"utf8");e[n++]=0;return n};var serializeMinMax=function(e,t,r,n,o){if(r===null){e[n++]=d.BSON_DATA_NULL}else if(r._bsontype==="MinKey"){e[n++]=d.BSON_DATA_MIN_KEY}else{e[n++]=d.BSON_DATA_MAX_KEY}var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeObjectId=function(e,t,r,n,o){e[n++]=d.BSON_DATA_OID;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(typeof r.id==="string"){e.write(r.id,n,"binary")}else if(r.id&&r.id.copy){r.id.copy(e,n,0,12)}else{throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId")}return n+12};var serializeBuffer=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=r.length;e[n++]=i&255;e[n++]=i>>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=d.BSON_BINARY_SUBTYPE_DEFAULT;r.copy(e,n,0,i);n=n+i;return n};var serializeObject=function(e,t,r,n,o,s,i,a,A,c){for(var l=0;l>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=a&255;e[n++]=a>>8&255;e[n++]=a>>16&255;e[n++]=a>>24&255;return n};var serializeInt32=function(e,t,r,n,o){e[n++]=d.BSON_DATA_INT;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r&255;e[n++]=r>>8&255;e[n++]=r>>16&255;e[n++]=r>>24&255;return n};var serializeDouble=function(e,t,r,o,s){e[o++]=d.BSON_DATA_NUMBER;var i=!s?e.write(t,o,"utf8"):e.write(t,o,"ascii");o=o+i;e[o++]=0;n(e,r,o,"little",52,8);o=o+8;return o};var serializeFunction=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_CODE;var A=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+A;e[n++]=0;var c=a(r);var l=e.write(c,n+4,"utf8")+1;e[n]=l&255;e[n+1]=l>>8&255;e[n+2]=l>>16&255;e[n+3]=l>>24&255;n=n+4+l-1;e[n++]=0;return n};var serializeCode=function(e,t,r,n,o,s,i,a,A){if(r.scope&&typeof r.scope==="object"){e[n++]=d.BSON_DATA_CODE_W_SCOPE;var c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;var l=n;var u=typeof r.code==="string"?r.code:r.code.toString();n=n+4;var g=e.write(u,n+4,"utf8")+1;e[n]=g&255;e[n+1]=g>>8&255;e[n+2]=g>>16&255;e[n+3]=g>>24&255;e[n+4+g-1]=0;n=n+g+4;var p=h(e,r.scope,o,n,s+1,i,a);n=p-1;var E=p-l;e[l++]=E&255;e[l++]=E>>8&255;e[l++]=E>>16&255;e[l++]=E>>24&255;e[n++]=0}else{e[n++]=d.BSON_DATA_CODE;c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;u=r.code.toString();var m=e.write(u,n+4,"utf8")+1;e[n]=m&255;e[n+1]=m>>8&255;e[n+2]=m>>16&255;e[n+3]=m>>24&255;n=n+4+m-1;e[n++]=0}return n};var serializeBinary=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var a=r.value(true);var A=r.position;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY)A=A+4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=r.sub_type;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY){A=A-4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255}a.copy(e,n,0,r.position);n=n+r.position;return n};var serializeSymbol=function(e,t,r,n,o){e[n++]=d.BSON_DATA_SYMBOL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=e.write(r.value,n+4,"utf8")+1;e[n]=i&255;e[n+1]=i>>8&255;e[n+2]=i>>16&255;e[n+3]=i>>24&255;n=n+4+i-1;e[n++]=0;return n};var serializeDBRef=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_OBJECT;var a=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+a;e[n++]=0;var A=n;var c;if(null!=r.db){c=h(e,{$ref:r.namespace,$id:r.oid,$db:r.db},false,n,o+1,s)}else{c=h(e,{$ref:r.namespace,$id:r.oid},false,n,o+1,s)}var l=c-A;e[A++]=l&255;e[A++]=l>>8&255;e[A++]=l>>16&255;e[A++]=l>>24&255;return c};var h=function serializeInto(e,t,r,n,o,i,a,h){n=n||0;h=h||[];h.push(t);var d=n+4;if(Array.isArray(t)){for(var g=0;g>8&255;e[n++]=B>>16&255;e[n++]=B>>24&255;return d};var d={};d.BSON_DATA_NUMBER=1;d.BSON_DATA_STRING=2;d.BSON_DATA_OBJECT=3;d.BSON_DATA_ARRAY=4;d.BSON_DATA_BINARY=5;d.BSON_DATA_UNDEFINED=6;d.BSON_DATA_OID=7;d.BSON_DATA_BOOLEAN=8;d.BSON_DATA_DATE=9;d.BSON_DATA_NULL=10;d.BSON_DATA_REGEXP=11;d.BSON_DATA_CODE=13;d.BSON_DATA_SYMBOL=14;d.BSON_DATA_CODE_W_SCOPE=15;d.BSON_DATA_INT=16;d.BSON_DATA_TIMESTAMP=17;d.BSON_DATA_LONG=18;d.BSON_DATA_DECIMAL128=19;d.BSON_DATA_MIN_KEY=255;d.BSON_DATA_MAX_KEY=127;d.BSON_BINARY_SUBTYPE_DEFAULT=0;d.BSON_BINARY_SUBTYPE_FUNCTION=1;d.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;d.BSON_BINARY_SUBTYPE_UUID=3;d.BSON_BINARY_SUBTYPE_MD5=4;d.BSON_BINARY_SUBTYPE_USER_DEFINED=128;d.BSON_INT32_MAX=2147483647;d.BSON_INT32_MIN=-2147483648;d.BSON_INT64_MAX=Math.pow(2,63)-1;d.BSON_INT64_MIN=-Math.pow(2,63);d.JS_INT_MAX=9007199254740992;d.JS_INT_MIN=-9007199254740992;e.exports=h},2863:e=>{"use strict";function normalizedFunctionString(e){return e.toString().replace(/function *\(/,"function (")}function newBuffer(e,t){return new Buffer(e,t)}function allocBuffer(){return Buffer.alloc.apply(Buffer,arguments)}function toBuffer(){return Buffer.from.apply(Buffer,arguments)}e.exports={normalizedFunctionString:normalizedFunctionString,allocBuffer:typeof Buffer.alloc==="function"?allocBuffer:newBuffer,toBuffer:typeof Buffer.from==="function"?toBuffer:newBuffer}},4636:e=>{function BSONRegExp(e,t){if(!(this instanceof BSONRegExp))return new BSONRegExp;this._bsontype="BSONRegExp";this.pattern=e||"";this.options=t||"";for(var r=0;r{var n=Buffer?r(3837).inspect.custom||"inspect":"inspect";function Symbol(e){if(!(this instanceof Symbol))return new Symbol(e);this._bsontype="Symbol";this.value=e}Symbol.prototype.valueOf=function(){return this.value};Symbol.prototype.toString=function(){return this.value};Symbol.prototype[n]=function(){return this.value};Symbol.prototype.toJSON=function(){return this.value};e.exports=Symbol;e.exports.Symbol=Symbol},1031:e=>{function Timestamp(e,t){if(!(this instanceof Timestamp))return new Timestamp(e,t);this._bsontype="Timestamp";this.low_=e|0;this.high_=t|0}Timestamp.prototype.toInt=function(){return this.low_};Timestamp.prototype.toNumber=function(){return this.high_*Timestamp.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Timestamp.prototype.toJSON=function(){return this.toString()};Timestamp.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Timestamp.TWO_PWR_32_DBL_+this.low_};Timestamp.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Timestamp.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Timestamp.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Timestamp.prototype.negate=function(){if(this.equals(Timestamp.MIN_VALUE)){return Timestamp.MIN_VALUE}else{return this.not().add(Timestamp.ONE)}};Timestamp.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.subtract=function(e){return this.add(e.negate())};Timestamp.prototype.multiply=function(e){if(this.isZero()){return Timestamp.ZERO}else if(e.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){return e.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}else if(e.equals(Timestamp.MIN_VALUE)){return this.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Timestamp.TWO_PWR_24_)&&e.lessThan(Timestamp.TWO_PWR_24_)){return Timestamp.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){if(e.equals(Timestamp.ONE)||e.equals(Timestamp.NEG_ONE)){return Timestamp.MIN_VALUE}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Timestamp.ZERO)){return e.isNegative()?Timestamp.ONE:Timestamp.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Timestamp.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Timestamp.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Timestamp.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Timestamp.ONE}s=s.add(A);n=n.subtract(c)}return s};Timestamp.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Timestamp.prototype.not=function(){return Timestamp.fromBits(~this.low_,~this.high_)};Timestamp.prototype.and=function(e){return Timestamp.fromBits(this.low_&e.low_,this.high_&e.high_)};Timestamp.prototype.or=function(e){return Timestamp.fromBits(this.low_|e.low_,this.high_|e.high_)};Timestamp.prototype.xor=function(e){return Timestamp.fromBits(this.low_^e.low_,this.high_^e.high_)};Timestamp.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Timestamp.fromBits(t<>>32-e)}else{return Timestamp.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Timestamp.fromBits(t>>e-32,t>=0?0:-1)}}};Timestamp.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Timestamp.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Timestamp.fromBits(t,0)}else{return Timestamp.fromBits(t>>>e-32,0)}}};Timestamp.fromInt=function(e){if(-128<=e&&e<128){var t=Timestamp.INT_CACHE_[e];if(t){return t}}var r=new Timestamp(e|0,e<0?-1:0);if(-128<=e&&e<128){Timestamp.INT_CACHE_[e]=r}return r};Timestamp.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Timestamp.ZERO}else if(e<=-Timestamp.TWO_PWR_63_DBL_){return Timestamp.MIN_VALUE}else if(e+1>=Timestamp.TWO_PWR_63_DBL_){return Timestamp.MAX_VALUE}else if(e<0){return Timestamp.fromNumber(-e).negate()}else{return new Timestamp(e%Timestamp.TWO_PWR_32_DBL_|0,e/Timestamp.TWO_PWR_32_DBL_|0)}};Timestamp.fromBits=function(e,t){return new Timestamp(e,t)};Timestamp.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Timestamp.fromNumber(Math.pow(r,8));var o=Timestamp.ZERO;for(var s=0;s{var n=r(4300).Buffer;var o=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){o=new Int32Array(o)}function ensureBuffer(e){if(n.isBuffer(e)){return e}var t=typeof n.alloc==="function"&&typeof n.from==="function";if(typeof e==="number"){return t?n.alloc(e):new n(e)}else if(typeof e==="string"){return t?n.from(e):new n(e)}else{throw new Error("input must be buffer, number, or string, received "+typeof e)}}function bufferizeInt(e){var t=ensureBuffer(4);t.writeInt32BE(e,0);return t}function _crc32(e,t){e=ensureBuffer(e);if(n.isBuffer(t)){t=t.readUInt32BE(0)}var r=~~t^-1;for(var s=0;s>>8}return r^-1}function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};e.exports=crc32},1362:e=>{"use strict";const t=/[\p{Lu}]/u;const r=/[\p{Ll}]/u;const n=/^[\p{Lu}](?![\p{Lu}])/gu;const o=/([\p{Alpha}\p{N}_]|$)/u;const s=/[_.\- ]+/;const i=new RegExp("^"+s.source);const a=new RegExp(s.source+o.source,"gu");const A=new RegExp("\\d+"+o.source,"gu");const preserveCamelCase=(e,n,o)=>{let s=false;let i=false;let a=false;for(let A=0;A{n.lastIndex=0;return e.replace(n,(e=>t(e)))};const postProcess=(e,t)=>{a.lastIndex=0;A.lastIndex=0;return e.replace(a,((e,r)=>t(r))).replace(A,(e=>t(e)))};const camelCase=(e,t)=>{if(!(typeof e==="string"||Array.isArray(e))){throw new TypeError("Expected the input to be `string | string[]`")}t={pascalCase:false,preserveConsecutiveUppercase:false,...t};if(Array.isArray(e)){e=e.map((e=>e.trim())).filter((e=>e.length)).join("-")}else{e=e.trim()}if(e.length===0){return""}const r=t.locale===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale);const n=t.locale===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);if(e.length===1){return t.pascalCase?n(e):r(e)}const o=e!==r(e);if(o){e=preserveCamelCase(e,r,n)}e=e.replace(i,"");if(t.preserveConsecutiveUppercase){e=preserveConsecutiveUppercase(e,r)}else{e=r(e)}if(t.pascalCase){e=n(e.charAt(0))+e.slice(1)}return postProcess(e,n)};e.exports=camelCase;e.exports["default"]=camelCase},9930:(e,t,r)=>{var n=r(1017);e.exports=function(e,t){if(t){var r=t.map((function(t){return n.resolve(e,t)}))}else{var r=e}var o=r.slice(1).reduce((function(e,t){if(!t.match(/^([A-Za-z]:)?\/|\\/)){throw new Error("relative path without a basedir")}var r=t.split(/\/+|\\+/);for(var n=0;e[n]===r[n]&&n1?o.join("/"):"/"}},6891:e=>{e.exports=function(e,r){var n=[];for(var o=0;o{t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.storage=localstorage();t.destroy=(()=>{let e=false;return()=>{if(!e){e=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(t){t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff);if(!this.useColors){return}const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0;let o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{if(e==="%%"){return}n++;if(e==="%c"){o=n}}));t.splice(o,0,r)}t.log=console.debug||console.log||(()=>{});function save(e){try{if(e){t.storage.setItem("debug",e)}else{t.storage.removeItem("debug")}}catch(e){}}function load(){let e;try{e=t.storage.getItem("debug")}catch(e){}if(!e&&typeof process!=="undefined"&&"env"in process){e=process.env.DEBUG}return e}function localstorage(){try{return localStorage}catch(e){}}e.exports=r(6243)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},6243:(e,t,r)=>{function setup(e){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=r(900);createDebug.destroy=destroy;Object.keys(e).forEach((t=>{createDebug[t]=e[t]}));createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let t=0;for(let r=0;r{if(t==="%%"){return"%"}s++;const o=createDebug.formatters[n];if(typeof o==="function"){const n=e[s];t=o.call(r,n);e.splice(s,1);s--}return t}));createDebug.formatArgs.call(r,e);const i=r.log||createDebug.log;i.apply(r,e)}debug.namespace=e;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(e);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>r===null?createDebug.enabled(e):r,set:e=>{r=e}});if(typeof createDebug.init==="function"){createDebug.init(debug)}return debug}function extend(e,t){const r=createDebug(this.namespace+(typeof t==="undefined"?":":t)+e);r.log=this.log;return r}function enable(e){createDebug.save(e);createDebug.names=[];createDebug.skips=[];let t;const r=(typeof e==="string"?e:"").split(/[\s,]+/);const n=r.length;for(t=0;t"-"+e))].join(",");createDebug.enable("");return e}function enabled(e){if(e[e.length-1]==="*"){return true}let t;let r;for(t=0,r=createDebug.skips.length;t{if(typeof process==="undefined"||process.type==="renderer"||process.browser===true||process.__nwjs){e.exports=r(8222)}else{e.exports=r(5332)}},5332:(e,t,r)=>{const n=r(6224);const o=r(3837);t.init=init;t.log=log;t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.destroy=o.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");t.colors=[6,2,3,4,5,1];try{const e=r(9318);if(e&&(e.stderr||e).level>=2){t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];if(/^(yes|on|true|enabled)$/i.test(n)){n=true}else if(/^(no|off|false|disabled)$/i.test(n)){n=false}else if(n==="null"){n=null}else{n=Number(n)}e[r]=n;return e}),{});function useColors(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(t){const{namespace:r,useColors:n}=this;if(n){const n=this.color;const o="[3"+(n<8?n:"8;5;"+n);const s=` ${o};1m${r} `;t[0]=s+t[0].split("\n").join("\n"+s);t.push(o+"m+"+e.exports.humanize(this.diff)+"")}else{t[0]=getDate()+r+" "+t[0]}}function getDate(){if(t.inspectOpts.hideDate){return""}return(new Date).toISOString()+" "}function log(...e){return process.stderr.write(o.format(...e)+"\n")}function save(e){if(e){process.env.DEBUG=e}else{delete process.env.DEBUG}}function load(){return process.env.DEBUG}function init(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;ne.trim())).join(" ")};s.O=function(e){this.inspectOpts.colors=this.useColors;return o.inspect(e,this.inspectOpts)}},2342:e=>{"use strict";function Denque(e,t){var t=t||{};this._head=0;this._tail=0;this._capacity=t.capacity;this._capacityMask=3;this._list=new Array(4);if(Array.isArray(e)){this._fromArray(e)}}Denque.prototype.peekAt=function peekAt(e){var t=e;if(t!==(t|0)){return void 0}var r=this.size();if(t>=r||t<-r)return undefined;if(t<0)t+=r;t=this._head+t&this._capacityMask;return this._list[t]};Denque.prototype.get=function get(e){return this.peekAt(e)};Denque.prototype.peek=function peek(){if(this._head===this._tail)return undefined;return this._list[this._head]};Denque.prototype.peekFront=function peekFront(){return this.peek()};Denque.prototype.peekBack=function peekBack(){return this.peekAt(-1)};Object.defineProperty(Denque.prototype,"length",{get:function length(){return this.size()}});Denque.prototype.size=function size(){if(this._head===this._tail)return 0;if(this._headthis._capacity)this.pop();if(this._head1e4&&this._tail<=this._list.length>>>2)this._shrinkArray();return t};Denque.prototype.push=function push(e){if(e===undefined)return this.size();var t=this._tail;this._list[t]=e;this._tail=t+1&this._capacityMask;if(this._tail===this._head){this._growArray()}if(this._capacity&&this.size()>this._capacity){this.shift()}if(this._head1e4&&e<=t>>>2)this._shrinkArray();return r};Denque.prototype.removeOne=function removeOne(e){var t=e;if(t!==(t|0)){return void 0}if(this._head===this._tail)return void 0;var r=this.size();var n=this._list.length;if(t>=r||t<-r)return void 0;if(t<0)t+=r;t=this._head+t&this._capacityMask;var o=this._list[t];var s;if(e0;s--){this._list[t]=this._list[t=t-1+n&this._capacityMask]}this._list[t]=void 0;this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--){this._list[t]=this._list[t=t+1+n&this._capacityMask]}this._list[t]=void 0;this._tail=this._tail-1+n&this._capacityMask}return o};Denque.prototype.remove=function remove(e,t){var r=e;var n;var o=t;if(r!==(r|0)){return void 0}if(this._head===this._tail)return void 0;var s=this.size();var i=this._list.length;if(r>=s||r<-s||t<1)return void 0;if(r<0)r+=s;if(t===1||!t){n=new Array(1);n[0]=this.removeOne(r);return n}if(r===0&&r+t>=s){n=this.toArray();this.clear();return n}if(r+t>s)t=s-r;var a;n=new Array(t);for(a=0;a0;a--){this._list[r=r+1+i&this._capacityMask]=void 0}return n}if(e===0){this._head=this._head+t+i&this._capacityMask;for(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])}r=this._head-1+i&this._capacityMask;while(o>0){this._list[r=r-1+i&this._capacityMask]=void 0;o--}if(e<0)this._tail=r}else{this._tail=r;r=r+t+i&this._capacityMask;for(a=s-(t+e);a>0;a--){this.push(this._list[r++])}r=this._tail;while(o>0){this._list[r=r+1+i&this._capacityMask]=void 0;o--}}if(this._head<2&&this._tail>1e4&&this._tail<=i>>>2)this._shrinkArray();return n};Denque.prototype.splice=function splice(e,t){var r=e;if(r!==(r|0)){return void 0}var n=this.size();if(r<0)r+=n;if(r>n)return void 0;if(arguments.length>2){var o;var s;var i;var a=arguments.length;var A=this._list.length;var c=2;if(!n||r0){this._head=this._head+r+A&this._capacityMask}}else{i=this.remove(r,t);this._head=this._head+r+A&this._capacityMask}while(a>c){this.unshift(arguments[--a])}for(o=r;o>0;o--){this.unshift(s[o-1])}}else{s=new Array(n-(r+t));var l=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1;this._capacityMask>>>=1};e.exports=Denque},1205:(e,t,r)=>{var n=r(1223);var noop=function(){};var isRequest=function(e){return e.setHeader&&typeof e.abort==="function"};var isChildProcess=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3};var eos=function(e,t,r){if(typeof t==="function")return eos(e,null,t);if(!t)t={};r=n(r||noop);var o=e._writableState;var s=e._readableState;var i=t.readable||t.readable!==false&&e.readable;var a=t.writable||t.writable!==false&&e.writable;var A=false;var onlegacyfinish=function(){if(!e.writable)onfinish()};var onfinish=function(){a=false;if(!i)r.call(e)};var onend=function(){i=false;if(!a)r.call(e)};var onexit=function(t){r.call(e,t?new Error("exited with error code: "+t):null)};var onerror=function(t){r.call(e,t)};var onclose=function(){process.nextTick(onclosenexttick)};var onclosenexttick=function(){if(A)return;if(i&&!(s&&(s.ended&&!s.destroyed)))return r.call(e,new Error("premature close"));if(a&&!(o&&(o.ended&&!o.destroyed)))return r.call(e,new Error("premature close"))};var onrequest=function(){e.req.on("finish",onfinish)};if(isRequest(e)){e.on("complete",onfinish);e.on("abort",onclose);if(e.req)onrequest();else e.on("request",onrequest)}else if(a&&!o){e.on("end",onlegacyfinish);e.on("close",onlegacyfinish)}if(isChildProcess(e))e.on("exit",onexit);e.on("end",onend);e.on("finish",onfinish);if(t.error!==false)e.on("error",onerror);e.on("close",onclose);return function(){A=true;e.removeListener("complete",onfinish);e.removeListener("abort",onclose);e.removeListener("request",onrequest);if(e.req)e.req.removeListener("finish",onfinish);e.removeListener("end",onlegacyfinish);e.removeListener("close",onlegacyfinish);e.removeListener("finish",onfinish);e.removeListener("exit",onexit);e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose)}};e.exports=eos},5010:(e,t,r)=>{var n=r(7147);var o=r(3837);var s=r(2781);var i=s.Readable;var a=s.Writable;var A=s.PassThrough;var c=r(4833);var l=r(2361).EventEmitter;t.createFromBuffer=createFromBuffer;t.createFromFd=createFromFd;t.BufferSlicer=BufferSlicer;t.FdSlicer=FdSlicer;o.inherits(FdSlicer,l);function FdSlicer(e,t){t=t||{};l.call(this);this.fd=e;this.pend=new c;this.pend.max=1;this.refCount=0;this.autoClose=!!t.autoClose}FdSlicer.prototype.read=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.read(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.write=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.write(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.createReadStream=function(e){return new ReadStream(this,e)};FdSlicer.prototype.createWriteStream=function(e){return new WriteStream(this,e)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var e=this;e.refCount-=1;if(e.refCount>0)return;if(e.refCount<0)throw new Error("invalid unref");if(e.autoClose){n.close(e.fd,onCloseDone)}function onCloseDone(t){if(t){e.emit("error",t)}else{e.emit("close")}}};o.inherits(ReadStream,i);function ReadStream(e,t){t=t||{};i.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end;this.pos=this.start;this.destroyed=false}ReadStream.prototype._read=function(e){var t=this;if(t.destroyed)return;var r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null){r=Math.min(r,t.endOffset-t.pos)}if(r<=0){t.destroyed=true;t.push(null);t.context.unref();return}t.context.pend.go((function(e){if(t.destroyed)return e();var o=new Buffer(r);n.read(t.context.fd,o,0,r,t.pos,(function(r,n){if(r){t.destroy(r)}else if(n===0){t.destroyed=true;t.push(null);t.context.unref()}else{t.pos+=n;t.push(o.slice(0,n))}e()}))}))};ReadStream.prototype.destroy=function(e){if(this.destroyed)return;e=e||new Error("stream destroyed");this.destroyed=true;this.emit("error",e);this.context.unref()};o.inherits(WriteStream,a);function WriteStream(e,t){t=t||{};a.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end==null?Infinity:+t.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}WriteStream.prototype._write=function(e,t,r){var o=this;if(o.destroyed)return;if(o.pos+e.length>o.endOffset){var s=new Error("maximum file length exceeded");s.code="ETOOBIG";o.destroy();r(s);return}o.context.pend.go((function(t){if(o.destroyed)return t();n.write(o.context.fd,e,0,e.length,o.pos,(function(e,n){if(e){o.destroy();t();r(e)}else{o.bytesWritten+=n;o.pos+=n;o.emit("progress");t();r()}}))}))};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};o.inherits(BufferSlicer,l);function BufferSlicer(e,t){l.call(this);t=t||{};this.refCount=0;this.buffer=e;this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}BufferSlicer.prototype.read=function(e,t,r,n,o){var s=n+r;var i=s-this.buffer.length;var a=i>0?i:r;this.buffer.copy(e,t,n,s);setImmediate((function(){o(null,a)}))};BufferSlicer.prototype.write=function(e,t,r,n,o){e.copy(this.buffer,n,t,t+r);setImmediate((function(){o(null,r,e)}))};BufferSlicer.prototype.createReadStream=function(e){e=e||{};var t=new A(e);t.destroyed=false;t.start=e.start||0;t.endOffset=e.end;t.pos=t.endOffset||this.buffer.length;var r=this.buffer.slice(t.start,t.pos);var n=0;while(true){var o=n+this.maxChunkSize;if(o>=r.length){if(nr.endOffset){var i=new Error("maximum file length exceeded");i.code="ETOOBIG";r.destroyed=true;o(i);return}e.copy(t.buffer,r.pos,0,e.length);r.bytesWritten+=e.length;r.pos=s;r.emit("progress");o()};r.destroy=function(){r.destroyed=true};return r};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(e,t){return new BufferSlicer(e,t)}function createFromFd(e,t){return new FdSlicer(e,t)}},7281:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(9930);const i=r(8098);const a=r(9126);const{env:A,cwd:c}=process;const isWritable=e=>{try{o.accessSync(e,o.constants.W_OK);return true}catch(e){return false}};function useDirectory(e,t){if(t.create){a.sync(e)}if(t.thunk){return(...t)=>n.join(e,...t)}return e}function getNodeModuleDirectory(e){const t=n.join(e,"node_modules");if(!isWritable(t)&&(o.existsSync(t)||!isWritable(n.join(e)))){return}return t}e.exports=(e={})=>{if(A.CACHE_DIR&&!["true","false","1","0"].includes(A.CACHE_DIR)){return useDirectory(n.join(A.CACHE_DIR,e.name),e)}let{cwd:t=c()}=e;if(e.files){t=s(t,e.files)}t=i.sync(t);if(!t){return}const r=getNodeModuleDirectory(t);if(!r){return undefined}return useDirectory(n.join(t,"node_modules",".cache",e.name),e)}},3186:(e,t,r)=>{e.exports=r(7147).constants||r(2057)},6863:(e,t,r)=>{e.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var n=r(7147);var o=n.realpath;var s=n.realpathSync;var i=process.version;var a=/^v[0-5]\./.test(i);var A=r(1734);function newError(e){return e&&e.syscall==="realpath"&&(e.code==="ELOOP"||e.code==="ENOMEM"||e.code==="ENAMETOOLONG")}function realpath(e,t,r){if(a){return o(e,t,r)}if(typeof t==="function"){r=t;t=null}o(e,t,(function(n,o){if(newError(n)){A.realpath(e,t,r)}else{r(n,o)}}))}function realpathSync(e,t){if(a){return s(e,t)}try{return s(e,t)}catch(r){if(newError(r)){return A.realpathSync(e,t)}else{throw r}}}function monkeypatch(){n.realpath=realpath;n.realpathSync=realpathSync}function unmonkeypatch(){n.realpath=o;n.realpathSync=s}},1734:(e,t,r)=>{var n=r(1017);var o=process.platform==="win32";var s=r(7147);var i=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function rethrow(){var e;if(i){var t=new Error;e=debugCallback}else e=missingCallback;return e;function debugCallback(e){if(e){t.message=e.message;e=t;missingCallback(e)}}function missingCallback(e){if(e){if(process.throwDeprecation)throw e;else if(!process.noDeprecation){var t="fs: missing callback "+(e.stack||e.message);if(process.traceDeprecation)console.trace(t);else console.error(t)}}}}function maybeCallback(e){return typeof e==="function"?e:rethrow()}var a=n.normalize;if(o){var A=/(.*?)(?:[\/\\]+|$)/g}else{var A=/(.*?)(?:[\/]+|$)/g}if(o){var c=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/}else{var c=/^[\/]*/}t.realpathSync=function realpathSync(e,t){e=n.resolve(e);if(t&&Object.prototype.hasOwnProperty.call(t,e)){return t[e]}var r=e,i={},a={};var l;var u;var h;var d;start();function start(){var t=c.exec(e);l=t[0].length;u=t[0];h=t[0];d="";if(o&&!a[h]){s.lstatSync(h);a[h]=true}}while(l=e.length){if(t)t[i]=e;return r(null,e)}A.lastIndex=u;var n=A.exec(e);g=h;h+=n[0];d=g+n[1];u=A.lastIndex;if(l[d]||t&&t[d]===d){return process.nextTick(LOOP)}if(t&&Object.prototype.hasOwnProperty.call(t,d)){return gotResolvedLink(t[d])}return s.lstat(d,gotStat)}function gotStat(e,n){if(e)return r(e);if(!n.isSymbolicLink()){l[d]=true;if(t)t[d]=d;return process.nextTick(LOOP)}if(!o){var i=n.dev.toString(32)+":"+n.ino.toString(32);if(a.hasOwnProperty(i)){return gotTarget(null,a[i],d)}}s.stat(d,(function(e){if(e)return r(e);s.readlink(d,(function(e,t){if(!o)a[i]=t;gotTarget(e,t)}))}))}function gotTarget(e,o,s){if(e)return r(e);var i=n.resolve(g,o);if(t)t[s]=i;gotResolvedLink(i)}function gotResolvedLink(t){e=n.resolve(t,e.slice(u));start()}}},3002:(e,t,r)=>{"use strict";const n=r(1808);class Locked extends Error{constructor(e){super(`${e} is locked`)}}const o={old:new Set,young:new Set};const s=1e3*15;let i;const getAvailablePort=e=>new Promise(((t,r)=>{const o=n.createServer();o.unref();o.on("error",r);o.listen(e,(()=>{const{port:e}=o.address();o.close((()=>{t(e)}))}))}));const portCheckSequence=function*(e){if(e){yield*e}yield 0};e.exports=async e=>{let t;if(e){t=typeof e.port==="number"?[e.port]:e.port}if(i===undefined){i=setInterval((()=>{o.old=o.young;o.young=new Set}),s);if(i.unref){i.unref()}}for(const r of portCheckSequence(t)){try{let t=await getAvailablePort({...e,port:r});while(o.old.has(t)||o.young.has(t)){if(r!==0){throw new Locked(r)}t=await getAvailablePort({...e,port:r})}o.young.add(t);return t}catch(e){if(!["EADDRINUSE","EACCES"].includes(e.code)&&!(e instanceof Locked)){throw e}}}throw new Error("No available ports found")};e.exports.makeRange=(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)){throw new TypeError("`from` and `to` must be integer numbers")}if(e<1024||e>65535){throw new RangeError("`from` must be between 1024 and 65535")}if(t<1024||t>65536){throw new RangeError("`to` must be between 1024 and 65536")}if(t{t.setopts=setopts;t.ownProp=ownProp;t.makeAbs=makeAbs;t.finish=finish;t.mark=mark;t.isIgnored=isIgnored;t.childrenIgnored=childrenIgnored;function ownProp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var n=r(1017);var o=r(3973);var s=r(8714);var i=o.Minimatch;function alphasort(e,t){return e.localeCompare(t,"en")}function setupIgnores(e,t){e.ignore=t.ignore||[];if(!Array.isArray(e.ignore))e.ignore=[e.ignore];if(e.ignore.length){e.ignore=e.ignore.map(ignoreMap)}}function ignoreMap(e){var t=null;if(e.slice(-3)==="/**"){var r=e.replace(/(\/\*\*)+$/,"");t=new i(r,{dot:true})}return{matcher:new i(e,{dot:true}),gmatcher:t}}function setopts(e,t,r){if(!r)r={};if(r.matchBase&&-1===t.indexOf("/")){if(r.noglobstar){throw new Error("base matching requires globstar")}t="**/"+t}e.silent=!!r.silent;e.pattern=t;e.strict=r.strict!==false;e.realpath=!!r.realpath;e.realpathCache=r.realpathCache||Object.create(null);e.follow=!!r.follow;e.dot=!!r.dot;e.mark=!!r.mark;e.nodir=!!r.nodir;if(e.nodir)e.mark=true;e.sync=!!r.sync;e.nounique=!!r.nounique;e.nonull=!!r.nonull;e.nosort=!!r.nosort;e.nocase=!!r.nocase;e.stat=!!r.stat;e.noprocess=!!r.noprocess;e.absolute=!!r.absolute;e.maxLength=r.maxLength||Infinity;e.cache=r.cache||Object.create(null);e.statCache=r.statCache||Object.create(null);e.symlinks=r.symlinks||Object.create(null);setupIgnores(e,r);e.changedCwd=false;var o=process.cwd();if(!ownProp(r,"cwd"))e.cwd=o;else{e.cwd=n.resolve(r.cwd);e.changedCwd=e.cwd!==o}e.root=r.root||n.resolve(e.cwd,"/");e.root=n.resolve(e.root);if(process.platform==="win32")e.root=e.root.replace(/\\/g,"/");e.cwdAbs=s(e.cwd)?e.cwd:makeAbs(e,e.cwd);if(process.platform==="win32")e.cwdAbs=e.cwdAbs.replace(/\\/g,"/");e.nomount=!!r.nomount;r.nonegate=true;r.nocomment=true;e.minimatch=new i(t,r);e.options=e.minimatch.options}function finish(e){var t=e.nounique;var r=t?[]:Object.create(null);for(var n=0,o=e.matches.length;n{e.exports=glob;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(4124);var A=r(2361).EventEmitter;var c=r(1017);var l=r(9491);var u=r(8714);var h=r(9010);var d=r(7625);var g=d.setopts;var p=d.ownProp;var E=r(2492);var m=r(3837);var C=d.childrenIgnored;var I=d.isIgnored;var y=r(1223);function glob(e,t,r){if(typeof t==="function")r=t,t={};if(!t)t={};if(t.sync){if(r)throw new TypeError("callback provided to sync glob");return h(e,t)}return new Glob(e,t,r)}glob.sync=h;var B=glob.GlobSync=h.GlobSync;glob.glob=glob;function extend(e,t){if(t===null||typeof t!=="object"){return e}var r=Object.keys(t);var n=r.length;while(n--){e[r[n]]=t[r[n]]}return e}glob.hasMagic=function(e,t){var r=extend({},t);r.noprocess=true;var n=new Glob(e,r);var o=n.minimatch.set;if(!e)return false;if(o.length>1)return true;for(var s=0;sthis.maxLength)return t();if(!this.stat&&p(this.cache,r)){var s=this.cache[r];if(Array.isArray(s))s="DIR";if(!o||s==="DIR")return t(null,s);if(o&&s==="FILE")return t()}var i;var a=this.statCache[r];if(a!==undefined){if(a===false)return t(null,a);else{var A=a.isDirectory()?"DIR":"FILE";if(o&&A==="FILE")return t();else return t(null,A,a)}}var c=this;var l=E("stat\0"+r,lstatcb_);if(l)n.lstat(r,l);function lstatcb_(o,s){if(s&&s.isSymbolicLink()){return n.stat(r,(function(n,o){if(n)c._stat2(e,r,null,s,t);else c._stat2(e,r,n,o,t)}))}else{c._stat2(e,r,o,s,t)}}};Glob.prototype._stat2=function(e,t,r,n,o){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR")){this.statCache[t]=false;return o()}var s=e.slice(-1)==="/";this.statCache[t]=n;if(t.slice(-1)==="/"&&n&&!n.isDirectory())return o(null,false,n);var i=true;if(n)i=n.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||i;if(s&&i==="FILE")return o();return o(null,i,n)}},9010:(e,t,r)=>{e.exports=globSync;globSync.GlobSync=GlobSync;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(1957).Glob;var A=r(3837);var c=r(1017);var l=r(9491);var u=r(8714);var h=r(7625);var d=h.setopts;var g=h.ownProp;var p=h.childrenIgnored;var E=h.isIgnored;function globSync(e,t){if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(e,t).found}function GlobSync(e,t){if(!e)throw new Error("must provide pattern");if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(e,t);d(this,e,t);if(this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;nthis.maxLength)return false;if(!this.stat&&g(this.cache,t)){var o=this.cache[t];if(Array.isArray(o))o="DIR";if(!r||o==="DIR")return o;if(r&&o==="FILE")return false}var s;var i=this.statCache[t];if(!i){var a;try{a=n.lstatSync(t)}catch(e){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[t]=false;return false}}if(a&&a.isSymbolicLink()){try{i=n.statSync(t)}catch(e){i=a}}else{i=a}}this.statCache[t]=i;var o=true;if(i)o=i.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||o;if(r&&o==="FILE")return false;return o};GlobSync.prototype._mark=function(e){return h.mark(this,e)};GlobSync.prototype._makeAbs=function(e){return h.makeAbs(this,e)}},1621:e=>{"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":e.length===1?"-":"--";const n=t.indexOf(r+e);const o=t.indexOf("--");return n!==-1&&(o===-1||n{h("replaying proxy buffer for failed request");A.default(e.listenerCount("data")>0);e.push(C);e.push(null)}));return I}))}}t["default"]=HttpsProxyAgent;function resume(e){e.resume()}function isDefaultPort(e,t){return Boolean(!t&&e===80||t&&e===443)}function isHTTPS(e){return typeof e==="string"?/^https:?$/i.test(e):false}function omit(e,...t){const r={};let n;for(n in e){if(!t.includes(n)){r[n]=e[n]}}return r}},7219:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(3734));function createHttpsProxyAgent(e){return new o.default(e)}(function(e){e.HttpsProxyAgent=o.default;e.prototype=o.default.prototype})(createHttpsProxyAgent||(createHttpsProxyAgent={}));e.exports=createHttpsProxyAgent},595:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=n(r(8237));const s=o.default("https-proxy-agent:parse-proxy-response");function parseProxyResponse(e){return new Promise(((t,r)=>{let n=0;const o=[];function read(){const t=e.read();if(t)ondata(t);else e.once("readable",read)}function cleanup(){e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose);e.removeListener("readable",read)}function onclose(e){s("onclose had error %o",e)}function onend(){s("onend")}function onerror(e){cleanup();s("onerror %o",e);r(e)}function ondata(e){o.push(e);n+=e.length;const r=Buffer.concat(o,n);const i=r.indexOf("\r\n\r\n");if(i===-1){s("have not received end of HTTP headers yet...");read();return}const a=r.toString("ascii",0,r.indexOf("\r\n"));const A=+a.split(" ")[1];s("got proxy server response: %o",a);t({statusCode:A,buffered:r})}e.on("error",onerror);e.on("close",onclose);e.on("end",onend);read()}))}t["default"]=parseProxyResponse},2492:(e,t,r)=>{var n=r(2940);var o=Object.create(null);var s=r(1223);e.exports=n(inflight);function inflight(e,t){if(o[e]){o[e].push(t);return null}else{o[e]=[t];return makeres(e)}}function makeres(e){return s((function RES(){var t=o[e];var r=t.length;var n=slice(arguments);try{for(var s=0;sr){t.splice(0,r);process.nextTick((function(){RES.apply(null,n)}))}else{delete o[e]}}}))}function slice(e){var t=e.length;var r=[];for(var n=0;n{try{var n=r(3837);if(typeof n.inherits!=="function")throw"";e.exports=n.inherits}catch(t){e.exports=r(8544)}},8544:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9126:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const{promisify:s}=r(3837);const i=r(1383);const a=i.satisfies(process.version,">=10.12.0");const checkPath=e=>{if(process.platform==="win32"){const t=/[<>:"|?*]/.test(e.replace(o.parse(e).root,""));if(t){const t=new Error(`Path contains invalid characters: ${e}`);t.code="EINVAL";throw t}}};const processOptions=e=>{const t={mode:511,fs:n};return{...t,...e}};const permissionError=e=>{const t=new Error(`operation not permitted, mkdir '${e}'`);t.code="EPERM";t.errno=-4048;t.path=e;t.syscall="mkdir";return t};const makeDir=async(e,t)=>{checkPath(e);t=processOptions(t);const r=s(t.fs.mkdir);const i=s(t.fs.stat);if(a&&t.fs.mkdir===n.mkdir){const n=o.resolve(e);await r(n,{mode:t.mode,recursive:true});return n}const make=async e=>{try{await r(e,t.mode);return e}catch(t){if(t.code==="EPERM"){throw t}if(t.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(t.message.includes("null bytes")){throw t}await make(o.dirname(e));return make(e)}try{const t=await i(e);if(!t.isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw t}return e}};return make(o.resolve(e))};e.exports=makeDir;e.exports.sync=(e,t)=>{checkPath(e);t=processOptions(t);if(a&&t.fs.mkdirSync===n.mkdirSync){const r=o.resolve(e);n.mkdirSync(r,{mode:t.mode,recursive:true});return r}const make=e=>{try{t.fs.mkdirSync(e,t.mode)}catch(r){if(r.code==="EPERM"){throw r}if(r.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(r.message.includes("null bytes")){throw r}make(o.dirname(e));return make(e)}try{if(!t.fs.statSync(e).isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw r}}return e};return make(o.resolve(e))}},1446:(e,t,r)=>{const n=r(6113);const o=r(7147);const s=8192;function md5FileSync(e){const t=o.openSync(e,"r");const r=n.createHash("md5");const i=Buffer.alloc(s);try{let e;do{e=o.readSync(t,i,0,s);r.update(i.slice(0,e))}while(e===s)}finally{o.closeSync(t)}return r.digest("hex")}function md5File(e){return new Promise(((t,r)=>{const s=n.createHash("md5");const i=o.createReadStream(e);i.on("error",(e=>{r(e)}));s.once("readable",(()=>{t(s.read().toString("hex"))}));i.pipe(s)}))}e.exports=md5File;e.exports.sync=md5FileSync},1529:e=>{e.exports=Pager;function Pager(e,t){if(!(this instanceof Pager))return new Pager(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?alloc(this.deduplicate.length):null}Pager.prototype.updated=function(e){while(this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate]){e.deduplicate++;if(e.deduplicate===this.deduplicate.length){e.deduplicate=0;if(e.buffer.equals&&e.buffer.equals(this.deduplicate))e.buffer=this.deduplicate;break}}if(e.updated||!this.updates)return;e.updated=true;this.updates.push(e)};Pager.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();e.updated=false;return e};Pager.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;grow(this,e)}factor(e,this.path);var r=this.pages;for(var n=this.level;n>0;n--){var o=this.path[n];var s=r[o];if(!s){if(t)return;s=r[o]=new Array(32768)}r=s}return r};Pager.prototype.get=function(e,t){var r=this._array(e,t);var n=this.path[0];var o=r&&r[n];if(!o&&!t){o=r[n]=new Page(e,alloc(this.pageSize));if(e>=this.length)this.length=e+1}if(o&&o.buffer===this.deduplicate&&this.deduplicate&&!t){o.buffer=copy(o.buffer);o.deduplicate=0}return o};Pager.prototype.set=function(e,t){var r=this._array(e,false);var n=this.path[0];if(e>=this.length)this.length=e+1;if(!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=undefined;return}if(this.deduplicate&&t.equals&&t.equals(this.deduplicate)){t=this.deduplicate}var o=r[n];var s=truncate(t,this.pageSize);if(o)o.buffer=s;else r[n]=new Page(e,s)};Pager.prototype.toBuffer=function(){var e=new Array(this.length);var t=alloc(this.pageSize);var r=0;while(rt)return e.slice(0,t);var r=alloc(t);e.copy(r);return r}function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function copy(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);e.copy(t);return t}function Page(e,t){this.offset=e*t.length;this.buffer=t;this.updated=false;this.deduplicate=0}function factor(e,t){e=(e-(t[0]=e&32767))/32768;e=(e-(t[1]=e&32767))/32768;t[3]=(e-(t[2]=e&32767))/32768&32767}},3973:(e,t,r)=>{e.exports=minimatch;minimatch.Minimatch=Minimatch;var n=function(){try{return r(1017)}catch(e){}}()||{sep:"/"};minimatch.sep=n.sep;var o=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={};var s=r(3717);var i={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};var a="[^/]";var A=a+"*?";var c="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var l="(?:(?!(?:\\/|^)\\.).)*?";var u=charSet("().*{}+?[]^$\\!");function charSet(e){return e.split("").reduce((function(e,t){e[t]=true;return e}),{})}var h=/\/+/;minimatch.filter=filter;function filter(e,t){t=t||{};return function(r,n,o){return minimatch(r,e,t)}}function ext(e,t){t=t||{};var r={};Object.keys(e).forEach((function(t){r[t]=e[t]}));Object.keys(t).forEach((function(e){r[e]=t[e]}));return r}minimatch.defaults=function(e){if(!e||typeof e!=="object"||!Object.keys(e).length){return minimatch}var t=minimatch;var r=function minimatch(r,n,o){return t(r,n,ext(e,o))};r.Minimatch=function Minimatch(r,n){return new t.Minimatch(r,ext(e,n))};r.Minimatch.defaults=function defaults(r){return t.defaults(ext(e,r)).Minimatch};r.filter=function filter(r,n){return t.filter(r,ext(e,n))};r.defaults=function defaults(r){return t.defaults(ext(e,r))};r.makeRe=function makeRe(r,n){return t.makeRe(r,ext(e,n))};r.braceExpand=function braceExpand(r,n){return t.braceExpand(r,ext(e,n))};r.match=function(r,n,o){return t.match(r,n,ext(e,o))};return r};Minimatch.defaults=function(e){return minimatch.defaults(e).Minimatch};function minimatch(e,t,r){assertValidPattern(t);if(!r)r={};if(!r.nocomment&&t.charAt(0)==="#"){return false}return new Minimatch(t,r).match(e)}function Minimatch(e,t){if(!(this instanceof Minimatch)){return new Minimatch(e,t)}assertValidPattern(e);if(!t)t={};e=e.trim();if(!t.allowWindowsEscape&&n.sep!=="/"){e=e.split(n.sep).join("/")}this.options=t;this.set=[];this.pattern=e;this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.partial=!!t.partial;this.make()}Minimatch.prototype.debug=function(){};Minimatch.prototype.make=make;function make(){var e=this.pattern;var t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate();var r=this.globSet=this.braceExpand();if(t.debug)this.debug=function debug(){console.error.apply(console,arguments)};this.debug(this.pattern,r);r=this.globParts=r.map((function(e){return e.split(h)}));this.debug(this.pattern,r);r=r.map((function(e,t,r){return e.map(this.parse,this)}),this);this.debug(this.pattern,r);r=r.filter((function(e){return e.indexOf(false)===-1}));this.debug(this.pattern,r);this.set=r}Minimatch.prototype.parseNegate=parseNegate;function parseNegate(){var e=this.pattern;var t=false;var r=this.options;var n=0;if(r.nonegate)return;for(var o=0,s=e.length;od){throw new TypeError("pattern is too long")}};Minimatch.prototype.parse=parse;var g={};function parse(e,t){assertValidPattern(e);var r=this.options;if(e==="**"){if(!r.noglobstar)return o;else e="*"}if(e==="")return"";var n="";var s=!!r.nocase;var c=false;var l=[];var h=[];var d;var p=false;var E=-1;var m=-1;var C=e.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var I=this;function clearStateChar(){if(d){switch(d){case"*":n+=A;s=true;break;case"?":n+=a;s=true;break;default:n+="\\"+d;break}I.debug("clearStateChar %j %j",d,n);d=false}}for(var y=0,B=e.length,Q;y-1;D--){var N=h[D];var T=n.slice(0,N.reStart);var O=n.slice(N.reStart,N.reEnd-8);var _=n.slice(N.reEnd-8,N.reEnd);var M=n.slice(N.reEnd);_+=M;var L=T.split("(").length-1;var F=M;for(y=0;y=0;i--){s=e[i];if(s)break}for(i=0;i>> no match, partial?",e,u,t,h);if(u===a)return true}return false}var g;if(typeof c==="string"){g=l===c;this.debug("string match",c,l,g)}else{g=l.match(c);this.debug("pattern match",c,l,g)}if(!g)return false}if(s===a&&i===A){return true}else if(s===a){return r}else if(i===A){return s===a-1&&e[s]===""}throw new Error("wtf?")};function globUnescape(e){return e.replace(/\\(.)/g,"$1")}function regExpEscape(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},1257:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoMemoryServer=t.MongoMemoryServerStates=t.MongoMemoryServerEvents=void 0;const n=r(4351);const o=(0,n.__importStar)(r(8517));const s=(0,n.__importDefault)(r(3002));const i=r(1978);const a=r(843);const A=(0,n.__importDefault)(r(8237));const c=r(2361);const l=r(7147);const u=r(5517);const h=r(1383);const d=r(3386);const g=(0,A.default)("MongoMS:MongoMemoryServer");o.setGracefulCleanup();var p;(function(e){e["stateChange"]="stateChange"})(p=t.MongoMemoryServerEvents||(t.MongoMemoryServerEvents={}));var E;(function(e){e["new"]="new";e["starting"]="starting";e["running"]="running";e["stopped"]="stopped"})(E=t.MongoMemoryServerStates||(t.MongoMemoryServerStates={}));class MongoMemoryServer extends c.EventEmitter{constructor(e){super();this._state=E.new;this.opts=Object.assign({},e);if(!(0,i.isNullOrUndefined)(this.opts.auth)){this.auth=(0,i.authDefault)(this.opts.auth)}}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("create: Called .create() method");const t=new MongoMemoryServer(Object.assign({},e));yield t.start();return t}))}start(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start: Called .start() method");switch(this._state){case E.new:case E.stopped:break;case E.running:case E.starting:default:throw new d.StateError([E.new,E.stopped],this.state)}(0,i.assertion)((0,i.isNullOrUndefined)((t=this._instanceInfo)===null||t===void 0?void 0:t.instance.mongodProcess),new Error('Cannot start because "instance.mongodProcess" is already defined!'));this.stateChange(E.starting);yield this._startUpInstance(e).catch((e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!A.default.enabled("MongoMS:MongoMemoryServer")){console.warn("Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n",e)}this.debug("_startUpInstance threw a Error: ",e);yield this.stop({doCleanup:false,force:false});this.stateChange(E.stopped);throw e}))));this.stateChange(E.running);this.debug("start: Instance fully Started")}))}stateChange(e){this._state=e;this.emit(p.stateChange,e)}debug(e,...t){var r,n;const o=(n=(r=this._instanceInfo)===null||r===void 0?void 0:r.port)!==null&&n!==void 0?n:"unknown";g(`Mongo[${o}]: ${e}`,...t)}getNewPort(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield(0,s.default)({port:e});if(e!=t&&typeof e==="number"){this.debug(`getNewPort: starting with port "${t}", since "${e}" was locked`)}return t}))}getStartOptions(e=false){var t,r,s;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`getStartOptions: forceSamePort: ${e}`);const n=(t=this.opts.instance)!==null&&t!==void 0?t:{};let a=true;let A=typeof n.port==="number"?n.port:undefined;if(!e||(0,i.isNullOrUndefined)(A)){A=yield this.getNewPort(A)}const c={port:A,dbName:(0,i.generateDbName)(n.dbName),ip:(r=n.ip)!==null&&r!==void 0?r:"127.0.0.1",storageEngine:(s=n.storageEngine)!==null&&s!==void 0?s:"ephemeralForTest",replSet:n.replSet,dbPath:n.dbPath,tmpDir:undefined};if((0,i.isNullOrUndefined)(this._instanceInfo)){if(!c.dbPath){c.tmpDir=o.dirSync({mode:493,prefix:"mongo-mem-",unsafeCleanup:true});c.dbPath=c.tmpDir.name;a=true}else{this.debug(`getStartOptions: Checking if "${c.dbPath}}" (no new tmpDir) already has data`);const e=yield l.promises.readdir(c.dbPath);a=e.length===0}}else{a=false}const u=(typeof n.auth==="boolean"?n.auth:true)&&!(0,i.isNullOrUndefined)(this.auth)&&!this.auth.disable&&(this.auth.force||a)&&!n.replSet;return{data:c,createAuth:u,mongodOptions:{instance:Object.assign(Object.assign({},c),{args:n.args,auth:u?false:n.auth}),binary:this.opts.binary,spawn:this.opts.spawn}}}))}_startUpInstance(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("_startUpInstance: Called MongoMemoryServer._startUpInstance() method");if(!(0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');if(!e){const e=yield this.getNewPort(this._instanceInfo.port);this._instanceInfo.instance.instanceOpts.port=e;this._instanceInfo.port=e}yield this._instanceInfo.instance.start();return}const{mongodOptions:r,createAuth:n,data:o}=yield this.getStartOptions(e);this.debug(`_startUpInstance: Creating new MongoDB instance with options:`,r);const s=yield a.MongoInstance.create(r);this.debug(`_startUpInstance: Instance Started, createAuth: "${n}"`);if(!(0,i.isNullOrUndefined)(this.auth)&&n){this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);yield this.createAuth(o);if(o.storageEngine!=="ephemeralForTest"){this.debug("_startUpInstance: Killing No-Auth instance");yield s.stop();this.debug("_startUpInstance: Starting Auth Instance");s.instanceOpts.auth=true;yield s.start()}else{console.warn("Not Restarting MongoInstance for Auth\n"+'Storage engine is "ephemeralForTest", which does not write data on shutdown, and mongodb does not allow changing "auth" runtime')}}else{if((t=this.opts.auth)===null||t===void 0?void 0:t.disable){this.debug('_startUpInstance: AutomaticAuth.disable is set to "true" skipping "createAuth"')}}this._instanceInfo=Object.assign(Object.assign({},o),{dbPath:o.dbPath,instance:s})}))}stop(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop: Called .stop() method");let n={doCleanup:true,force:false};if(typeof e==="boolean"){n.doCleanup=e}if(typeof e==="object"){n=e}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('stop: "instanceInfo" is not defined (never ran?)');return false}if(this._state===E.stopped){this.debug('stop: state is "stopped", trying to stop / kill anyway')}this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${(r=(t=this._instanceInfo.instance)===null||t===void 0?void 0:t.mongodProcess)===null||r===void 0?void 0:r.pid}`);yield this._instanceInfo.instance.stop();this.stateChange(E.stopped);if(n.doCleanup){yield this.cleanup(n)}return true}))}cleanup(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){assertionIsMMSState(E.stopped,this.state);let t={doCleanup:true,force:false};if(typeof e==="boolean"){t.force=e}if(typeof e==="object"){t=e}this.debug(`cleanup:`,t);if(!t.doCleanup){this.debug('cleanup: "doCleanup" is set to false');return}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('cleanup: "instanceInfo" is undefined');return}(0,i.assertion)((0,i.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess),new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));const r=this._instanceInfo.tmpDir;if(!(0,i.isNullOrUndefined)(r)){this.debug(`cleanup: removing tmpDir at ${r.name}`);r.removeCallback()}if(t.force){const e=this._instanceInfo.dbPath;const t=yield(0,i.statPath)(e);if((0,i.isNullOrUndefined)(t)){this.debug(`cleanup: force is true, but path "${e}" dosnt exist anymore`)}else{(0,i.assertion)(t.isDirectory(),new Error("Defined dbPath is not an directory"));if((0,h.lt)(process.version,"14.14.0")){yield l.promises.rmdir(e,{recursive:true,maxRetries:1})}else{yield l.promises.rm(e,{recursive:true,maxRetries:1})}}}this.stateChange(E.new);this._instanceInfo=undefined}))}get instanceInfo(){return this._instanceInfo}get state(){return this._state}ensureInstance(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("ensureInstance: Called .ensureInstance() method");switch(this._state){case E.running:if(this._instanceInfo){return this._instanceInfo}throw new d.EnsureInstanceError(true);case E.new:case E.stopped:break;case E.starting:return new Promise(((e,t)=>this.once(p.stateChange,(r=>{if(r!=E.running){t(new Error(`"ensureInstance" waited for "running" but got an different state: "${r}"`));return}(0,i.assertion)(!(0,i.isNullOrUndefined)(this._instanceInfo),new Error("InstanceInfo is undefined!"));e(this._instanceInfo)}))));default:throw new d.StateError([E.running,E.new,E.stopped,E.starting],this.state)}this.debug('ensureInstance: no running instance, calling "start()" command');yield this.start();this.debug('ensureInstance: "start()" command was succesfully resolved');if(!this._instanceInfo){throw new d.EnsureInstanceError(false)}return this._instanceInfo}))}getUri(e,t){this.debug("getUri:",this.state,e,t);switch(this.state){case E.running:case E.starting:break;case E.stopped:default:throw new d.StateError([E.running,E.starting],this.state)}assertionInstanceInfo(this._instanceInfo);return(0,i.uriTemplate)(t||"127.0.0.1",this._instanceInfo.port,(0,i.generateDbName)(e))}createAuth(e){var t,r,o;return(0,n.__awaiter)(this,void 0,void 0,(function*(){(0,i.assertion)(!(0,i.isNullOrUndefined)(this.auth),new Error('"createAuth" got called, but "this.auth" is undefined!'));this.debug("createAuth: options:",this.auth);const n=yield u.MongoClient.connect((0,i.uriTemplate)(e.ip,e.port,"admin"),{});try{let e=n.db("admin");this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);yield e.command({createUser:this.auth.customRootName,pwd:this.auth.customRootPwd,mechanisms:["SCRAM-SHA-256"],customData:{createdBy:"mongodb-memory-server",as:"ROOTUSER"},roles:["root"],writeConcern:{w:"majority"}});if(this.auth.extraUsers.length>0){this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);this.auth.extraUsers.sort(((e,t)=>{if(e.database==="admin"){return-1}return e.database===t.database?0:1}));for(const s of this.auth.extraUsers){s.database=(0,i.isNullOrUndefined)(s.database)?"admin":s.database;if(s.database!==e.databaseName){e=n.db(s.database)}this.debug("createAuth: Creating User: ",s);yield e.command({createUser:s.createUser,pwd:s.pwd,customData:Object.assign(Object.assign({},s.customData),{createdBy:"mongodb-memory-server",as:"EXTRAUSER"}),roles:s.roles,authenticationRestrictions:(t=s.authenticationRestrictions)!==null&&t!==void 0?t:[],mechanisms:(r=s.mechanisms)!==null&&r!==void 0?r:["SCRAM-SHA-256"],digestPassword:(o=s.digestPassword)!==null&&o!==void 0?o:true})}}}finally{yield n.close()}}))}}t.MongoMemoryServer=MongoMemoryServer;t["default"]=MongoMemoryServer;function assertionInstanceInfo(e){(0,i.assertion)(!(0,i.isNullOrUndefined)(e),new Error('"instanceInfo" is undefined'))}function assertionIsMMSState(e,t){(0,i.assertion)(t===e,new d.StateError([e],t))}},8919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.DryMongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(8730);const i=r(1978);const a=(0,n.__importStar)(r(1017));const A=r(2037);const c=(0,n.__importDefault)(r(7281));const l=r(8278);const u=r(3386);const h=r(1);const d=(0,o.default)("MongoMS:DryMongoBinary");class DryMongoBinary{static locateBinary(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d(`locateBinary: Trying to locate Binary for version "${e.version}"`);const t=yield this.generateOptions(e);if(!!t.systemBinary){d(`locateBinary: env "SYSTEM_BINARY" was provided with value: "${t.systemBinary}"`);const e=yield this.getSystemPath(t.systemBinary);if((0,i.isNullOrUndefined)(e)){throw new u.NoSystemBinaryFoundError(t.systemBinary)}return e}if(this.binaryCache.has(e.version)){const t=this.binaryCache.get(e.version);d(`locateBinary: Requested Version found in cache: "[${e.version}, ${t}]"`);return t}d("locateBinary: running generateDownloadPath");const r=yield this.generateDownloadPath(t);if(!r[0]){d("locateBinary: could not find a existing binary");return undefined}d(`locateBinary: found binary at "${r[1]}"`);this.binaryCache.set(e.version,r[1]);return r[1]}))}static generateOptions(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generateOptions");const n=(t=(0,s.resolveConfig)(s.ResolveConfigVariables.VERSION))!==null&&t!==void 0?t:s.DEFAULT_VERSION;const o=(0,i.isNullOrUndefined)(e)?{version:n}:e;const c={version:o.version||n,downloadDir:(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR)||o.downloadDir||"",os:(r=o.os)!==null&&r!==void 0?r:yield(0,l.getOS)(),platform:o.platform||(0,A.platform)(),arch:o.arch||(0,A.arch)(),systemBinary:(0,s.resolveConfig)(s.ResolveConfigVariables.SYSTEM_BINARY)||o.systemBinary||""};c.downloadDir=a.dirname((yield this.generateDownloadPath(c))[1]);if((0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME)||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)||(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);d(`generateOptions: ARCHIVE_NAME or DOWNLOAD_URL defined, generating options based on that (input: "${e}")`);return this.parseArchiveNameRegex(e,c)}return c}))}static parseArchiveNameRegex(e,t){d(`parseArchiveNameRegex (input: "${e}")`);const r=/mongodb-(?linux|win32|osx|macos)(?:-ssl-|-)(?\w{4,})(?:-(?\w+)|)(?:-ssl-|-)(?:v|)(?[\d.]+(?:-latest|))\./gim.exec(e);(0,i.assertion)(!(0,i.isNullOrUndefined)(r),new u.NoRegexMatchError("input"));(0,i.assertion)(!(0,i.isNullOrUndefined)(r.groups),new u.NoRegexMatchError("input","groups"));const n=r.groups;(0,i.assertion)(typeof n.version==="string"&&n.version.length>1,new u.ParseArchiveRegexError("version"));(0,i.assertion)(typeof n.platform==="string"&&n.platform.length>1,new u.ParseArchiveRegexError("platform"));(0,i.assertion)(typeof n.arch==="string"&&n.arch.length>=4,new u.ParseArchiveRegexError("arch"));t.version=n.version;t.arch=n.arch;if(n.platform==="linux"){const e=!!n.dist?/([a-z]+)(\d*)/gim.exec(n.dist):null;t.os={os:"linux",dist:typeof(e===null||e===void 0?void 0:e[1])==="string"?e[1]:"unknown",release:""}}else{t.os={os:n.platform}}return t}static getBinaryName(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getBinaryName");let t;if((0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.USE_ARCHIVE_NAME_FOR_BINARY_NAME))){const r=yield new h.MongoBinaryDownloadUrl(e).getArchiveName();t=a.parse(r).name}else{const r=e.platform==="win32"?".exe":"";const n=(0,l.isLinuxOS)(e.os)?e.os.dist:e.os.os;t=`mongod-${e.arch}-${n}-${e.version}${r}`}return t}))}static combineBinaryName(e,t){d("combineBinaryName");return a.resolve(e,t)}static getSystemPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getSystempath");try{yield(0,i.checkBinaryPermissions)(e);d(`getSystemPath: found system binary path at "${e}"`);return e}catch(t){d(`getSystemPath: can't find system binary at "${e}".\n${t instanceof Error?t.message:t}`)}return undefined}))}static generatePaths(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generatePaths",e);const t={legacyHomeCache:"",modulesCache:"",relative:"",resolveConfig:""};const r=yield this.getBinaryName(e);let n=process.env["INIT_CWD"]||process.cwd();while(n.includes(`node_modules${a.sep}mongodb-memory-server`)){n=a.resolve(n,"..","..")}const o=(0,c.default)({name:"mongodb-memory-server",cwd:n});if(!(0,i.isNullOrUndefined)(o)){t.modulesCache=this.combineBinaryName(a.resolve(o),r)}const A=a.resolve(this.homedir(),".cache/mongodb-binaries");t.legacyHomeCache=this.combineBinaryName(A,r);const l=e.downloadDir||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR);if(!(0,i.isNullOrUndefined)(l)&&l.length>0){d(`generatePaths: resolveConfigValue is not empty`);t.resolveConfig=this.combineBinaryName(l,r)}t.relative=this.combineBinaryName(a.resolve(process.cwd(),"mongodb-binaries"),r);return t}))}static generateDownloadPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.PREFER_GLOBAL_PATH));d(`generateDownloadPath: Generating Download Path, preferGlobal: "${t}"`);const r=yield this.generatePaths(e);d("generateDownloadPath: Paths:",r,e.systemBinary);if(!!e.systemBinary&&(yield(0,i.pathExists)(e.systemBinary))){const t=yield this.getSystemPath(e.systemBinary);if(!(0,i.isNullOrUndefined)(t)){return[true,t]}}if(yield(0,i.pathExists)(r.resolveConfig)){d(`generateDownloadPath: Found binary in resolveConfig (DOWNLOAD_DIR): "${r.resolveConfig}"`);return[true,r.resolveConfig]}if(yield(0,i.pathExists)(r.legacyHomeCache)){d(`generateDownloadPath: Found binary in legacyHomeCache: "${r.legacyHomeCache}"`);return[true,r.legacyHomeCache]}if(yield(0,i.pathExists)(r.modulesCache)){d(`generateDownloadPath: Found binary in modulesCache: "${r.modulesCache}"`);return[true,r.modulesCache]}if(yield(0,i.pathExists)(r.relative)){d(`generateDownloadPath: Found binary in relative: "${r.relative}"`);return[true,r.relative]}d(`generateDownloadPath: no existing binary for version "${e.version}" was found`);if(r.resolveConfig.length>0){d(`generateDownloadPath: using resolveConfig (DOWNLOAD_DIR) "${r.resolveConfig}"`);return[false,r.resolveConfig]}if(t&&!!r.legacyHomeCache){d(`generateDownloadPath: using global (preferGlobal) "${r.legacyHomeCache}"`);return[false,r.legacyHomeCache]}if(r.modulesCache.length>0){d(`generateDownloadPath: using modulesCache "${r.modulesCache}"`);return[false,r.modulesCache]}d(`generateDownloadPath: using relative "${r.relative}"`);return[false,r.relative]}))}static homedir(){return(0,A.homedir)()}}t.DryMongoBinary=DryMongoBinary;DryMongoBinary.binaryCache=new Map},9125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=(0,n.__importDefault)(r(1017));const i=(0,n.__importDefault)(r(229));const a=(0,n.__importStar)(r(8730));const A=(0,n.__importDefault)(r(8237));const c=(0,n.__importStar)(r(1383));const l=r(1978);const u=r(2081);const h=r(4908);const d=r(8919);const g=(0,A.default)("MongoMS:MongoBinary");class MongoBinary{static download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("download");const{downloadDir:t,version:r}=e;yield(0,l.mkdir)(t);const n=s.default.resolve(t,`${r}.lock`);g(`download: Waiting to acquire Download lock for file "${n}"`);const o=yield h.LockFile.lock(n);g("download: Download lock acquired");try{if(!d.DryMongoBinary.binaryCache.has(r)){g(`download: Adding version ${r} to cache`);const t=new i.default(e);d.DryMongoBinary.binaryCache.set(r,yield t.getMongodPath())}}finally{g("download: Removing Download lock");yield o.unlock();g("download: Download lock removed")}const a=d.DryMongoBinary.binaryCache.get(r);(0,l.assertion)(typeof a==="string",new Error(`No Cache Path for version "${r}" found (and download failed silently?)`));return a}))}static getPath(e={}){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("getPath");const t=Object.assign(Object.assign({},yield d.DryMongoBinary.generateOptions(e)),{platform:e.platform||(0,a.default)(a.ResolveConfigVariables.PLATFORM)||o.default.platform(),checkMD5:e.checkMD5||(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.MD5_CHECK))});g(`getPath: MongoBinary options:`,JSON.stringify(t,null,2));let r=yield d.DryMongoBinary.locateBinary(t);if(!!t.systemBinary){if(!(0,l.isNullOrUndefined)(r)){g(`getPath: Spawning binaryPath "${r}" to get version`);const e=(0,u.spawnSync)(r,["--version"]).stdout.toString().match(/^\s*db\s+version\s+v?(\d+\.\d+\.\d+)(-\d*)?(-[a-zA-Z0-9].*)?\s*$/im);(0,l.assertion)(!(0,l.isNullOrUndefined)(e),new Error("Couldnt find an version from system binary output!"));if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.SYSTEM_BINARY_VERSION_CHECK))){g("getPath: Checking & Warning about version conflicts");const r=e[1];if(c.neq(t.version,r)){console.warn("getPath: MongoMemoryServer: Possible version conflict\n"+` SystemBinary version: "${r}"\n`+` Requested version: "${t.version}"\n\n`+" Using SystemBinary!")}}}else{throw new Error('Option "SYSTEM_BINARY" was set, but binaryPath was empty! (system binary could not be found?) [This Error should normally not be thrown, please report this]')}}(0,l.assertion)(typeof t.version==="string",new Error('"MongoBinary.options.version" is not an string!'));if(!r){if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD))){g('getPath: "RUNTIME_DOWNLOAD" is "true", trying to download');r=yield this.download(t)}else{g('getPath: "RUNTIME_DOWNLOAD" is "false", not downloading')}}if(!r){const e=(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD));throw new Error(`MongoBinary.getPath: could not find an valid binary path! (Got: "${r}", RUNTIME_DOWNLOAD: "${e}")`)}g(`getPath: Mongod binary path: "${r}"`);return r}))}}t.MongoBinary=MongoBinary;t["default"]=MongoBinary},229:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownload=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=r(7310);const i=(0,n.__importDefault)(r(1017));const a=r(7147);const A=(0,n.__importDefault)(r(1446));const c=(0,n.__importDefault)(r(5687));const l=r(9796);const u=(0,n.__importDefault)(r(2283));const h=(0,n.__importDefault)(r(8781));const d=(0,n.__importDefault)(r(1));const g=r(7219);const p=(0,n.__importStar)(r(8730));const E=(0,n.__importDefault)(r(8237));const m=r(1978);const C=r(8919);const I=r(4521);const y=r(3386);const B=(0,E.default)("MongoMS:MongoBinaryDownload");class MongoBinaryDownload{constructor(e){var t,r,n,s,i,a;(0,m.assertion)(typeof e.downloadDir==="string",new Error("An DownloadDir must be specified!"));const A=(t=e.version)!==null&&t!==void 0?t:(0,p.default)(p.ResolveConfigVariables.VERSION);(0,m.assertion)(typeof A==="string",new Error("An MongoDB Binary version must be specified!"));this.binaryOpts={platform:(r=e.platform)!==null&&r!==void 0?r:o.default.platform(),arch:(n=e.arch)!==null&&n!==void 0?n:o.default.arch(),version:A,downloadDir:e.downloadDir,checkMD5:(s=e.checkMD5)!==null&&s!==void 0?s:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.MD5_CHECK)),systemBinary:(i=e.systemBinary)!==null&&i!==void 0?i:"",os:(a=e.os)!==null&&a!==void 0?a:{os:"unknown"}};this.dlProgress={current:0,length:0,totalMb:0,lastPrintedAt:0}}get checkMD5(){return this.binaryOpts.checkMD5}set checkMD5(e){this.binaryOpts.checkMD5=e}get downloadDir(){return this.binaryOpts.downloadDir}set downloadDir(e){this.binaryOpts.downloadDir=e}get arch(){return this.binaryOpts.arch}set arch(e){this.binaryOpts.arch=e}get version(){return this.binaryOpts.version}set version(e){this.binaryOpts.version=e}get platform(){return this.binaryOpts.platform}set platform(e){this.binaryOpts.platform=e}getPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield C.DryMongoBinary.generateOptions(this.binaryOpts);return C.DryMongoBinary.combineBinaryName(this.downloadDir,yield C.DryMongoBinary.getBinaryName(e))}))}getMongodPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("getMongodPath");const e=yield this.getPath();if(yield(0,m.pathExists)(e)){B(`getMongodPath: mongod path "${e}" already exists, using this`);return e}const t=yield this.startDownload();yield this.extract(t);yield a.promises.unlink(t);if(yield(0,m.pathExists)(e)){return e}throw new Error(`Cannot find downloaded mongod binary by path "${e}"`)}))}startDownload(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("startDownload");const e=new d.default(this.binaryOpts);yield(0,m.mkdir)(this.downloadDir);try{yield a.promises.access(this.downloadDir,a.constants.X_OK|a.constants.W_OK)}catch(e){console.error(`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n`+"Needed Permissions: Write & Execute (-wx)\n");throw e}const t=yield e.getDownloadUrl();const r=yield this.download(t);yield this.makeMD5check(`${t}.md5`,r);return r}))}makeMD5check(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("makeMD5check: Checking MD5 of downloaded binary...");if(!this.checkMD5){B("makeMD5check: checkMD5 is disabled");return undefined}const r=yield this.download(e);const n=(yield a.promises.readFile(r)).toString("utf-8");const o=n.match(/^\s*([\w\d]+)\s*/i);const s=o?o[1]:null;const i=A.default.sync(t);B(`makeMD5check: Local MD5: ${i}, Remote MD5: ${s}`);if(s!==i){throw new y.Md5CheckFailedError(i,s||"unknown")}yield a.promises.unlink(r);return true}))}download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("download");const t=process.env["yarn_https-proxy"]||process.env.yarn_proxy||process.env["npm_config_https-proxy"]||process.env.npm_config_proxy||process.env.https_proxy||process.env.http_proxy||process.env.HTTPS_PROXY||process.env.HTTP_PROXY;const r=process.env.npm_config_strict_ssl==="true";const n=new s.URL(e);n.port=n.port||"443";const o={method:"GET",rejectUnauthorized:r,protocol:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.USE_HTTP))?"http:":"https:",agent:t?new g.HttpsProxyAgent(t):undefined};const a=n.pathname.split("/").pop();if(!a){throw new Error(`MongoBinaryDownload: missing filename for url "${e}"`)}const A=i.default.resolve(this.downloadDir,a);const c=i.default.resolve(this.downloadDir,`${a}.downloading`);B(`download: Downloading${t?` via proxy "${t}"`:""}: "${e}"`);if(yield(0,m.pathExists)(A)){B("download: Already downloaded archive found, skipping download");return A}this.assignDownloadingURL(n);const l=yield this.httpDownload(n,o,A,c);return l}))}extract(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extract");const n=yield this.getPath();B(`extract: archive: "${e}" final: "${n}"`);yield(0,m.mkdir)(i.default.dirname(n));const filter=e=>/(?:bin\/(?:mongod(?:\.exe)?)|(?:.*\.dll))$/i.test(e);if(/(.tar.gz|.tgz)$/.test(e)){yield this.extractTarGz(e,n,filter)}else if(/.zip$/.test(e)){yield this.extractZip(e,n,filter)}else{throw new Error(`MongoBinaryDownload: unsupported archive "${e}" (downloaded from "${(t=this._downloadingUrl)!==null&&t!==void 0?t:"unknown"}"). Broken archive from MongoDB Provider?`)}if(!(yield(0,m.pathExists)(n))){throw new Error(`MongoBinaryDownload: missing mongod binary in "${e}" (downloaded from "${(r=this._downloadingUrl)!==null&&r!==void 0?r:"unknown"}"). Broken archive from MongoDB Provider?`)}return n}))}extractTarGz(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractTarGz");const n=u.default.extract();n.on("entry",((e,n,o)=>{if(r(e.name)){n.pipe((0,a.createWriteStream)(t,{mode:509}))}n.on("end",(()=>o()));n.resume()}));return new Promise(((t,r)=>{(0,a.createReadStream)(e).on("error",(t=>{r("Unable to open tarball "+e+": "+t)})).pipe((0,l.createUnzip)()).on("error",(t=>{r("Error during unzip for "+e+": "+t)})).pipe(n).on("error",(t=>{r("Error during untar for "+e+": "+t)})).on("finish",(e=>{t(e)}))}))}))}extractZip(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractZip");return new Promise(((n,o)=>{h.default.open(e,{lazyEntries:true},((e,s)=>{if(e||!s){return o(e)}s.readEntry();s.on("end",(()=>n()));s.on("entry",(e=>{if(!r(e.fileName)){return s.readEntry()}s.openReadStream(e,((e,r)=>{if(e||!r){return o(e)}r.on("end",(()=>s.readEntry()));r.pipe((0,a.createWriteStream)(t,{mode:509}))}))}))}))}))}))}httpDownload(e,t,r,o){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("httpDownload");const s=this.assignDownloadingURL(e);return new Promise(((i,A)=>{B(`httpDownload: trying to download "${s}"`);c.default.get(e,t,(e=>{if(e.statusCode!=200){if(e.statusCode===403){A(new Error("Status Code is 403 (MongoDB's 404)\n"+"This means that the requested version-platform combination doesn't exist\n"+` Used Url: "${s}"\n`+"Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n"+"List of available versions can be found here:\n"+" https://www.mongodb.org/dl/linux for Linux\n"+" https://www.mongodb.org/dl/osx for OSX\n"+" https://www.mongodb.org/dl/win32 for Windows"));return}A(new Error("Status Code isnt 200!"));return}if(typeof e.headers["content-length"]!="string"){A(new Error('Response header "content-length" is empty!'));return}this.dlProgress.current=0;this.dlProgress.length=parseInt(e.headers["content-length"],10);this.dlProgress.totalMb=Math.round(this.dlProgress.length/1048576*10)/10;const c=(0,a.createWriteStream)(o);e.pipe(c);c.on("finish",(()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){var e;if(this.dlProgress.current{this.printDownloadProgress(e)}))})).on("error",(e=>{console.error(`Couldnt download "${s}"!`,e.message);A(e)}))}))}))}printDownloadProgress(e,t=false){this.dlProgress.current+=e.length;const r=Date.now();if(r-this.dlProgress.lastPrintedAt<2e3&&!t){return}this.dlProgress.lastPrintedAt=r;const n=Math.round(100*this.dlProgress.current/this.dlProgress.length*10)/10;const o=Math.round(this.dlProgress.current/1048576*10)/10;const s=this.platform==="win32"?"":"\r";const i=`Downloading MongoDB "${this.version}": ${n}% (${o}mb / ${this.dlProgress.totalMb}mb)${s}`;if(process.stdout.isTTY){(0,I.clearLine)(process.stdout,0);process.stdout.write(i)}else{console.log(i)}}assignDownloadingURL(e){this._downloadingUrl=e.href;return this._downloadingUrl}}t.MongoBinaryDownload=MongoBinaryDownload;t["default"]=MongoBinaryDownload},1:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownloadUrl=void 0;const n=r(4351);const o=r(8278);const s=r(8730);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1383));const A=r(1978);const c=r(7310);const l=r(3386);const u=r(3837);const h=(0,i.default)("MongoMS:MongoBinaryDownloadUrl");class MongoBinaryDownloadUrl{constructor(e){this.version=e.version;this.platform=this.translatePlatform(e.platform);this.arch=MongoBinaryDownloadUrl.translateArch(e.arch,this.platform);this.os=e.os}getDownloadUrl(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL);if(t){h(`Using "${t}" as the Download-URL`);const e=new c.URL(t);return e.toString()}const r=yield this.getArchiveName();h(`Using "${r}" as the Archive String`);const n=(e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_MIRROR))!==null&&e!==void 0?e:"https://fastdl.mongodb.org";h(`Using "${n}" as the mirror`);const o=new c.URL(n);if(!o.pathname.endsWith("/")){o.pathname=o.pathname+"/"}o.pathname=`${o.pathname}${this.platform}/${r}`;return o.toString()}))}getArchiveName(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);if(!!e){return e}switch(this.platform){case"osx":return this.getArchiveNameOsx();case"win32":case"windows":return this.getArchiveNameWin();case"linux":return this.getArchiveNameLinux();default:throw new l.UnknownPlatformError(this.platform)}}))}getArchiveNameWin(){let e=`mongodb-${this.platform}-${this.arch}`;if(!(0,A.isNullOrUndefined)(a.coerce(this.version))){if(a.satisfies(this.version,"4.2.x")){e+="-2012plus"}else if(a.lt(this.version,"4.1.0")){e+="-2008plus-ssl"}}e+=`-${this.version}.zip`;return e}getArchiveNameOsx(){let e=`mongodb-osx`;const t=a.coerce(this.version);if(!(0,A.isNullOrUndefined)(t)&&a.gte(t,"3.2.0")){e+="-ssl"}if((0,A.isNullOrUndefined)(t)||a.gte(t,"4.2.0")){e=`mongodb-macos`}if(this.arch==="arm64"){h('getArchiveNameOsx: Arch is "arm64", using x64 binary');this.arch="x86_64"}e+=`-${this.arch}-${this.version}.tgz`;return e}getArchiveNameLinux(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){let e;if(this.arch!=="i686"){if(!this.os){this.os=yield(0,o.getOS)()}e=this.getLinuxOSVersionString(this.os)}let t=`mongodb-linux-${this.arch}`;if(!!e){t+=`-${e}`}t+=`-${this.version}.tgz`;return t}))}getLinuxOSVersionString(e){var t;if(regexHelper(/ubuntu/i,e)){return this.getUbuntuVersionString(e)}else if(regexHelper(/amzn/i,e)){return this.getAmazonVersionString(e)}else if(regexHelper(/suse/i,e)){return this.getSuseVersionString(e)}else if(regexHelper(/(rhel|centos|scientific)/i,e)){return this.getRhelVersionString(e)}else if(regexHelper(/fedora/i,e)){return this.getFedoraVersionString(e)}else if(regexHelper(/debian/i,e)){return this.getDebianVersionString(e)}else if(regexHelper(/alpine/i,e)){console.warn("There is no offical build of MongoDB for Alpine!")}else if(regexHelper(/(arch|manjaro|arco)(?:linux)?$/i,e)){console.warn(`There is no official build of MongoDB for ArchLinux (${e.dist}). Falling back to Ubuntu 20.04 release.`);return this.getUbuntuVersionString({os:"linux",dist:"Ubuntu Linux",release:"20.04"})}else if(regexHelper(/gentoo/i,e)){console.warn(`There is no official build of MongoDB for Gentoo (${e.dist}). Falling back to Debian.`);return this.getDebianVersionString({os:"linux",dist:"Debian",release:"11"})}else if(regexHelper(/unknown/i,e)){console.warn("Couldnt parse dist information, please report this to https://github.com/nodkz/mongodb-memory-server/issues")}console.warn(`Unknown/unsupported linux "${e.dist}(${(t=e.id_like)===null||t===void 0?void 0:t.join(", ")})". Falling back to legacy MongoDB build!`);return this.getLegacyVersionString()}getDebianVersionString(e){let t="debian";const r=parseFloat(e.release);if(r>=11||["unstable","testing"].includes(e.release)){if(a.lt(this.version,"5.0.8")){h("debian11 detected, but version below 5.0.8 requested, using debian10");t+="10"}else{t+="11"}}else if(r>=10){t+="10"}else if(r>=9){t+="92"}else if(r>=8.1){t+="81"}else if(r>=7.1){t+="71"}if(r>=10){if(a.lt(this.version,"4.2.1")){throw new l.KnownVersionIncompatibilityError(`Debian ${r}`,this.version,">=4.2.1","Mongodb does not provide binaries for versions before 4.2.1 for Debian 10+ and also cannot be mapped to a previous Debian release")}}return t}getFedoraVersionString(e){let t="rhel";const r=parseInt(e.release,10);if(r>=34){t+="80"}if(r<34&&r>=19){t+="70"}if(r<19&&r>=12){t+="62"}if(r<12&&r>=6){t+="55"}return t}getRhelVersionString(e){let t="rhel";const{release:r}=e;if(r){if(/^8/.test(r)){t+="80"}else if(/^7/.test(r)){t+="70"}else if(/^6/.test(r)){t+="62"}else if(/^5/.test(r)){t+="55"}}if(t==="rhel"){h('getRhelVersionString: falling back to "70"');t+="70"}return t}getAmazonVersionString(e){let t="amazon";const r=parseInt(e.release,10);if(r>=2&&r<=3){t+="2"}return t}getLegacyVersionString(){return""}getSuseVersionString(e){const t=e.release.match(/(^11|^12|^15)/);return t?`suse${t[0]}`:""}getUbuntuVersionString(e){let t=undefined;{if(/^linux\s?mint\s*$/i.test(e.dist)){const r={17:"14.04",18:"16.04",19:"18.04",20:"20.04"};t={os:"linux",dist:"ubuntu",release:r[parseInt(e.release.split(".")[0])]||r[20]}}if(/^elementary\s?os\s*$/i.test(e.dist)){const r={3:"14.04",4:"16.04",5:"18.04",6:"20.04"};const[n,o]=e.release.split(".").map((e=>parseInt(e)));const s=n||o;t={os:"linux",dist:"ubuntu",release:r[s]||r[6]}}}if((0,A.isNullOrUndefined)(t)){if(!/^ubuntu(?:| linux)\s*$/i.test(e.dist)){console.warn(`Unmapped distro "${e.dist}" with ID_LIKE "ubuntu", defaulting to highest ubuntu version!\n`+'This means that your distro does not have a internal mapping in MMS or does not have a upstream release file (like "/etc/upstream-release/lsb-release"), but has set a ID_LIKE');t={os:"linux",dist:"ubuntu",release:"20.04"}}else{t=e}}const r=parseInt(t.release.split(".")[0],10);if(this.arch==="arm64"){if(a.satisfies(this.version,"<4.1.10")){this.arch="arm64";return"ubuntu1604"}if(a.satisfies(this.version,">=4.1.10")){this.arch="aarch64";if(a.satisfies(this.version,"<4.4.0")){return"ubuntu1804"}return`ubuntu${r||18}04`}}if(t.release==="14.10"){return"ubuntu1410-clang"}if(r>=18&&a.satisfies(this.version,"3.x.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an 3.x.x version, defaulting to "1604"`);return"ubuntu1604"}if(r>18&&a.satisfies(this.version,"<=4.3.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an "<=4.3.x" version, defaulting to "1804"`);return"ubuntu1804"}if(r>=21){return"ubuntu2004"}return`ubuntu${r||14}04`}translatePlatform(e){switch(e){case"darwin":return"osx";case"win32":const t=a.coerce(this.version);if((0,A.isNullOrUndefined)(t)){return"windows"}return a.gte(t,"4.3.0")?"windows":"win32";case"linux":case"elementary OS":return"linux";case"sunos":return"sunos5";default:throw new l.UnknownPlatformError(e)}}static translateArch(e,t){switch(e){case"ia32":(0,u.deprecate)((()=>{}),"mongodb-memory-server will fully drop support for ia32 in 9.0","MMS001")();if(t==="linux"){return"i686"}else if(t==="win32"){return"i386"}throw new l.UnknownArchitectureError(e,t);case"x86_64":case"x64":return"x86_64";case"arm64":return"arm64";case"aarch64":return"aarch64";default:throw new l.UnknownArchitectureError(e)}}}t.MongoBinaryDownloadUrl=MongoBinaryDownloadUrl;t["default"]=MongoBinaryDownloadUrl;function regexHelper(e,t){return e.test(t.dist)||(!(0,A.isNullOrUndefined)(t.id_like)?t.id_like.filter((t=>e.test(t))).length>=1:false)}},843:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoInstance=t.MongoInstanceEvents=void 0;const n=r(4351);const o=r(2081);const s=(0,n.__importStar)(r(1017));const i=r(9125);const a=(0,n.__importDefault)(r(8237));const A=r(1978);const c=r(1383);const l=r(2361);const u=r(5517);const h=r(3386);if((0,c.lt)(process.version,"12.22.0")){console.warn("Using NodeJS below 12.22.0")}const d=(0,a.default)("MongoMS:MongoInstance");var g;(function(e){e["instanceReplState"]="instanceReplState";e["instancePrimary"]="instancePrimary";e["instanceReady"]="instanceReady";e["instanceSTDOUT"]="instanceSTDOUT";e["instanceSTDERR"]="instanceSTDERR";e["instanceClosed"]="instanceClosed";e["instanceRawError"]="instanceRawError";e["instanceError"]="instanceError";e["killerLaunched"]="killerLaunched";e["instanceLaunched"]="instanceLaunched";e["instanceStarted"]="instanceStarted"})(g=t.MongoInstanceEvents||(t.MongoInstanceEvents={}));class MongoInstance extends l.EventEmitter{constructor(e){super();this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;this.instanceOpts=Object.assign({},e.instance);this.binaryOpts=Object.assign({},e.binary);this.spawnOpts=Object.assign({},e.spawn);this.on(g.instanceReady,(()=>{this.isInstanceReady=true;this.debug("constructor: Instance is ready!")}));this.on(g.instanceError,(e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`constructor: Instance has thrown an Error: ${e.toString()}`);this.isInstanceReady=false;this.isInstancePrimary=false;yield this.stop()}))))}debug(e,...t){var r;const n=(r=this.instanceOpts.port)!==null&&r!==void 0?r:"unknown";d(`Mongo[${n}]: ${e}`,...t)}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("create: Called .create() method");const t=new this(e);yield t.start();return t}))}prepareCommandArgs(){var e;this.debug("prepareCommandArgs");(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.port),new Error('"instanceOpts.port" is required to be set!'));(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.dbPath),new Error('"instanceOpts.dbPath" is required to be set!'));const t=[];t.push("--port",this.instanceOpts.port.toString());t.push("--dbpath",this.instanceOpts.dbPath);if(!!this.instanceOpts.replSet){this.isReplSet=true;t.push("--replSet",this.instanceOpts.replSet)}if(!!this.instanceOpts.storageEngine){t.push("--storageEngine",this.instanceOpts.storageEngine)}if(!!this.instanceOpts.ip){t.push("--bind_ip",this.instanceOpts.ip)}if(this.instanceOpts.auth){t.push("--auth");if(this.isReplSet){(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.keyfileLocation),new h.KeyFileMissingError);t.push("--keyFile",this.instanceOpts.keyfileLocation)}}else{t.push("--noauth")}const r=t.concat((e=this.instanceOpts.args)!==null&&e!==void 0?e:[]);this.debug("prepareCommandArgs: final argument array:"+JSON.stringify(r));return r}start(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start");this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;const e=new Promise(((e,t)=>{this.once(g.instanceReady,e);this.once(g.instanceError,t);this.once(g.instanceClosed,(()=>{t(new Error("Instance Exited before being ready and without throwing an error!"))}))}));const t=yield i.MongoBinary.getPath(this.binaryOpts);yield(0,A.checkBinaryPermissions)(t);this.debug("start: Starting Processes");this.mongodProcess=this._launchMongod(t);(0,A.assertion)(!(0,A.isNullOrUndefined)(this.mongodProcess.pid),new Error("MongoD Process failed to spawn"));this.killerProcess=this._launchKiller(process.pid,this.mongodProcess.pid);yield e;this.emit(g.instanceStarted);this.debug("start: Processes Started")}))}stop(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop");if(!this.mongodProcess&&!this.killerProcess){this.debug("stop: nothing to shutdown, returning");return false}if(!(0,A.isNullOrUndefined)(this.mongodProcess)){if(this.isReplSet){let e;try{this.debug("stop: trying shutdownServer");const t=this.instanceOpts.port;const r=this.instanceOpts.ip;(0,A.assertion)(!(0,A.isNullOrUndefined)(t),new Error('Cannot shutdown replset gracefully, no "port" is provided'));(0,A.assertion)(!(0,A.isNullOrUndefined)(r),new Error('Cannot shutdown replset gracefully, no "ip" is provided'));e=yield u.MongoClient.connect((0,A.uriTemplate)(r,t,"admin"),Object.assign(Object.assign({},this.extraConnectionOptions),{directConnection:true}));const n=e.db("admin");yield n.command({shutdown:1,force:true,timeoutSecs:1});this.debug("stop: after admin shutdown command")}catch(e){if(!(e instanceof u.MongoNetworkError&&/^connection \d+ to [\d.]+:\d+ closed$/i.test(e.message))){console.warn(e)}}finally{if(!(0,A.isNullOrUndefined)(e)){yield e.close()}}}yield(0,A.killProcess)(this.mongodProcess,"mongodProcess",this.instanceOpts.port);this.mongodProcess=undefined}else{this.debug("stop: mongodProcess: nothing to shutdown, skipping")}if(!(0,A.isNullOrUndefined)(this.killerProcess)){yield(0,A.killProcess)(this.killerProcess,"killerProcess",this.instanceOpts.port);this.killerProcess=undefined}else{this.debug("stop: killerProcess: nothing to shutdown, skipping")}this.debug("stop: Instance Finished Shutdown");return true}))}_launchMongod(e){var t,r;this.debug("_launchMongod: Launching Mongod Process");const n=(0,o.spawn)(s.resolve(e),this.prepareCommandArgs(),Object.assign(Object.assign({},this.spawnOpts),{stdio:"pipe"}));(t=n.stderr)===null||t===void 0?void 0:t.on("data",this.stderrHandler.bind(this));(r=n.stdout)===null||r===void 0?void 0:r.on("data",this.stdoutHandler.bind(this));n.on("close",this.closeHandler.bind(this));n.on("error",this.errorHandler.bind(this));if((0,A.isNullOrUndefined)(n.pid)){throw new h.StartBinaryFailedError(s.resolve(e))}this.emit(g.instanceLaunched);return n}_launchKiller(e,t){this.debug(`_launchKiller: Launching Killer Process (parent: ${e}, child: ${t})`);const r=(0,o.fork)(s.resolve(__dirname,"../../scripts/mongo_killer.js"),[e.toString(),t.toString()],{detached:true,stdio:"ignore"});r.unref();this.emit(g.killerLaunched);return r}errorHandler(e){this.emit(g.instanceRawError,e);this.emit(g.instanceError,e)}closeHandler(e,t){if(process.platform==="win32"&&e!=12&&e!=0||e!=0){this.debug("closeHandler: Mongod instance closed with an non-0 (or non 12 on windows) code!")}this.debug(`closeHandler: "${e}" "${t}"`);this.emit(g.instanceClosed,e,t)}stderrHandler(e){const t=e.toString().trim();this.debug(`stderrHandler: ""${t}""`);this.emit(g.instanceSTDERR,t);this.checkErrorInLine(t)}stdoutHandler(e){var t,r;const n=e.toString().trim();this.debug(`stdoutHandler: ""${n}""`);this.emit(g.instanceSTDOUT,n);if(/waiting for connections/i.test(n)){this.emit(g.instanceReady)}this.checkErrorInLine(n);if(/transition to \w+ from \w+/i.test(n)){const e=(r=(t=/transition to (\w+) from \w+/i.exec(n))===null||t===void 0?void 0:t[1])!==null&&r!==void 0?r:"UNKNOWN";this.emit(g.instanceReplState,e);if(e!=="PRIMARY"){this.isInstancePrimary=false}}if(/transition to primary complete; database writes are now permitted/i.test(n)){this.isInstancePrimary=true;this.debug('stdoutHandler: emitting "instancePrimary"');this.emit(g.instancePrimary)}}checkErrorInLine(e){var t,r;if(/address already in use/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError(`Port "${this.instanceOpts.port}" already in use`))}if(/exception in initAndListen: \w+[^:]: .+[^,], terminating/i.test(e)){const t=/exception in initAndListen: (\w+[^:]): (.+[^,]), terminating/i.exec(e);const{1:r,2:n}=t||[];this.emit(g.instanceError,new h.StdoutInstanceError(`Instance Failed to start with "${r}". Original Error:\n`+n))}if(/CURL_OPENSSL_3['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You should manually install libcurl3 or try to use an newer version of MongoDB"))}if(/CURL_OPENSSL_4['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl4 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You need to manually install libcurl4"))}if(/lib[^:]+(?=: cannot open shared object)/i.test(e)){const n=(r=(t=e.match(/(lib[^:]+)(?=: cannot open shared object)/i))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown";this.emit(g.instanceError,new h.StdoutInstanceError(`Instance failed to start because a library is missing or cannot be opened: "${n}"`))}if(/\*\*\*aborting after/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("Mongod internal error"))}}}t.MongoInstance=MongoInstance;t["default"]=MongoInstance},3386:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.StdoutInstanceError=t.KnownVersionIncompatibilityError=t.NoRegexMatchError=t.ParseArchiveRegexError=t.ReplsetCountLowError=t.AssertionFallbackError=t.BinaryNotFoundError=t.InsufficientPermissionsError=t.AuthNotObjectError=t.KeyFileMissingError=t.InstanceInfoError=t.StartBinaryFailedError=t.Md5CheckFailedError=t.NoSystemBinaryFoundError=t.EnsureInstanceError=t.WaitForPrimaryTimeoutError=t.UnknownArchitectureError=t.UnknownPlatformError=t.UnableToUnlockLockfileError=t.UnknownLockfileStatusError=t.StateError=void 0;const n=r(1978);class StateError extends Error{constructor(e,t){super(`Incorrect State for operation: "${t}", allowed States: "[${e.join(",")}]"\n`+"This may be because of using a v6.x way of calling functions, look at the following guide if anything applies:\n"+"https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7#no-function-other-than-start-create-ensureinstance-will-be-starting-anything");this.wantedStates=e;this.gotState=t}}t.StateError=StateError;class UnknownLockfileStatusError extends Error{constructor(e){super(`Unknown LockFile Status: "${e}"`);this.status=e}}t.UnknownLockfileStatusError=UnknownLockfileStatusError;class UnableToUnlockLockfileError extends Error{constructor(e,t){super(`Cannot unlock file "${t}", because it is not locked by this ${e?"instance":"process"}`);this.thisInstance=e;this.file=t}}t.UnableToUnlockLockfileError=UnableToUnlockLockfileError;class UnknownPlatformError extends Error{constructor(e){super(`Unknown Platform: "${e}"`);this.platform=e}}t.UnknownPlatformError=UnknownPlatformError;class UnknownArchitectureError extends Error{constructor(e,t){super();this.arch=e;this.platform=t;if(!(0,n.isNullOrUndefined)(t)){this.message=`Unsupported Architecture-Platform combination: arch: "${e}", platform: "${t}"`}else{this.message=`Unsupported Architecture: "${e}"`}}}t.UnknownArchitectureError=UnknownArchitectureError;class WaitForPrimaryTimeoutError extends Error{constructor(e,t){super(`Timed out after ${e}ms while waiting for a Primary (where: "${t}")`);this.timeout=e;this.where=t}}t.WaitForPrimaryTimeoutError=WaitForPrimaryTimeoutError;class EnsureInstanceError extends Error{constructor(e){super();this.isRunning=e;const t='"ensureInstance" failed, because';if(e){this.message=`${t} state was "running" but "instanceInfo" was undefined!`}else{this.message=`${t} "instanceInfo" was undefined after running "start"`}}}t.EnsureInstanceError=EnsureInstanceError;class NoSystemBinaryFoundError extends Error{constructor(e){super(`Config option "SYSTEM_BINARY" was provided with value "${e}", but no binary could be found!`);this.binaryPath=e}}t.NoSystemBinaryFoundError=NoSystemBinaryFoundError;class Md5CheckFailedError extends Error{constructor(e,t){super(`MD5 check failed! Binary MD5 is "${e}", Checkfile MD5 is "${t}"`);this.binarymd5=e;this.checkfilemd5=t}}t.Md5CheckFailedError=Md5CheckFailedError;class StartBinaryFailedError extends Error{constructor(e){super(`Starting the Binary Failed (PID is undefined)! Binary: "${e}"`);this.binary=e}}t.StartBinaryFailedError=StartBinaryFailedError;class InstanceInfoError extends Error{constructor(e){super(`"instanceInfo" was undefined when expected to be defined! (where: "${e}")`);this.where=e}}t.InstanceInfoError=InstanceInfoError;class KeyFileMissingError extends Error{constructor(){super(`"keyfileLocation" was undefined when expected!`)}}t.KeyFileMissingError=KeyFileMissingError;class AuthNotObjectError extends Error{constructor(){super('"auth" was not a object when it was expected!')}}t.AuthNotObjectError=AuthNotObjectError;class InsufficientPermissionsError extends Error{constructor(e){super(`File "${e}" does not have the required Permissions, required Permissions: "--x"`);this.path=e}}t.InsufficientPermissionsError=InsufficientPermissionsError;class BinaryNotFoundError extends Error{constructor(e){super(`No Binary at path "${e}" was found! (ENOENT)`);this.path=e}}t.BinaryNotFoundError=BinaryNotFoundError;class AssertionFallbackError extends Error{constructor(){super("Assert failed - no custom error")}}t.AssertionFallbackError=AssertionFallbackError;class ReplsetCountLowError extends Error{constructor(e){super(`ReplSet Count needs to be 1 or higher! (specified count: "${e}")`);this.count=e}}t.ReplsetCountLowError=ReplsetCountLowError;class ParseArchiveRegexError extends Error{constructor(e){super(`Expected "${e}" to be found in regex groups`);this.key=e}}t.ParseArchiveRegexError=ParseArchiveRegexError;class NoRegexMatchError extends Error{constructor(e,t){super();this.name=e;this.extra=t;const r=!!t?`(${t})`:"";this.message=`Expected "${e}" to have Regex Matches${r}`}}t.NoRegexMatchError=NoRegexMatchError;class KnownVersionIncompatibilityError extends Error{constructor(e,t,r,n){super();this.dist=e;this.requested_version=t;this.available_versions=r;this.extra=n;const o=!!n?`\n${n}`:"";this.message=`Requested Version "${t}" is not available for "${e}"! Available Versions: "${r}"${o}`}}t.KnownVersionIncompatibilityError=KnownVersionIncompatibilityError;class StdoutInstanceError extends Error{constructor(e){super(e)}}t.StdoutInstanceError=StdoutInstanceError},8278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.parseOS=t.parseLSB=t.getOS=t.isLinuxOS=void 0;const n=r(4351);const o=r(2037);const s=(0,n.__importDefault)(r(8237));const i=r(1978);const a=(0,s.default)("MongoMS:getos");const A={name:/^(?:distributor id:|DISTRIB_ID=)\s*(.*)$/im,codename:/^(?:codename:|DISTRIB_CODENAME=)\s*(.*)$/im,release:/^(?:release:|DISTRIB_RELEASE=)\s*(.*)$/im};const c={name:/^id\s*=\s*"?(\w*)"?$/im,codename:/^version_codename\s*=\s*(.*)$/im,release:/^version_id\s*=\s*"?(\d*(?:\.\d*)?)"?$/im,id_like:/^id_like\s*=\s*"?([\w\s]*)"?$/im};function isLinuxOS(e){return e.os==="linux"}t.isLinuxOS=isLinuxOS;let l;function getOS(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!l){const e=(0,o.platform)();if(e==="linux"){l=yield getLinuxInformation()}else{l={os:e}}}return l}))}t.getOS=getOS;function getLinuxInformation(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield(0,i.tryReleaseFile)("/etc/upstream-release/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(e)){a("getLinuxInformation: Using UpstreamLSB");return e}const t=yield(0,i.tryReleaseFile)("/etc/os-release",parseOS);if(!(0,i.isNullOrUndefined)(t)){a("getLinuxInformation: Using etcOsRelease");return t}const r=yield(0,i.tryReleaseFile)("/usr/lib/os-release",parseOS);if(!(0,i.isNullOrUndefined)(r)){a("getLinuxInformation: Using usrOsRelease");return r}const n=yield(0,i.tryReleaseFile)("/etc/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(n)){a("getLinuxInformation: Using etcLSBRelease");return n}console.warn("Could not find any Release File, using fallback binary");return{os:"linux",dist:"unknown",release:""}}))}function parseLSB(e){var t,r,n,o,s;return{os:"linux",dist:(r=(t=e.match(A.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(A.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(A.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:""}}t.parseLSB=parseLSB;function parseOS(e){var t,r,n,o,s,i;return{os:"linux",dist:(r=(t=e.match(c.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(c.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(c.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:"",id_like:(i=e.match(c.id_like))===null||i===void 0?void 0:i[1].toLocaleLowerCase().split(" ")}}t.parseOS=parseOS},4908:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.LockFile=t.LockFileEvents=t.LockFileStatus=void 0;const n=r(4351);const o=r(2361);const s=(0,n.__importStar)(r(1978));const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(4038);const l=r(5840);const u=r(3386);const h=(0,i.default)("MongoMS:LockFile");class RepeatError extends Error{constructor(e){super();this.repeat=e}}var d;(function(e){e[e["available"]=0]="available";e[e["availableInstance"]=1]="availableInstance";e[e["lockedSelf"]=2]="lockedSelf";e[e["lockedDifferent"]=3]="lockedDifferent"})(d=t.LockFileStatus||(t.LockFileStatus={}));var g;(function(e){e["lock"]="lock";e["unlock"]="unlock"})(g=t.LockFileEvents||(t.LockFileEvents={}));class LockFileEventsClass extends o.EventEmitter{}class LockFile{constructor(e,t){this.file=e;this.uuid=t}static lock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`lock: Locking file "${e}"`);const t=a.resolve(e.trim());s.assertion(t.length>0,new Error("Provided Path for lock file is length of 0"));const r=yield this.checkLock(t);switch(r){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(t);case d.available:return this.createLock(t);default:throw new u.UnknownLockfileStatusError(r)}}))}static checkLock(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`checkLock: for file "${e}" with uuid: "${t}"`);if(!(yield s.pathExists(e))){return d.available}try{const r=(yield A.promises.readFile(e)).toString().trim().split(" ");const n=parseInt(r[0]);if(n===process.pid){h(`checkLock: Lock File Already exists, and is for *this* process, with uuid: "${r[1]}"`);if(!this.files.has(e)){return d.available}if(!s.isNullOrUndefined(t)){return t===r[1]?d.availableInstance:d.lockedSelf}return d.lockedSelf}h(`checkLock: Lock File Aready exists, for a different process: "${n}"`);return s.isAlive(n)?d.lockedDifferent:d.available}catch(e){if(s.errorWithCode(e)&&e.code==="ENOENT"){h("checkLock: reading file failed with ENOENT");return d.available}throw e}}))}static waitForLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`waitForLock: Starting to wait for file "${e}"`);let t=undefined;let r=undefined;yield new Promise((o=>{r=t=>{if(t===e){o()}};t=setInterval((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.checkLock(e);h(`waitForLock: Interval for file "${e}" with status "${t}"`);if(t===d.available){o()}}))),1e3*3);this.events.on(g.unlock,r)}));if(t){clearInterval(t)}if(r){this.events.removeListener(g.unlock,r)}h(`waitForLock: File became available "${e}"`);yield s.ensureAsync();const o=yield this.checkLock(e);h(`waitForLock: Lock File Status reassessment for file "${e}": ${o}`);switch(o){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(e);case d.available:return this.createLock(e);default:throw new u.UnknownLockfileStatusError(o)}}))}static createLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`createLock: trying to create a lock file for "${e}"`);const t=(0,l.v4)();try{yield this.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(this.files.has(e)){h(`createLock: Map already has file "${e}"`);throw new RepeatError(true)}yield s.mkdir(a.dirname(e));yield A.promises.writeFile(e,`${process.pid.toString()} ${t}`);this.files.add(e);this.events.emit(g.lock,e)}))))}catch(t){if(t instanceof RepeatError&&t.repeat){return this.waitForLock(e)}}h(`createLock: Lock File Created for file "${e}"`);return new this(e,t)}))}unlock(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`unlock: Unlocking file "${this.file}"`);if(s.isNullOrUndefined(this.file)||((e=this.file)===null||e===void 0?void 0:e.length)<=0){h("unlock: invalid file, returning");return}switch(yield LockFile.checkLock(this.file,this.uuid)){case d.available:h(`unlock: Lock Status was already "available" for file "${this.file}"`);yield this.unlockCleanup(false);return;case d.availableInstance:h(`unlock: Lock Status was "availableInstance" for file "${this.file}"`);yield this.unlockCleanup(true);return;case d.lockedSelf:throw new u.UnableToUnlockLockfileError(true,this.file);default:throw new u.UnableToUnlockLockfileError(false,this.file)}}))}unlockCleanup(e=true){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return yield LockFile.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`unlockCleanup: for file "${this.file}"`);if(s.isNullOrUndefined(this.file)){return}if(e){yield A.promises.unlink(this.file).catch((e=>{h(`unlockCleanup: lock file unlink failed: "${e}"`)}))}LockFile.files.delete(this.file);LockFile.events.emit(g.unlock,this.file);this.file=undefined;this.uuid=undefined}))))}))}}t.LockFile=LockFile;LockFile.files=new Set;LockFile.events=new LockFileEventsClass;LockFile.mutex=new c.Mutex},8730:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.envToBool=t.envName=t.resolveConfig=t.processConfigOption=t.findPackageJson=t.setDefaultValue=t.defaultValues=t.DEFAULT_VERSION=t.ENV_CONFIG_PREFIX=t.ResolveConfigVariables=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(1362));const s=r(1156);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(1978);const l=(0,i.default)("MongoMS:ResolveConfig");var u;(function(e){e["DOWNLOAD_DIR"]="DOWNLOAD_DIR";e["PLATFORM"]="PLATFORM";e["ARCH"]="ARCH";e["VERSION"]="VERSION";e["DEBUG"]="DEBUG";e["DOWNLOAD_MIRROR"]="DOWNLOAD_MIRROR";e["DOWNLOAD_URL"]="DOWNLOAD_URL";e["PREFER_GLOBAL_PATH"]="PREFER_GLOBAL_PATH";e["DISABLE_POSTINSTALL"]="DISABLE_POSTINSTALL";e["SYSTEM_BINARY"]="SYSTEM_BINARY";e["MD5_CHECK"]="MD5_CHECK";e["ARCHIVE_NAME"]="ARCHIVE_NAME";e["RUNTIME_DOWNLOAD"]="RUNTIME_DOWNLOAD";e["USE_HTTP"]="USE_HTTP";e["SYSTEM_BINARY_VERSION_CHECK"]="SYSTEM_BINARY_VERSION_CHECK";e["USE_ARCHIVE_NAME_FOR_BINARY_NAME"]="USE_ARCHIVE_NAME_FOR_BINARY_NAME"})(u=t.ResolveConfigVariables||(t.ResolveConfigVariables={}));t.ENV_CONFIG_PREFIX="MONGOMS_";t.DEFAULT_VERSION="5.0.8";t.defaultValues=new Map([[u.VERSION,t.DEFAULT_VERSION],[u.PREFER_GLOBAL_PATH,"true"],[u.RUNTIME_DOWNLOAD,"true"],[u.USE_HTTP,"false"],[u.SYSTEM_BINARY_VERSION_CHECK,"true"],[u.USE_ARCHIVE_NAME_FOR_BINARY_NAME,"false"]]);function setDefaultValue(e,r){t.defaultValues.set(e,r)}t.setDefaultValue=setDefaultValue;let h=undefined;function findPackageJson(e){var t;for(const r of(0,s.findSync)(e||process.cwd())){l(`findPackageJson: Found package.json at "${r}"`);const e=JSON.parse((0,A.readFileSync)(r).toString());const n=(t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.mongodbMemoryServer;if(!(0,c.isNullOrUndefined)(n)&&Object.keys(n!==null&&n!==void 0?n:{}).length>0){l(`findPackageJson: Found package with non-empty config field at "${r}"`);const e=a.dirname(r);h={filePath:e,config:processConfigOption(n,e)};break}}return h}t.findPackageJson=findPackageJson;function processConfigOption(e,t){l("processConfigOption",e,t);if(typeof e!=="object"){l("processConfigOptions: input was not a object");return{}}const r=e;const n=(0,o.default)(u.DOWNLOAD_DIR);const s=(0,o.default)(u.SYSTEM_BINARY);if(n in r){r[n]=a.resolve(t,r[n])}if(s in r){r[s]=a.resolve(t,r[s])}return r}t.processConfigOption=processConfigOption;function resolveConfig(e){var r,n,s;return(s=(n=(r=process.env[envName(e)])!==null&&r!==void 0?r:h===null||h===void 0?void 0:h.config[(0,o.default)(e)])!==null&&n!==void 0?n:t.defaultValues.get(e))===null||s===void 0?void 0:s.toString()}t.resolveConfig=resolveConfig;t["default"]=resolveConfig;function envName(e){return`${t.ENV_CONFIG_PREFIX}${e}`}t.envName=envName;function envToBool(e=""){if(typeof e!=="string"){l("envToBool: input was not a string!");return false}return["1","on","yes","true"].indexOf(e.toLowerCase())!==-1}t.envToBool=envToBool;if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through Environment Variable")}findPackageJson();if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through package.json")}},1978:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mkdir=t.checkBinaryPermissions=t.ManagerAdvanced=t.ManagerBase=t.tryReleaseFile=t.pathExists=t.statPath=t.authDefault=t.ensureAsync=t.isAlive=t.killProcess=t.assertion=t.isNullOrUndefined=t.uriTemplate=t.getHost=t.generateDbName=t.errorWithCode=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(7147);const i=r(3386);const a=(0,o.default)("MongoMS:utils");function errorWithCode(e){return e instanceof Error&&"code"in e}t.errorWithCode=errorWithCode;function generateDbName(e){return e||""}t.generateDbName=generateDbName;function getHost(e){return e.replace(/(?:^mongodb:\/{2})|(?:\/.*$)|(?:.*@)/gim,"")}t.getHost=getHost;function uriTemplate(e,t,r,n){const o=!isNullOrUndefined(t)?`${e}:${t}`:e;return`mongodb://${o}/${r}`+(!isNullOrUndefined(n)?`?${n.join("&")}`:"")}t.uriTemplate=uriTemplate;function isNullOrUndefined(e){return e===null||e===undefined}t.isNullOrUndefined=isNullOrUndefined;function assertion(e,t){if(!e){throw t!==null&&t!==void 0?t:new i.AssertionFallbackError}}t.assertion=assertion;function killProcess(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){function ilog(e){a(`Mongo[${r||"unknown"}] killProcess: ${e}`)}if(!isAlive(e.pid)){ilog("given childProcess's PID was not alive anymore");return}const n=1e3*10;yield new Promise(((r,s)=>{let i=setTimeout((()=>{ilog("killProcess: timeout triggered, trying SIGKILL");if(!o.default.enabled("MongoMS:utils")){console.warn('An Process didnt exit with signal "SIGINT" within 10 seconds, using "SIGKILL"!\n'+"Enable debug logs for more information")}e.kill("SIGKILL");i=setTimeout((()=>{ilog("killProcess: timeout triggered again, rejecting");s(new Error(`Process "${t}" didnt exit, enable debug for more information.`))}),n)}),n);e.once(`exit`,((e,n)=>{ilog(`killProcess: ${t}: got exit signal, Code: ${e}, Signal: ${n}`);clearTimeout(i);r()}));ilog(`killProcess: ${t}: sending "SIGINT"`);e.kill("SIGINT")}))}))}t.killProcess=killProcess;function isAlive(e){if(isNullOrUndefined(e)){return false}try{process.kill(e,0);return true}catch(e){return false}}t.isAlive=isAlive;function ensureAsync(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return new Promise((e=>process.nextTick(e)))}))}t.ensureAsync=ensureAsync;function authDefault(e){return Object.assign({force:false,disable:false,customRootName:"mongodb-memory-server-root",customRootPwd:"rootuser",extraUsers:[],keyfileContent:"0123456789"},e)}t.authDefault=authDefault;function statPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(["ENOENT","EACCES"].includes(e.code)){return undefined}throw e}))}))}t.statPath=statPath;function pathExists(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return!isNullOrUndefined(yield statPath(e))}))}t.pathExists=pathExists;function tryReleaseFile(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{const r=yield s.promises.readFile(e);return t(r.toString())}catch(t){if(errorWithCode(t)&&!["ENOENT","EACCES"].includes(t.code)){throw t}a(`tryReleaseFile: "${e}" does not exist`);return undefined}}))}t.tryReleaseFile=tryReleaseFile;class ManagerBase{}t.ManagerBase=ManagerBase;class ManagerAdvanced extends ManagerBase{}t.ManagerAdvanced=ManagerAdvanced;function checkBinaryPermissions(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{yield s.promises.access(e,s.constants.X_OK)}catch(t){if(errorWithCode(t)){if(t.code==="EACCES"){throw new i.InsufficientPermissionsError(e)}if(t.code==="ENOENT"){throw new i.BinaryNotFoundError(e)}}throw t}}))}t.checkBinaryPermissions=checkBinaryPermissions;function mkdir(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.promises.mkdir(e,{recursive:true})}))}t.mkdir=mkdir},5517:(e,t,r)=>{"use strict";const n=r(3994);const o=r(2138);const s=r(1545).connect;s.MongoError=n.MongoError;s.MongoNetworkError=n.MongoNetworkError;s.MongoTimeoutError=n.MongoTimeoutError;s.MongoServerSelectionError=n.MongoServerSelectionError;s.MongoParseError=n.MongoParseError;s.MongoWriteConcernError=n.MongoWriteConcernError;s.MongoBulkWriteError=r(4239).BulkWriteError;s.BulkWriteError=s.MongoBulkWriteError;s.ServerApiVersion=n.ServerApiVersion;s.Admin=r(3238);s.MongoClient=r(1545);s.Db=r(6662);s.Collection=r(5193);s.Server=r(8421);s.ReplSet=r(382);s.Mongos=r(2048);s.ReadPreference=n.ReadPreference;s.GridStore=r(9406);s.Chunk=r(3890);s.Logger=n.Logger;s.AggregationCursor=r(7429);s.CommandCursor=r(538);s.Cursor=r(7159);s.GridFSBucket=r(2573);s.CoreServer=n.Server;s.CoreConnection=n.Connection;s.Binary=n.BSON.Binary;s.Code=n.BSON.Code;s.Map=n.BSON.Map;s.DBRef=n.BSON.DBRef;s.Double=n.BSON.Double;s.Int32=n.BSON.Int32;s.Long=n.BSON.Long;s.MinKey=n.BSON.MinKey;s.MaxKey=n.BSON.MaxKey;s.ObjectID=n.BSON.ObjectID;s.ObjectId=n.BSON.ObjectID;s.Symbol=n.BSON.Symbol;s.Timestamp=n.BSON.Timestamp;s.BSONRegExp=n.BSON.BSONRegExp;s.Decimal128=n.BSON.Decimal128;s.connect=s;s.instrument=function(e,t){if(typeof e==="function"){t=e;e={}}const r=new o;r.instrument(s.MongoClient,t);return r};e.exports=s},3238:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(7057);const s=r(1681);const i=r(1969);const a=r(9263);const A=r(9929);const c=r(2548);function Admin(e,t,r){if(!(this instanceof Admin))return new Admin(e,t);this.s={db:e,topology:t,promiseLibrary:r}}Admin.prototype.command=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():{};const o=new s(this.s.db,e,t);return c(this.s.db.s.topology,o,r)};Admin.prototype.buildInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{serverStatus:1},e);return c(this.s.db.s.topology,r,t)};Admin.prototype.ping=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={ping:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.addUser=function(e,t,r,s){const i=Array.prototype.slice.call(arguments,2);s=typeof i[i.length-1]==="function"?i.pop():undefined;if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}r=i.length?i.shift():{};r=Object.assign({},r);r=n(r,{db:this.s.db});r.dbName="admin";const a=new o(this.s.db,e,t,r);return c(this.s.db.s.topology,a,s)};Admin.prototype.removeUser=function(e,t,r){const o=Array.prototype.slice.call(arguments,1);r=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():{};t=Object.assign({},t);t=n(t,{db:this.s.db});t.dbName="admin";const s=new i(this.s.db,e,t);return c(this.s.db.s.topology,s,r)};Admin.prototype.validateCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new a(this,e,t);return c(this.s.db.s.topology,n,r)};Admin.prototype.listDatabases=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return c(this.s.db.s.topology,new A(this.s.db,e),t)};Admin.prototype.replSetGetStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{replSetGetStatus:1},e);return c(this.s.db.s.topology,r,t)};e.exports=Admin},7429:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(7159);const s=r(4847).CursorState;class AggregationCursor extends o{constructor(e,t,r){super(e,t,r)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead()){throw n.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw n.create({message:"batchSize requires an integer",driver:true})}this.operation.options.batchSize=e;this.setCursorBatchSize(e);return this}geoNear(e){this.operation.addToPipeline({$geoNear:e});return this}group(e){this.operation.addToPipeline({$group:e});return this}limit(e){this.operation.addToPipeline({$limit:e});return this}match(e){this.operation.addToPipeline({$match:e});return this}maxTimeMS(e){this.operation.options.maxTimeMS=e;return this}out(e){this.operation.addToPipeline({$out:e});return this}project(e){this.operation.addToPipeline({$project:e});return this}lookup(e){this.operation.addToPipeline({$lookup:e});return this}redact(e){this.operation.addToPipeline({$redact:e});return this}skip(e){this.operation.addToPipeline({$skip:e});return this}sort(e){this.operation.addToPipeline({$sort:e});return this}unwind(e){this.operation.addToPipeline({$unwind:e});return this}getLogger(){return this.logger}}AggregationCursor.prototype.get=AggregationCursor.prototype.toArray;e.exports=AggregationCursor},2138:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;class Instrumentation extends n{constructor(){super()}instrument(e,t){this.$MongoClient=e;const r=this.$prototypeConnect=e.prototype.connect;const n=this;e.prototype.connect=function(e){this.s.options.monitorCommands=true;this.on("commandStarted",(e=>n.emit("started",e)));this.on("commandSucceeded",(e=>n.emit("succeeded",e)));this.on("commandFailed",(e=>n.emit("failed",e)));return r.call(this,e)};if(typeof t==="function")t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}e.exports=Instrumentation},1749:(e,t)=>{"use strict";function asyncIterator(){const e=this;return{next:function(){return Promise.resolve().then((()=>e.next())).then((t=>{if(!t){return e.close().then((()=>({value:t,done:true})))}return{value:t,done:false}}))}}}t.asyncIterator=asyncIterator},4239:(e,t,r)=>{"use strict";const n=r(3994).BSON.Long;const o=r(3994).MongoError;const s=r(3994).BSON.ObjectID;const i=r(3994).BSON;const a=r(3994).MongoWriteConcernError;const A=r(1371).emitWarningOnce;const c=r(1371).toError;const l=r(1371).handleCallback;const u=r(1371).applyRetryableWrites;const h=r(1371).applyWriteConcern;const d=r(1371).executeLegacyOperation;const g=r(1371).isPromiseLike;const p=r(1371).hasAtomicOperators;const E=r(1178).maxWireVersion;const m=64;const C=1;const I=2;const y=3;const B=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 Batch{constructor(e,t){this.originalZeroIndex=t;this.currentIndex=0;this.originalIndexes=[];this.batchType=e;this.operations=[];this.size=0;this.sizeBytes=0}}const Q=Symbol("upsertedIds");const b=Symbol("insertedIds");class BulkWriteResult{constructor(e){this.result=e;this[Q]=undefined;this[b]=undefined}get insertedCount(){return typeof this.result.nInserted!=="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!=="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!=="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!=="number"?0:this.result.nRemoved}get upsertedCount(){return!this.result.upserted?0:this.result.upserted.length}get upsertedIds(){if(this[Q]){return this[Q]}this[Q]={};for(const e of this.result.upserted||[]){this[Q][e.index]=e._id}return this[Q]}get insertedIds(){if(this[b]){return this[b]}this[b]={};for(const e of this.result.insertedIds||[]){this[b][e.index]=e._id}return this[b]}get n(){return this.result.insertedCount}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){if(ee.multi))}if(e.batch.batchType===y){r.retryWrites=r.retryWrites&&!e.batch.operations.some((e=>e.limit===0))}}try{if(e.batch.batchType===C){this.s.topology.insert(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===I){this.s.topology.update(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===y){this.s.topology.remove(this.s.namespace,e.batch.operations,r,e.resultHandler)}}catch(r){r.ok=0;l(t,null,mergeBatchResults(e.batch,this.s.bulkResult,r,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const r=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";l(e,new BulkWriteError(c({message:r,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null);return true}if(t.getWriteConcernError()){l(e,new BulkWriteError(c(t.getWriteConcernError()),t),null);return true}}}Object.defineProperty(BulkOperationBase.prototype,"length",{enumerable:true,get:function(){return this.s.currentIndex}});e.exports={Batch:Batch,BulkOperationBase:BulkOperationBase,mergeBatchResults:mergeBatchResults,bson:B,INSERT:C,UPDATE:I,REMOVE:y,BulkWriteError:BulkWriteError,BulkWriteResult:BulkWriteResult}},5035:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);const a=e.s.maxKeySize;if(e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+a+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}if(t===n.INSERT){e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id})}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentBatch.operations.push(r);e.s.currentBatchSize+=1;e.s.currentBatchSizeBytes+=a+o;e.s.currentIndex+=1;return e}class OrderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,true)}}function initializeOrderedBulkOp(e,t,r){return new OrderedBulkOperation(e,t,r)}initializeOrderedBulkOp.OrderedBulkOperation=OrderedBulkOperation;e.exports=initializeOrderedBulkOp;e.exports.Bulk=OrderedBulkOperation},325:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null;if(t===n.INSERT){e.s.currentBatch=e.s.currentInsertBatch}else if(t===n.UPDATE){e.s.currentBatch=e.s.currentUpdateBatch}else if(t===n.REMOVE){e.s.currentBatch=e.s.currentRemoveBatch}const a=e.s.maxKeySize;if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);if(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+a+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)}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.operations.push(r);e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentIndex=e.s.currentIndex+1;if(t===n.INSERT){e.s.currentInsertBatch=e.s.currentBatch;e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})}else if(t===n.UPDATE){e.s.currentUpdateBatch=e.s.currentBatch}else if(t===n.REMOVE){e.s.currentRemoveBatch=e.s.currentBatch}e.s.currentBatch.size+=1;e.s.currentBatch.sizeBytes+=a+o;return e}class UnorderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,false)}handleWriteError(e,t){if(this.s.batches.length){return false}return super.handleWriteError(e,t)}}function initializeUnorderedBulkOp(e,t,r){return new UnorderedBulkOperation(e,t,r)}initializeUnorderedBulkOp.UnorderedBulkOperation=UnorderedBulkOperation;e.exports=initializeUnorderedBulkOp;e.exports.Bulk=UnorderedBulkOperation},1117:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(9386).isResumableError;const i=r(3994).MongoError;const a=r(7159);const A=r(1178).relayEvents;const c=r(1178).maxWireVersion;const l=r(1371).maybePromise;const u=r(1371).now;const h=r(1371).calculateDurationInMs;const d=r(1554);const g=Symbol("resumeQueue");const p=["resumeAfter","startAfter","startAtOperationTime","fullDocument"];const E=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(p);const m={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class ChangeStream extends o{constructor(e,t,o){super();const s=r(5193);const i=r(6662);const a=r(1545);this.pipeline=t||[];this.options=o||{};this.parent=e;this.namespace=e.s.namespace;if(e instanceof s){this.type=m.COLLECTION;this.topology=e.s.db.serverConfig}else if(e instanceof i){this.type=m.DATABASE;this.topology=e.serverConfig}else if(e instanceof a){this.type=m.CLUSTER;this.topology=e.topology}else{throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient")}this.promiseLibrary=e.s.promiseLibrary;if(!this.options.readPreference&&e.s.readPreference){this.options.readPreference=e.s.readPreference}this[g]=new n;this.cursor=createChangeStreamCursor(this,o);this.closed=false;this.on("newListener",(e=>{if(e==="change"&&this.cursor&&this.listenerCount("change")===0){this.cursor.on("data",(e=>processNewChange(this,e)))}}));this.on("removeListener",(e=>{if(e==="change"&&this.listenerCount("change")===0&&this.cursor){this.cursor.removeAllListeners("data")}}))}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.hasNext(e)}))}))}next(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.next(((t,r)=>{if(t){this[g].push((()=>this.next(e)));processError(this,t,e);return}processNewChange(this,r,e)}))}))}))}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,(e=>{if(this.closed)return e();this.closed=true;if(!this.cursor)return e();const t=this.cursor;return t.close((r=>{["data","close","end","error"].forEach((e=>t.removeAllListeners(e)));this.cursor=undefined;return e(r)}))}))}pipe(e,t){if(!this.pipeDestinations){this.pipeDestinations=[]}this.pipeDestinations.push(e);return this.cursor.pipe(e,t)}unpipe(e){if(this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1){this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1)}return this.cursor.unpipe(e)}stream(e){this.streamOptions=e;return this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}class ChangeStreamCursor extends a{constructor(e,t,r){super(e,t,r);r=r||{};this._resumeToken=null;this.startAtOperationTime=r.startAtOperationTime;if(r.startAfter){this.resumeToken=r.startAfter}else if(r.resumeAfter){this.resumeToken=r.resumeAfter}}set resumeToken(e){this._resumeToken=e;this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of E){if(this.options[t])e[t]=this.options[t]}if(this.resumeToken||this.startAtOperationTime){["resumeAfter","startAfter","startAtOperationTime"].forEach((t=>delete e[t]));if(this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else if(this.startAtOperationTime&&c(this.server)>=7){e.startAtOperationTime=this.startAtOperationTime}}return e}cacheResumeToken(e){if(this.bufferedCount()===0&&this.cursorState.postBatchResumeToken){this.resumeToken=this.cursorState.postBatchResumeToken}else{this.resumeToken=e}this.hasReceived=true}_processBatch(e,t){const r=t.cursor;if(r.postBatchResumeToken){this.cursorState.postBatchResumeToken=r.postBatchResumeToken;if(r[e].length===0){this.resumeToken=r.postBatchResumeToken}}}_initializeCursor(e){super._initializeCursor(((t,r)=>{if(t||r==null){e(t,r);return}const n=r.documents[0];if(this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&c(this.server)>=7){this.startAtOperationTime=n.operationTime}this._processBatch("firstBatch",n);this.emit("init",r);this.emit("response");e(t,r)}))}_getMore(e){super._getMore(((t,r)=>{if(t){e(t);return}this._processBatch("nextBatch",r);this.emit("more",r);this.emit("response");e(t,r)}))}}function createChangeStreamCursor(e,t){const r={fullDocument:t.fullDocument||"default"};applyKnownOptions(r,t,p);if(e.type===m.CLUSTER){r.allChangesForCluster=true}const n=[{$changeStream:r}].concat(e.pipeline);const o=applyKnownOptions({},t,E);const s=new ChangeStreamCursor(e.topology,new d(e.parent,n,t),o);A(s,e,["resumeTokenChanged","end","close"]);if(e.listenerCount("change")>0){s.on("data",(function(t){processNewChange(e,t)}))}s.on("error",(function(t){processError(e,t)}));if(e.pipeDestinations){const t=s.stream(e.streamOptions);for(let r of e.pipeDestinations){t.pipe(r)}}return s}function applyKnownOptions(e,t,r){r.forEach((r=>{if(t[r]){e[r]=t[r]}}));return e}const C=3e4;function waitForTopologyConnected(e,t,r){setTimeout((()=>{if(t&&t.start==null){t.start=u()}const n=t.start||u();const o=t.timeout||C;const s=t.readPreference;if(e.isConnected({readPreference:s})){return r()}if(h(n)>o){return r(new i("Timed out waiting for connection"))}waitForTopologyConnected(e,t,r)}),500)}function processNewChange(e,t,r){const n=e.cursor;if(t==null){e.closed=true}if(e.closed){if(r)r(new i("ChangeStream is closed"));return}if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");if(!r)return e.emit("error",t);return r(t)}n.cacheResumeToken(t._id);e.options.startAtOperationTime=undefined;if(!r)return e.emit("change",t);return r(undefined,t)}function processError(e,t,r){const n=e.topology;const o=e.cursor;if(e.closed){if(r)r(new i("ChangeStream is closed"));return}function resumeWithCursor(t){e.cursor=t;processResumeQueue(e)}function unresumableError(t){if(!r){e.emit("error",t);e.emit("close")}processResumeQueue(e,t);e.closed=true}if(o&&s(t,c(o.server))){e.cursor=undefined;["data","close","end","error"].forEach((e=>o.removeAllListeners(e)));o.close();waitForTopologyConnected(n,{readPreference:o.options.readPreference},(t=>{if(t)return unresumableError(t);const n=createChangeStreamCursor(e,o.resumeOptions);if(!r)return resumeWithCursor(n);n.hasNext((e=>{if(e)return unresumableError(e);resumeWithCursor(n)}))}));return}if(!r)return e.emit("error",t);return r(t)}function getCursor(e,t){if(e.isClosed()){t(new i("ChangeStream is closed."));return}if(e.cursor){t(undefined,e.cursor);return}e[g].push(t)}function processResumeQueue(e,t){while(e[g].length){const r=e[g].pop();if(e.isClosed()&&!t){r(new i("Change Stream is not open."));return}r(t,e.cursor)}}e.exports=ChangeStream},9820:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2425);const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(3111).MongoNetworkTimeoutError;const A=r(3111).MongoWriteConcernError;const c=r(2337);const l=r(6292).StreamDescription;const u=r(9206);const h=r(9815);const d=r(5474).updateSessionFromResponse;const g=r(1178).uuidV4;const p=r(1371).now;const E=r(1371).calculateDurationInMs;const m=Symbol("stream");const C=Symbol("queue");const I=Symbol("messageStream");const y=Symbol("generation");const B=Symbol("lastUseTime");const Q=Symbol("clusterTime");const b=Symbol("description");const w=Symbol("ismaster");const S=Symbol("autoEncrypter");class Connection extends n{constructor(e,t){super(t);this.id=t.id;this.address=streamIdentifier(e);this.bson=t.bson;this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.host=t.host||"localhost";this.port=t.port||27017;this.monitorCommands=typeof t.monitorCommands==="boolean"?t.monitorCommands:false;this.serverApi=t.serverApi;this.closed=false;this.destroyed=false;this[b]=new l(this.address,t);this[y]=t.generation;this[B]=p();if(t.autoEncrypter){this[S]=t.autoEncrypter}this[C]=new Map;this[I]=new o(t);this[I].on("message",messageHandler(this));this[m]=e;e.on("error",(()=>{}));this[I].on("error",(e=>this.handleIssue({destroy:e})));e.on("close",(()=>this.handleIssue({isClose:true})));e.on("timeout",(()=>this.handleIssue({isTimeout:true,destroy:true})));e.pipe(this[I]);this[I].pipe(e)}get description(){return this[b]}get ismaster(){return this[w]}set ismaster(e){this[b].receiveResponse(e);this[w]=e}get generation(){return this[y]||0}get idleTime(){return E(this[B])}get clusterTime(){return this[Q]}get stream(){return this[m]}markAvailable(){this[B]=p()}handleIssue(e){if(this.closed){return}if(e.destroy){this[m].destroy(typeof e.destroy==="boolean"?undefined:e.destroy)}this.closed=true;for(const t of this[C]){const r=t[1];if(e.isTimeout){r.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null}))}else if(e.isClose){r.cb(new i(`connection ${this.id} to ${this.address} closed`))}else{r.cb(typeof e.destroy==="boolean"?undefined:e.destroy)}}this[C].clear();this.emit("close")}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(this[m]==null||this.destroyed){this.destroyed=true;if(typeof t==="function"){t()}return}if(e.force){this[m].destroy();this.destroyed=true;if(typeof t==="function"){t()}return}this[m].end((e=>{this.destroyed=true;if(typeof t==="function"){t(e)}}))}applyApiVersion(e){if(this.serverApi){e.serverApi=this.serverApi}return e}command(e,t,r,n){if(typeof r==="function"){n=r;r={}}u.command(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}query(e,t,r,n,o){u.query(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}getMore(e,t,r,n,o){u.getMore(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}killCursors(e,t,r){u.killCursors(makeServerTrampoline(this),e,t,this.applyApiVersion({}),r)}insert(e,t,r,n){u.insert(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}update(e,t,r,n){u.update(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}remove(e,t,r,n){u.remove(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}}function makeServerTrampoline(e){const t={description:e.description,clusterTime:e[Q],s:{bson:e.bson,pool:{write:write.bind(e),isConnected:()=>true}}};if(e[S]){t.autoEncrypter=e[S]}return t}function messageHandler(e){return function messageHandler(t){e.emit("message",t);if(!e[C].has(t.responseTo)){return}const r=e[C].get(t.responseTo);const n=r.cb;e[C].delete(t.responseTo);if(t.moreToCome){e[C].set(t.requestId,r)}else if(r.socketTimeoutOverride){e[m].setTimeout(e.socketTimeout)}try{t.parse(r)}catch(e){n(new s(e));return}if(t.documents[0]){const o=t.documents[0];const i=r.session;if(i){d(i,o)}if(o.$clusterTime){e[Q]=o.$clusterTime;e.emit("clusterTimeReceived",o.$clusterTime)}if(r.command){if(o.writeConcernError){n(new A(o.writeConcernError,o));return}if(o.ok===0||o.$err||o.errmsg||o.code){n(new s(o));return}}}n(undefined,new c(r.fullResult?t:t.documents[0],e,t))}}function streamIdentifier(e){if(typeof e.address==="function"){return`${e.remoteAddress}:${e.remotePort}`}return g().toString("hex")}function write(e,t,r){if(typeof t==="function"){r=t}t=t||{};const n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false,noResponse:typeof t.noResponse==="boolean"?t.noResponse:false,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,raw:typeof t.raw==="boolean"?t.raw:false};if(this[b]&&this[b].compressor){n.agreedCompressor=this[b].compressor;if(this[b].zlibCompressionLevel){n.zlibCompressionLevel=this[b].zlibCompressionLevel}}if(typeof t.socketTimeout==="number"){n.socketTimeoutOverride=true;this[m].setTimeout(t.socketTimeout)}if(this.monitorCommands){this.emit("commandStarted",new h.CommandStartedEvent(this,e));n.started=p();n.cb=(t,o)=>{if(t){this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,n.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,n.started))}else{this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,n.started))}}if(typeof r==="function"){r(t,o)}}}if(!n.noResponse){this[C].set(n.requestId,n)}try{this[I].writeCommand(e,n)}catch(e){if(!n.noResponse){this[C].delete(n.requestId);n.cb(e);return}}if(n.noResponse){n.cb()}}e.exports={Connection:Connection}},2529:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361).EventEmitter;const s=r(104);const i=r(1371).makeCounter;const a=r(3111).MongoError;const A=r(9820).Connection;const c=r(1178).eachAsync;const l=r(6573);const u=r(1178).relayEvents;const h=r(2926);const d=h.PoolClosedError;const g=h.WaitQueueTimeoutError;const p=r(897);const E=p.ConnectionPoolCreatedEvent;const m=p.ConnectionPoolClosedEvent;const C=p.ConnectionCreatedEvent;const I=p.ConnectionReadyEvent;const y=p.ConnectionClosedEvent;const B=p.ConnectionCheckOutStartedEvent;const Q=p.ConnectionCheckOutFailedEvent;const b=p.ConnectionCheckedOutEvent;const w=p.ConnectionCheckedInEvent;const S=p.ConnectionPoolClearedEvent;const v=Symbol("logger");const R=Symbol("connections");const k=Symbol("permits");const D=Symbol("minPoolSizeTimer");const N=Symbol("generation");const T=Symbol("connectionCounter");const O=Symbol("cancellationToken");const _=Symbol("waitQueue");const M=Symbol("cancelled");const L=new Set(["ssl","bson","connectionType","serverApi","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 resolveOptions(e,t){const r=Array.from(L).reduce(((t,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){t[r]=e[r]}return t}),{});return Object.freeze(Object.assign({},t,r))}class ConnectionPool extends o{constructor(e){super();e=e||{};this.closed=false;this.options=resolveOptions(e,{connectionType:A,maxPoolSize:typeof e.maxPoolSize==="number"?e.maxPoolSize:100,minPoolSize:typeof e.minPoolSize==="number"?e.minPoolSize:0,maxIdleTimeMS:typeof e.maxIdleTimeMS==="number"?e.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof e.waitQueueTimeoutMS==="number"?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata,useUnifiedTopology:e.useUnifiedTopology});if(e.minSize>e.maxSize){throw new TypeError("Connection pool minimum size must not be greater than maximum pool size")}this[v]=s("ConnectionPool",e);this[R]=new n;this[k]=this.options.maxPoolSize;this[D]=undefined;this[N]=0;this[T]=i(1);this[O]=new o;this[O].setMaxListeners(Infinity);this[_]=new n;process.nextTick((()=>{this.emit("connectionPoolCreated",new E(this));ensureMinPoolSize(this)}))}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[N]}get totalConnectionCount(){return this[R].length+(this.options.maxPoolSize-this[k])}get availableConnectionCount(){return this[R].length}get waitQueueSize(){return this[_].length}checkOut(e){this.emit("connectionCheckOutStarted",new B(this));if(this.closed){this.emit("connectionCheckOutFailed",new Q(this,"poolClosed"));e(new d(this));return}const t={callback:e};const r=this;const n=this.options.waitQueueTimeoutMS;if(n){t.timer=setTimeout((()=>{t[M]=true;t.timer=undefined;r.emit("connectionCheckOutFailed",new Q(r,"timeout"));t.callback(new g(r))}),n)}this[_].push(t);process.nextTick((()=>processWaitQueue(this)))}checkIn(e){const t=this.closed;const r=connectionIsStale(this,e);const n=!!(t||r||e.closed);if(!n){e.markAvailable();this[R].push(e)}this.emit("connectionCheckedIn",new w(this,e));if(n){const r=e.closed?"error":t?"poolClosed":"stale";destroyConnection(this,e,r)}process.nextTick((()=>processWaitQueue(this)))}clear(){this[N]+=1;this.emit("connectionPoolCleared",new S(this))}close(e,t){if(typeof e==="function"){t=e}e=Object.assign({force:false},e);if(this.closed){return t()}this[O].emit("cancel");while(this.waitQueueSize){const e=this[_].pop();clearTimeout(e.timer);if(!e[M]){e.callback(new a("connection pool closed"))}}if(this[D]){clearTimeout(this[D])}if(typeof this[T].return==="function"){this[T].return()}this.closed=true;c(this[R].toArray(),((t,r)=>{this.emit("connectionClosed",new y(this,t,"poolClosed"));t.destroy(e,r)}),(e=>{this[R].clear();this.emit("connectionPoolClosed",new m(this));t(e)}))}withConnection(e,t){this.checkOut(((r,n)=>{e(r,n,((e,r)=>{if(typeof t==="function"){if(e){t(e)}else{t(undefined,r)}}if(n){this.checkIn(n)}}))}))}}function ensureMinPoolSize(e){if(e.closed||e.options.minPoolSize===0){return}const t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rensureMinPoolSize(e)),10)}function connectionIsStale(e,t){return t.generation!==e[N]}function connectionIsIdle(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function createConnection(e,t){const r=Object.assign({id:e[T].next().value,generation:e[N]},e.options);e[k]--;l(r,e[O],((r,n)=>{if(r){e[k]++;e[v].debug(`connection attempt failed with error [${JSON.stringify(r)}]`);if(typeof t==="function"){t(r)}return}if(e.closed){n.destroy({force:true});return}u(n,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]);e.emit("connectionCreated",new C(e,n));n.markAvailable();e.emit("connectionReady",new I(e,n));if(typeof t==="function"){t(undefined,n);return}e[R].push(n);process.nextTick((()=>processWaitQueue(e)))}))}function destroyConnection(e,t,r){e.emit("connectionClosed",new y(e,t,r));e[k]++;process.nextTick((()=>t.destroy()))}function processWaitQueue(e){if(e.closed){return}while(e.waitQueueSize){const t=e[_].peekFront();if(t[M]){e[_].shift();continue}if(!e.availableConnectionCount){break}const r=e[R].shift();const n=connectionIsStale(e,r);const o=connectionIsIdle(e,r);if(!n&&!o&&!r.closed){e.emit("connectionCheckedOut",new b(e,r));clearTimeout(t.timer);e[_].shift();t.callback(undefined,r);return}const s=r.closed?"error":n?"stale":"idle";destroyConnection(e,r,s)}const t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{const n=e[_].shift();if(n==null||n[M]){if(t==null){e[R].push(r)}return}if(t){e.emit("connectionCheckOutFailed",new Q(e,t))}else{e.emit("connectionCheckedOut",new b(e,r))}clearTimeout(n.timer);n.callback(t,r)}));return}}e.exports={ConnectionPool:ConnectionPool}},2926:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class PoolClosedError extends n{constructor(e){super("Attempted to check out a connection from closed connection pool");this.name="MongoPoolClosedError";this.address=e.address}}class WaitQueueTimeoutError extends n{constructor(e){super("Timed out while checking out a connection from connection pool");this.name="MongoWaitQueueTimeoutError";this.address=e.address}}e.exports={PoolClosedError:PoolClosedError,WaitQueueTimeoutError:WaitQueueTimeoutError}},897:e=>{"use strict";class ConnectionPoolMonitoringEvent{constructor(e){this.time=new Date;this.address=e.address}}class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e);this.options=e.options}}class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t,r){super(e);this.connectionId=t.id;this.reason=r||"unknown"}}class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.reason=t}}class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}const t=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];e.exports={CMAP_EVENT_NAMES:t,ConnectionPoolCreatedEvent:ConnectionPoolCreatedEvent,ConnectionPoolClosedEvent:ConnectionPoolClosedEvent,ConnectionCreatedEvent:ConnectionCreatedEvent,ConnectionReadyEvent:ConnectionReadyEvent,ConnectionClosedEvent:ConnectionClosedEvent,ConnectionCheckOutStartedEvent:ConnectionCheckOutStartedEvent,ConnectionCheckOutFailedEvent:ConnectionCheckOutFailedEvent,ConnectionCheckedOutEvent:ConnectionCheckedOutEvent,ConnectionCheckedInEvent:ConnectionCheckedInEvent,ConnectionPoolClearedEvent:ConnectionPoolClearedEvent}},2425:(e,t,r)=>{"use strict";const n=r(2781).Duplex;const o=r(336);const s=r(3111).MongoParseError;const i=r(7793).decompress;const a=r(9814).Response;const A=r(8988).BinMsg;const c=r(3111).MongoError;const l=r(7272).opcodes.OP_COMPRESSED;const u=r(7272).opcodes.OP_MSG;const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(8988).Msg;const I=1024*1024*16*4;const y=Symbol("buffer");class MessageStream extends n{constructor(e){e=e||{};super(e);this.bson=e.bson;this.maxBsonMessageSize=e.maxBsonMessageSize||I;this[y]=new o}_write(e,t,r){const n=this[y];n.append(e);processIncomingData(this,r)}_read(){return}writeCommand(e,t){const r=t&&!!t.agreedCompressor;if(!r||!canCompress(e)){const t=e.toBin();this.push(Array.isArray(t)?Buffer.concat(t):t);return}const n=Buffer.concat(e.toBin());const o=n.slice(h);const s=n.readInt32LE(12);p({options:t},o,((r,n)=>{if(r){t.cb(r,null);return}const i=Buffer.alloc(h);i.writeInt32LE(h+d+n.length,0);i.writeInt32LE(e.requestId,4);i.writeInt32LE(0,8);i.writeInt32LE(g.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(s,0);a.writeInt32LE(o.length,4);a.writeUInt8(E[t.agreedCompressor],8);this.push(Buffer.concat([i,a,n]))}))}}function canCompress(e){const t=e instanceof C?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function processIncomingData(e,t){const r=e[y];if(r.length<4){t();return}const n=r.readInt32LE(0);if(n<0){t(new s(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new s(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}const o=r.slice(0,n);r.consume(n);const d={length:o.readInt32LE(0),requestId:o.readInt32LE(4),responseTo:o.readInt32LE(8),opCode:o.readInt32LE(12)};let g=d.opCode===u?A:a;const p=e.responseOptions;if(d.opCode!==l){const n=o.slice(h);e.emit("message",new g(e.bson,o,d,n,p));if(r.length>=4){processIncomingData(e,t)}else{t()}return}d.fromCompressed=true;d.opCode=o.readInt32LE(h);d.length=o.readInt32LE(h+4);const E=o[h+8];const m=o.slice(h+9);g=d.opCode===u?A:a;i(E,m,((n,s)=>{if(n){t(n);return}if(s.length!==d.length){t(new c("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new g(e.bson,o,d,s,p));if(r.length>=4){processIncomingData(e,t)}else{t()}}))}e.exports=MessageStream},6292:(e,t,r)=>{"use strict";const n=r(750).parseServerType;const o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];class StreamDescription{constructor(e,t){this.address=e;this.type=n(null);this.minWireVersion=undefined;this.maxWireVersion=undefined;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=n(e);o.forEach((t=>{if(typeof e[t]!=="undefined"){this[t]=e[t]}}));if(e.compression){this.compressor=this.compressors.filter((t=>e.compression.indexOf(t)!==-1))[0]}}}e.exports={StreamDescription:StreamDescription}},5193:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(1371).deprecateOptions;const s=r(1371).emitWarningOnce;const i=r(1371).checkCollectionName;const a=r(3994).BSON.ObjectID;const A=r(3994).MongoError;const c=r(1371).normalizeHintField;const l=r(1371).decorateCommand;const u=r(1371).decorateWithCollation;const h=r(1371).decorateWithReadConcern;const d=r(1371).formattedOrderClause;const g=r(3994).ReadPreference;const p=r(325);const E=r(5035);const m=r(1117);const C=r(1371).executeLegacyOperation;const I=r(2481);const y=r(7289);const B=r(1371).MongoDBNamespace;const Q=r(7429);const b=r(538);const w=r(6716).ensureIndex;const S=r(6716).group;const v=r(6716).parallelCollectionScan;const R=r(2296).removeDocuments;const k=r(6716).save;const D=r(2296).updateDocuments;const N=r(1554);const T=r(6976);const O=r(5131);const _=r(6394);const M=r(323);const L=r(6352);const F=r(6469);const U=r(2360).DropCollectionOperation;const P=r(3560);const G=r(5328);const Y=r(4451);const V=r(9961);const W=r(4497);const J=r(711);const q=r(5841);const j=r(4316);const z=r(1925);const $=r(8169);const K=r(4218);const X=r(7809);const Z=r(4245);const ee=r(3592);const te=r(9915);const re=r(4956);const ne=r(28);const oe=r(2779);const se=r(43);const ie=r(2808);const ae=r(6331);const Ae=r(2508);const ce=r(968);const le=r(9350);const ue=r(9068);const fe=r(2548);const he=["ignoreUndefined"];function Collection(e,t,r,n,o,s){i(n);const A=null;const c=s==null||s.slaveOk==null?e.slaveOk:s.slaveOk;const l=s==null||s.serializeFunctions==null?e.s.options.serializeFunctions:s.serializeFunctions;const u=s==null||s.raw==null?e.s.options.raw:s.raw;const h=s==null||s.promoteLongs==null?e.s.options.promoteLongs:s.promoteLongs;const d=s==null||s.promoteValues==null?e.s.options.promoteValues:s.promoteValues;const p=s==null||s.promoteBuffers==null?e.s.options.promoteBuffers:s.promoteBuffers;const E=s==null||s.bsonRegExp==null?e.s.options.bsonRegExp:s.bsonRegExp;const m=null;const C=new B(r,n);const Q=s.promiseLibrary||Promise;o=o==null?a:o;this.s={pkFactory:o,db:e,topology:t,options:s,namespace:C,readPreference:g.fromOptions(s),slaveOk:c,serializeFunctions:l,raw:u,promoteLongs:h,promoteValues:d,promoteBuffers:p,bsonRegExp:E,internalHint:A,collectionHint:m,promiseLibrary:Q,readConcern:y.fromOptions(s),writeConcern:I.fromOptions(s)}}Object.defineProperty(Collection.prototype,"dbName",{enumerable:true,get:function(){return this.s.namespace.db}});Object.defineProperty(Collection.prototype,"collectionName",{enumerable:true,get:function(){return this.s.namespace.collection}});Object.defineProperty(Collection.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Object.defineProperty(Collection.prototype,"readConcern",{enumerable:true,get:function(){if(this.s.readConcern==null){return this.s.db.readConcern}return this.s.readConcern}});Object.defineProperty(Collection.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return this.s.db.readPreference}return this.s.readPreference}});Object.defineProperty(Collection.prototype,"writeConcern",{enumerable:true,get:function(){if(this.s.writeConcern==null){return this.s.db.writeConcern}return this.s.writeConcern}});Object.defineProperty(Collection.prototype,"hint",{enumerable:true,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const de=["maxScan","fields","snapshot","oplogReplay"];Collection.prototype.find=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `find()` must be a callback or undefined")}let n=e;if(typeof r!=="function"){if(typeof t==="function"){r=t;t=undefined}else if(t==null){r=typeof n==="function"?n:undefined;n=typeof n==="object"?n:undefined}}n=n==null?{}:n;const o=n;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+"]");t.name="MongoError";throw t}}if(n!=null&&n._bsontype==="ObjectID"){n={_id:n}}if(!t)t={};let i=t.projection||t.fields;if(i&&!Buffer.isBuffer(i)&&Array.isArray(i)){i=i.length?i.reduce(((e,t)=>{e[t]=1;return e}),{}):{_id:1}}let a=Object.assign({},t);for(let e in this.s.options){if(he.indexOf(e)!==-1){a[e]=this.s.options[e]}}a.skip=t.skip?t.skip:0;a.limit=t.limit?t.limit:0;a.raw=typeof t.raw==="boolean"?t.raw:this.s.raw;a.hint=t.hint!=null?c(t.hint):this.s.collectionHint;a.timeout=typeof t.timeout==="undefined"?undefined:t.timeout;a.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk;a.readPreference=g.resolve(this,a);if(a.readPreference!=null&&(a.readPreference!=="primary"||a.readPreference.mode!=="primary")){a.slaveOk=true}if(n!=null&&typeof n!=="object"){throw A.create({message:"query selector must be an object",driver:true})}const p={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:n};if(typeof t.allowDiskUse==="boolean"){p.allowDiskUse=t.allowDiskUse}if(typeof a.awaitdata==="boolean"){a.awaitData=a.awaitdata}if(typeof a.timeout==="boolean")a.noCursorTimeout=!a.timeout;l(p,a,["session","collation"]);if(i)p.fields=i;a.db=this.s.db;a.promiseLibrary=this.s.promiseLibrary;if(a.raw==null&&typeof this.s.raw==="boolean")a.raw=this.s.raw;if(a.promoteLongs==null&&typeof this.s.promoteLongs==="boolean")a.promoteLongs=this.s.promoteLongs;if(a.promoteValues==null&&typeof this.s.promoteValues==="boolean")a.promoteValues=this.s.promoteValues;if(a.promoteBuffers==null&&typeof this.s.promoteBuffers==="boolean")a.promoteBuffers=this.s.promoteBuffers;if(a.bsonRegExp==null&&typeof this.s.bsonRegExp==="boolean")a.bsonRegExp=this.s.bsonRegExp;if(p.sort){p.sort=d(p.sort)}h(p,this,t);try{u(p,this,t)}catch(e){if(typeof r==="function")return r(e,null);throw e}const E=this.s.topology.cursor(new V(this,this.s.namespace,p,a),a);if(typeof r==="function"){r(null,E);return}return E}));Collection.prototype.insertOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new te(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insertMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{ordered:true};const n=new ee(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.bulkWrite=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:true};if(!Array.isArray(e)){throw A.create({message:"operations must be an array of documents",driver:true})}const n=new T(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insert=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:false};e=!Array.isArray(e)?[e]:e;if(t.keepGoing===true){t.ordered=false}return this.insertMany(e,t,r)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");Collection.prototype.updateOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new ue(this,e,t,r),n)};Collection.prototype.replaceOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new Ae(this,e,t,r),n)};Collection.prototype.updateMany=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new le(this,e,t,r),n)};Collection.prototype.update=n((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,D,[this,e,t,r,n])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");Collection.prototype.deleteOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new L(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeOne=Collection.prototype.deleteOne;Collection.prototype.deleteMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new M(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeMany=Collection.prototype.deleteMany;Collection.prototype.remove=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,R,[this,e,t,r])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");Collection.prototype.save=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,k,[this,e,t,r])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");Collection.prototype.findOne=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `findOne()` must be a callback or undefined")}if(typeof e==="function")r=e,e={},t={};if(typeof t==="function")r=t,t={};e=e||{};t=t||{};const n=new W(this,e,t);return fe(this.s.topology,n,r)}));Collection.prototype.rename=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t,{readPreference:g.PRIMARY});const n=new ie(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.drop=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new U(this.s.db,this.collectionName,e);return fe(this.s.topology,r,t)};Collection.prototype.options=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new se(this,e);return fe(this.s.topology,r,t)};Collection.prototype.isCapped=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new re(this,e);return fe(this.s.topology,r,t)};Collection.prototype.createIndex=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.createIndexes=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{};if(typeof t.maxTimeMS!=="number")delete t.maxTimeMS;const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.dropIndex=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift()||{}:{};t.readPreference=g.PRIMARY;const o=new P(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.dropIndexes=function(e,t){if(typeof e==="function")t=e,e={};e=e?Object.assign({},e):{};if(typeof e.maxTimeMS!=="number")delete e.maxTimeMS;const r=new G(this,e);return fe(this.s.topology,r,t)};Collection.prototype.dropAllIndexes=n(Collection.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");Collection.prototype.reIndex=n((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new ae(this,e);return fe(this.s.topology,r,t)}),"collection.reIndex is deprecated. Use db.command instead.");Collection.prototype.listIndexes=function(e){const t=new b(this.s.topology,new ne(this,e),e);return t};Collection.prototype.ensureIndex=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return C(this.s.topology,w,[this,e,t,r])}),"collection.ensureIndex is deprecated. Use createIndexes instead.");Collection.prototype.indexExists=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new X(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.indexInformation=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new Z(this.s.db,this.collectionName,e);return fe(this.s.topology,n,t)};Collection.prototype.count=n((function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};if(typeof t==="function")r=t,t={};t=t||{};return fe(this.s.topology,new Y(this,Object.assign({query:e},t)),r)}),"collection.count is deprecated, and will be removed in a future version."+" Use Collection.countDocuments or Collection.estimatedDocumentCount instead");Collection.prototype.estimatedDocumentCount=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new Y(this,e);return fe(this.s.topology,r,t)};Collection.prototype.countDocuments=function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};const o=new O(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.distinct=function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;const s=o.length?o.shift()||{}:{};const i=o.length?o.shift()||{}:{};const a=new F(this,e,s,i);return fe(this.s.topology,a,n)};Collection.prototype.indexes=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new K(this,e);return fe(this.s.topology,r,t)};Collection.prototype.stats=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new ce(this,e);return fe(this.s.topology,n,t)};Collection.prototype.findOneAndDelete=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new q(this,e,t),r)};Collection.prototype.findOneAndReplace=o({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new j(this,e,t,r),n)}));Collection.prototype.findOneAndUpdate=o({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new z(this,e,t,r),n)}));Collection.prototype.findAndModify=n(_findAndModify,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");Collection.prototype._findAndModify=_findAndModify;function _findAndModify(e,t,r,n,o){const s=Array.prototype.slice.call(arguments,1);o=typeof s[s.length-1]==="function"?s.pop():undefined;t=s.length?s.shift()||[]:[];r=s.length?s.shift():null;n=s.length?s.shift()||{}:{};n=Object.assign({},n);n.readPreference=g.PRIMARY;return fe(this.s.topology,new J(this,e,t,r,n),o)}Collection.prototype.findAndRemove=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift()||[]:[];r=o.length?o.shift()||{}:{};r.remove=true;return fe(this.s.topology,new J(this,e,t,null,r),n)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");Collection.prototype.aggregate=function(e,t,r){if(Array.isArray(e)){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}}else{const n=Array.prototype.slice.call(arguments,0);r=n.pop();const o=n[n.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?n.pop():{};e=n}const n=new Q(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Collection.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Collection.prototype.parallelCollectionScan=n((function(e,t){if(typeof e==="function")t=e,e={numCursors:1};e.numCursors=e.numCursors||1;e.batchSize=e.batchSize||1e3;e=Object.assign({},e);e.readPreference=g.resolve(this,e);e.promiseLibrary=this.s.promiseLibrary;if(e.session){e.session=undefined}return C(this.s.topology,v,[this,e,t],{skipSessions:true})}),"parallelCollectionScan is deprecated in MongoDB v4.1");Collection.prototype.geoHaystackSearch=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift()||{}:{};const s=new $(this,e,t,r);return fe(this.s.topology,s,n)}),"geoHaystackSearch is deprecated, and will be removed in a future version.");Collection.prototype.group=n((function(e,t,r,n,o,s,i,a){const A=Array.prototype.slice.call(arguments,3);a=typeof A[A.length-1]==="function"?A.pop():undefined;n=A.length?A.shift():null;o=A.length?A.shift():null;s=A.length?A.shift():null;i=A.length?A.shift()||{}:{};if(!(typeof o==="function")){s=o;o=null}if(!Array.isArray(e)&&e instanceof Object&&typeof e!=="function"&&!(e._bsontype==="Code")){e=Object.keys(e)}if(typeof n==="function"){n=n.toString()}if(typeof o==="function"){o=o.toString()}s=s==null?true:s;return C(this.s.topology,S,[this,e,t,r,n,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");Collection.prototype.mapReduce=function(e,t,r,n){if("function"===typeof r)n=r,r={};if(null==r.out){throw new Error("the out option parameter must be defined, see mongodb docs for possible values")}if("function"===typeof e){e=e.toString()}if("function"===typeof t){t=t.toString()}if("function"===typeof r.finalize){r.finalize=r.finalize.toString()}const o=new oe(this,e,t,r);return fe(this.s.topology,o,n)};Collection.prototype.initializeUnorderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return p(this.s.topology,this,e)};Collection.prototype.initializeOrderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return E(this.s.topology,this,e)};Collection.prototype.getLogger=function(){return this.s.db.s.logger};e.exports=Collection},538:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(3994).MongoError;const s=r(7159);const i=r(4847).CursorState;class CommandCursor extends s{constructor(e,t,r,n){super(e,t,r,n)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(this.s.state!==i.INIT){throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof n){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new n(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw o.create({message:"batchSize requires an integer",driver:true})}if(this.cmd.cursor){this.cmd.cursor.batchSize=e}this.setCursorBatchSize(e);return this}maxTimeMS(e){if(this.topology.lastIsMaster().minWireVersion>2){this.cmd.maxTimeMS=e}return this}getLogger(){return this.logger}}CommandCursor.prototype.get=CommandCursor.prototype.toArray;e.exports=CommandCursor},7703:(e,t,r)=>{"use strict";const n=r(8988).Msg;const o=r(9814).KillCursor;const s=r(9814).GetMore;const i=r(1371).deepCopy;const a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const A=new Set(["hello","ismaster","isMaster"]);const c={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"};const l={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"};const u=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"];const collectionName=e=>e.ns.split(".")[1];const shouldRedactCommand=(e,t)=>a.has(e)||A.has(e)&&!!t.speculativeAuthenticate;const extractCommand=e=>{let t;if(e instanceof s){t={getMore:i(e.cursorId),collection:collectionName(e),batchSize:e.numberToReturn}}else if(e instanceof o){t={killCursors:collectionName(e),cursors:i(e.cursorIds)}}else if(e instanceof n){t=i(e.command)}else if(e.query&&e.query.$query){let r;if(e.ns==="admin.$cmd"){r=Object.assign({},e.query.$query)}else{r={find:collectionName(e)};Object.keys(c).forEach((t=>{if(typeof e.query[t]!=="undefined")r[c[t]]=i(e.query[t])}))}Object.keys(l).forEach((t=>{if(typeof e[t]!=="undefined")r[l[t]]=i(e[t])}));u.forEach((t=>{if(e[t])r[t]=e[t]}));if(typeof e.pre32Limit!=="undefined"){r.limit=e.pre32Limit}if(e.query.$explain){t={explain:r}}else{t=r}}else{t=i(e.query||e)}const r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:shouldRedactCommand(r,t)}};e.exports={extractCommand:extractCommand}},147:e=>{"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"}},557:e=>{"use strict";class AuthContext{constructor(e,t,r){this.connection=e;this.credentials=t;this.options=r}}class AuthProvider{constructor(e){this.bson=e}prepare(e,t,r){r(undefined,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}e.exports={AuthContext:AuthContext,AuthProvider:AuthProvider}},2192:(e,t,r)=>{"use strict";const n=r(4228);const o=r(7324);const s=r(8728);const i=r(2640);const a=r(864).ScramSHA1;const A=r(864).ScramSHA256;const c=r(8857);function defaultAuthProviders(e){return{"mongodb-aws":new c(e),mongocr:new n(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new A(e)}}e.exports={defaultAuthProviders:defaultAuthProviders}},2640:(e,t,r)=>{"use strict";const n=r(7578);const o=r(557).AuthProvider;const s=r(1178).retrieveKerberos;const i=r(3111).MongoError;let a;class GSSAPI extends o{auth(e,t){const r=e.connection;const n=e.credentials;if(n==null)return t(new i("credentials required"));const o=n.username;function externalCommand(e,t){return r.command("$external.$cmd",e,t)}makeKerberosClient(e,((e,r)=>{if(e)return t(e);if(r==null)return t(new i("gssapi client missing"));r.step("",((e,n)=>{if(e)return t(e);externalCommand(saslStart(n),((e,n)=>{if(e)return t(e);const s=n.result;negotiate(r,10,s.payload,((e,n)=>{if(e)return t(e);externalCommand(saslContinue(n,s.conversationId),((e,n)=>{if(e)return t(e);const s=n.result;finalize(r,o,s.payload,((e,r)=>{if(e)return t(e);externalCommand({saslContinue:1,conversationId:s.conversationId,payload:r},((e,r)=>{if(e)return t(e);t(undefined,r)}))}))}))}))}))}))}))}}e.exports=GSSAPI;function makeKerberosClient(e,t){const r=e.options.host;const n=e.options.port;const o=e.credentials;if(!r||!n||!o){return t(new i(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${o?"host":"credentials"}.`))}if(a==null){try{a=s()}catch(e){return t(e)}}const A=o.username;const c=o.password;const l=o.mechanismProperties;const u=l["gssapiservicename"]||l["gssapiServiceName"]||"mongodb";performGssapiCanonicalizeHostName(r,l,((e,r)=>{if(e)return t(e);const n={};if(c!=null){Object.assign(n,{user:A,password:c})}a.initializeClient(`${u}${process.platform==="win32"?"/":"@"}${r}`,n,((e,r)=>{if(e)return t(new i(e));t(null,r)}))}))}function saslStart(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}function saslContinue(e,t){return{saslContinue:1,conversationId:t,payload:e}}function negotiate(e,t,r,n){e.step(r,((o,s)=>{if(o&&t===0)return n(o);if(o)return negotiate(e,t-1,r,n);n(undefined,s||"")}))}function finalize(e,t,r,n){e.unwrap(r,((r,o)=>{if(r)return n(r);e.wrap(o||"",{user:t},((e,t)=>{if(e)return n(e);n(undefined,t)}))}))}function performGssapiCanonicalizeHostName(e,t,r){const o=typeof t.gssapiCanonicalizeHostName==="boolean"?t.gssapiCanonicalizeHostName:false;if(!o)return r(undefined,e);n.resolveCname(e,((t,n)=>{if(t)return r(t);if(Array.isArray(n)&&n.length>0){return r(undefined,n[0])}r(undefined,e)}))}},2222:e=>{"use strict";function getDefaultAuthMechanism(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 MongoCredentials{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||{};if(/MONGODB-AWS/i.test(this.mechanism)){if(!this.username&&process.env.AWS_ACCESS_KEY_ID){this.username=process.env.AWS_ACCESS_KEY_ID}if(!this.password&&process.env.AWS_SECRET_ACCESS_KEY){this.password=process.env.AWS_SECRET_ACCESS_KEY}if(this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null){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){if(/DEFAULT/i.test(this.mechanism)){return new MongoCredentials({username:this.username,password:this.password,source:this.source,mechanism:getDefaultAuthMechanism(e),mechanismProperties:this.mechanismProperties})}return this}}e.exports={MongoCredentials:MongoCredentials}},4228:(e,t,r)=>{"use strict";const n=r(6113);const o=r(557).AuthProvider;class MongoCR extends o{auth(e,t){const r=e.connection;const o=e.credentials;const s=o.username;const i=o.password;const a=o.source;r.command(`${a}.$cmd`,{getnonce:1},((e,o)=>{let A=null;let c=null;if(e==null){const e=o.result;A=e.nonce;let t=n.createHash("md5");t.update(s+":mongo:"+i,"utf8");const r=t.digest("hex");t=n.createHash("md5");t.update(A+s+r,"utf8");c=t.digest("hex")}const l={authenticate:1,user:s,nonce:A,key:c};r.command(`${a}.$cmd`,l,t)}))}}e.exports=MongoCR},8857:(e,t,r)=>{"use strict";const n=r(557).AuthProvider;const o=r(2222).MongoCredentials;const s=r(3111).MongoError;const i=r(6113);const a=r(3685);const A=r(1178).maxWireVersion;const c=r(7310);let l;try{l=r(3847)}catch(e){}const u=110;const h="http://169.254.170.2";const d="http://169.254.169.254";const g="/latest/meta-data/iam/security-credentials";class MongoDBAWS extends n{auth(e,t){const r=e.connection;const n=e.credentials;if(A(r)<9){t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(l==null){t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(n.username==null){makeTempCredentials(n,((r,n)=>{if(r)return t(r);e.credentials=n;this.auth(e,t)}));return}const o=n.source;const a=this.bson;const c=n.username;const h=n.password;const d=n.mechanismProperties.AWS_SESSION_TOKEN;const g=c&&h&&d?{accessKeyId:c,secretAccessKey:h,sessionToken:d}:c&&h?{accessKeyId:c,secretAccessKey:h}:undefined;i.randomBytes(32,((e,n)=>{if(e){t(e);return}const i={saslStart:1,mechanism:"MONGODB-AWS",payload:a.serialize({r:n,p:u})};r.command(`${o}.$cmd`,i,((e,i)=>{if(e)return t(e);const A=i.result;const c=a.deserialize(A.payload.buffer);const u=c.h;const h=c.s.buffer;if(h.length!==64){t(new s(`Invalid server nonce length ${h.length}, expected 64`));return}if(h.compare(n,0,n.length,0,n.length)!==0){t(new s("Server nonce does not begin with client nonce"));return}if(u.length<1||u.length>255||u.indexOf("..")!==-1){t(new s(`Server returned an invalid host: "${u}"`));return}const p="Action=GetCallerIdentity&Version=2011-06-15";const E=l.sign({method:"POST",host:u,region:deriveRegion(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":p.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:p},g);const m=E.headers.Authorization;const C=E.headers["X-Amz-Date"];const I={a:m,d:C};if(d){I.t=d}const y={saslContinue:1,conversationId:1,payload:a.serialize(I)};r.command(`${o}.$cmd`,y,(e=>{if(e)return t(e);t()}))}))}))}}function makeTempCredentials(e,t){function done(r){if(r.AccessKeyId==null||r.SecretAccessKey==null||r.Token==null){t(new s("Could not obtain temporary MONGODB-AWS credentials"));return}t(undefined,new o({username:r.AccessKeyId,password:r.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:r.Token}}))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){request(`${h}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,undefined,((e,r)=>{if(e)return t(e);done(r)}));return}request(`${d}/latest/api/token`,{method:"PUT",json:false,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},((e,r)=>{if(e)return t(e);request(`${d}/${g}`,{json:false,headers:{"X-aws-ec2-metadata-token":r}},((e,n)=>{if(e)return t(e);request(`${d}/${g}/${n}`,{headers:{"X-aws-ec2-metadata-token":r}},((e,r)=>{if(e)return t(e);done(r)}))}))}))}function deriveRegion(e){const t=e.split(".");if(t.length===1||t[1]==="amazonaws"){return"us-east-1"}return t[1]}function request(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:true},c.parse(e),t);const n=a.request(t,(e=>{e.setEncoding("utf8");let n="";e.on("data",(e=>n+=e));e.on("end",(()=>{if(t.json===false){r(undefined,n);return}try{const e=JSON.parse(n);r(undefined,e)}catch(e){r(new s(`Invalid JSON response: "${n}"`))}}))}));n.on("error",(e=>r(e)));n.end()}e.exports=MongoDBAWS},8728:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(557).AuthProvider;const s=n();const i=s.Binary;class Plain extends o{auth(e,t){const r=e.connection;const n=e.credentials;const o=n.username;const s=n.password;const a=new i(`\0${o}\0${s}`);const A={saslStart:1,mechanism:"PLAIN",payload:a,autoAuthorize:1};r.command("$external.$cmd",A,t)}}e.exports=Plain},864:(e,t,r)=>{"use strict";const n=r(6113);const o=r(1867).Buffer;const s=r(7746).retrieveBSON;const i=r(3111).MongoError;const a=r(557).AuthProvider;const A=r(1371).emitWarning;const c=s();const l=c.Binary;let u;try{u=r(9178)}catch(e){}class ScramSHA extends a{constructor(e,t){super(e);this.cryptoMethod=t||"sha1"}prepare(e,t,r){const o=this.cryptoMethod;if(o==="sha256"&&typeof u!=="function"){A("Warning: no saslprep library specified. Passwords will not be sanitized")}n.randomBytes(24,((n,s)=>{if(n){return r(n)}Object.assign(t,{nonce:s});const i=t.credentials;const a=Object.assign({},e,{speculativeAuthenticate:Object.assign(makeFirstMessage(o,i,s),{db:i.source})});r(undefined,a)}))}auth(e,t){const r=e.response;if(r&&r.speculativeAuthenticate){continueScramConversation(this.cryptoMethod,r.speculativeAuthenticate,e,t);return}executeScram(this.cryptoMethod,e,t)}}function cleanUsername(e){return e.replace("=","=3D").replace(",","=2C")}function clientFirstMessageBare(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function makeFirstMessage(e,t,r){const n=cleanUsername(t.username);const s=e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256";return{saslStart:1,mechanism:s,payload:new l(o.concat([o.from("n,,","utf8"),clientFirstMessageBare(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:true}}}function executeScram(e,t,r){const n=t.connection;const o=t.credentials;const s=t.nonce;const i=o.source;const a=makeFirstMessage(e,o,s);n.command(`${i}.$cmd`,a,((n,o)=>{const s=resolveError(n,o);if(s){return r(s)}continueScramConversation(e,o.result,t,r)}))}function continueScramConversation(e,t,r,n){const s=r.connection;const a=r.credentials;const A=r.nonce;const c=a.source;const h=cleanUsername(a.username);const d=a.password;let g;if(e==="sha256"){g=typeof u==="function"?u(d):d}else{try{g=passwordDigest(h,d)}catch(e){return n(e)}}const p=o.isBuffer(t.payload)?new l(t.payload):t.payload;const E=parsePayload(p.value());const m=parseInt(E.i,10);if(m&&m<4096){n(new i(`Server returned an invalid iteration count ${m}`),false);return}const C=E.s;const I=E.r;if(I.startsWith("nonce")){n(new i(`Server returned an invalid nonce: ${I}`),false);return}const y=`c=biws,r=${I}`;const B=HI(g,o.from(C,"base64"),m,e);const Q=HMAC(e,B,"Client Key");const b=HMAC(e,B,"Server Key");const w=H(e,Q);const S=[clientFirstMessageBare(h,A),p.value().toString("base64"),y].join(",");const v=HMAC(e,w,S);const R=`p=${xor(Q,v)}`;const k=[y,R].join(",");const D=HMAC(e,b,S);const N={saslContinue:1,conversationId:t.conversationId,payload:new l(o.from(k))};s.command(`${c}.$cmd`,N,((e,t)=>{const r=resolveError(e,t);if(r){return n(r)}const a=t.result;const A=parsePayload(a.payload.value());if(!compareDigest(o.from(A.v,"base64"),D)){n(new i("Server returned an invalid signature"));return}if(!a||a.done!==false){return n(r,a)}const l={saslContinue:1,conversationId:a.conversationId,payload:o.alloc(0)};s.command(`${c}.$cmd`,l,n)}))}function parsePayload(e){const t={};const r=e.split(",");for(let e=0;e=200){_hiCachePurge()}h[s]=i;d+=1;return i}function compareDigest(e,t){if(e.length!==t.length){return false}if(typeof n.timingSafeEqual==="function"){return n.timingSafeEqual(e,t)}let r=0;for(let n=0;n{"use strict";const n=r(557).AuthProvider;class X509 extends n{prepare(e,t,r){const n=t.credentials;Object.assign(e,{speculativeAuthenticate:x509AuthenticateCommand(n)});r(undefined,e)}auth(e,t){const r=e.connection;const n=e.credentials;const o=e.response;if(o.speculativeAuthenticate){return t()}r.command("$external.$cmd",x509AuthenticateCommand(n),t)}}function x509AuthenticateCommand(e){const t={authenticate:1,mechanism:"MONGODB-X509"};if(e.username){Object.assign(t,{user:e.username})}return t}e.exports=X509},9815:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(9814).GetMore;const s=r(1371).calculateDurationInMs;const i=r(7703).extractCommand;const namespace=e=>e.ns;const databaseName=e=>e.ns.split(".")[0];const generateConnectionId=e=>e.options?`${e.options.host}:${e.options.port}`:e.address;const isLegacyPool=e=>e.s&&e.queue;const extractReply=(e,t)=>{if(e instanceof o){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),nextBatch:t.message.documents}}}if(e instanceof n){return{ok:1,cursorsUnknown:e.cursorIds}}if(e.query&&typeof e.query.$query!=="undefined"){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),firstBatch:t.message.documents}}}return t&&t.result?t.result:t};const extractConnectionDetails=e=>{if(isLegacyPool(e)){return{connectionId:generateConnectionId(e)}}const t=e;return{address:t.address,connectionId:t.id}};class CommandStartedEvent{constructor(e,t){const r=i(t);const n=r.name;const o=extractConnectionDetails(e);Object.assign(this,o,{requestId:t.requestId,databaseName:databaseName(t),commandName:n,command:r.shouldRedact?{}:r.cmd})}}class CommandSucceededEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),reply:o.shouldRedact?{}:extractReply(t,r)})}}class CommandFailedEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),failure:o.shouldRedact?{}:r})}}e.exports={CommandStartedEvent:CommandStartedEvent,CommandSucceededEvent:CommandSucceededEvent,CommandFailedEvent:CommandFailedEvent}},2337:e=>{"use strict";var CommandResult=function(e,t,r){this.result=e;this.connection=t;this.message=r};CommandResult.prototype.toJSON=function(){let e=Object.assign({},this,this.result);delete e.message;return e};CommandResult.prototype.toString=function(){return JSON.stringify(this.toJSON())};e.exports=CommandResult},9814:(e,t,r)=>{"use strict";var n=r(7746).retrieveBSON;var o=n();var s=o.Long;const i=r(1867).Buffer;var a=0;var A=r(7272).opcodes;var c=2;var l=4;var u=8;var h=16;var d=32;var g=64;var p=128;var E=1;var m=2;var C=4;var I=8;var Query=function(e,t,r,n){var o=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1){throw new Error("namespace cannot contain a null character")}this.bson=e;this.ns=t;this.query=r;this.numberToSkip=n.numberToSkip||0;this.numberToReturn=n.numberToReturn||0;this.returnFieldSelector=n.returnFieldSelector||null;this.requestId=Query.getRequestId();this.pre32Limit=n.pre32Limit;this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:true;this.batchSize=o.numberToReturn;this.tailable=false;this.slaveOk=typeof n.slaveOk==="boolean"?n.slaveOk:false;this.oplogReplay=false;this.noCursorTimeout=false;this.awaitData=false;this.exhaust=false;this.partial=false};Query.prototype.incRequestId=function(){this.requestId=a++};Query.nextRequestId=function(){return a+1};Query.prototype.toBin=function(){var e=this;var t=[];var r=null;var n=0;if(this.tailable){n|=c}if(this.slaveOk){n|=l}if(this.oplogReplay){n|=u}if(this.noCursorTimeout){n|=h}if(this.awaitData){n|=d}if(this.exhaust){n|=g}if(this.partial){n|=p}if(e.batchSize!==e.numberToReturn)e.numberToReturn=e.batchSize;var o=i.alloc(4*4+4+i.byteLength(e.ns)+1+4+4);t.push(o);var s=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(s);if(e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0){r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(r)}var a=o.length+s.length+(r?r.length:0);var E=4;o[3]=a>>24&255;o[2]=a>>16&255;o[1]=a>>8&255;o[0]=a&255;o[E+3]=this.requestId>>24&255;o[E+2]=this.requestId>>16&255;o[E+1]=this.requestId>>8&255;o[E]=this.requestId&255;E=E+4;o[E+3]=0>>24&255;o[E+2]=0>>16&255;o[E+1]=0>>8&255;o[E]=0&255;E=E+4;o[E+3]=A.OP_QUERY>>24&255;o[E+2]=A.OP_QUERY>>16&255;o[E+1]=A.OP_QUERY>>8&255;o[E]=A.OP_QUERY&255;E=E+4;o[E+3]=n>>24&255;o[E+2]=n>>16&255;o[E+1]=n>>8&255;o[E]=n&255;E=E+4;E=E+o.write(this.ns,E,"utf8")+1;o[E-1]=0;o[E+3]=this.numberToSkip>>24&255;o[E+2]=this.numberToSkip>>16&255;o[E+1]=this.numberToSkip>>8&255;o[E]=this.numberToSkip&255;E=E+4;o[E+3]=this.numberToReturn>>24&255;o[E+2]=this.numberToReturn>>16&255;o[E+1]=this.numberToReturn>>8&255;o[E]=this.numberToReturn&255;E=E+4;return t};Query.getRequestId=function(){return++a};var GetMore=function(e,t,r,n){n=n||{};this.numberToReturn=n.numberToReturn||0;this.requestId=a++;this.bson=e;this.ns=t;this.cursorId=r};GetMore.prototype.toBin=function(){var e=4+i.byteLength(this.ns)+1+4+8+4*4;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_GETMORE>>24&255;r[t+2]=A.OP_GETMORE>>16&255;r[t+1]=A.OP_GETMORE>>8&255;r[t]=A.OP_GETMORE&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;t=t+r.write(this.ns,t,"utf8")+1;r[t-1]=0;r[t+3]=this.numberToReturn>>24&255;r[t+2]=this.numberToReturn>>16&255;r[t+1]=this.numberToReturn>>8&255;r[t]=this.numberToReturn&255;t=t+4;r[t+3]=this.cursorId.getLowBits()>>24&255;r[t+2]=this.cursorId.getLowBits()>>16&255;r[t+1]=this.cursorId.getLowBits()>>8&255;r[t]=this.cursorId.getLowBits()&255;t=t+4;r[t+3]=this.cursorId.getHighBits()>>24&255;r[t+2]=this.cursorId.getHighBits()>>16&255;r[t+1]=this.cursorId.getHighBits()>>8&255;r[t]=this.cursorId.getHighBits()&255;t=t+4;return r};var KillCursor=function(e,t,r){this.ns=t;this.requestId=a++;this.cursorIds=r};KillCursor.prototype.toBin=function(){var e=4+4+4*4+this.cursorIds.length*8;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_KILL_CURSORS>>24&255;r[t+2]=A.OP_KILL_CURSORS>>16&255;r[t+1]=A.OP_KILL_CURSORS>>8&255;r[t]=A.OP_KILL_CURSORS&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=this.cursorIds.length>>24&255;r[t+2]=this.cursorIds.length>>16&255;r[t+1]=this.cursorIds.length>>8&255;r[t]=this.cursorIds.length&255;t=t+4;for(var n=0;n>24&255;r[t+2]=this.cursorIds[n].getLowBits()>>16&255;r[t+1]=this.cursorIds[n].getLowBits()>>8&255;r[t]=this.cursorIds[n].getLowBits()&255;t=t+4;r[t+3]=this.cursorIds[n].getHighBits()>>24&255;r[t+2]=this.cursorIds[n].getHighBits()>>16&255;r[t+1]=this.cursorIds[n].getHighBits()>>8&255;r[t]=this.cursorIds[n].getHighBits()&255;t=t+4}return r};var Response=function(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.cursorId=new s(n.readInt32LE(4),n.readInt32LE(8));this.startingFrom=n.readInt32LE(12);this.numberReturned=n.readInt32LE(16);this.documents=new Array(this.numberReturned);this.cursorNotFound=(this.responseFlags&E)!==0;this.queryFailure=(this.responseFlags&m)!==0;this.shardConfigStale=(this.responseFlags&C)!==0;this.awaitCapable=(this.responseFlags&I)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false};Response.prototype.isParsed=function(){return this.parsed};Response.prototype.parse=function(e){if(this.parsed)return;e=e||{};var t=e.raw||false;var r=e.documentsReturnedIn||null;var n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;var o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;var s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;var i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;var a,A;A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};this.index=20;for(var c=0;c{"use strict";const n=r(1808);const o=r(4404);const s=r(6096);const i=r(3111).MongoError;const a=r(3111).MongoNetworkError;const A=r(3111).MongoNetworkTimeoutError;const c=r(2192).defaultAuthProviders;const l=r(557).AuthContext;const u=r(7161);const h=r(1178).makeClientMetadata;const d=u.MAX_SUPPORTED_WIRE_VERSION;const g=u.MAX_SUPPORTED_SERVER_VERSION;const p=u.MIN_SUPPORTED_WIRE_VERSION;const E=u.MIN_SUPPORTED_SERVER_VERSION;let m;function connect(e,t,r){if(typeof t==="function"){r=t;t=undefined}const n=e&&e.connectionType?e.connectionType:s;if(m==null){m=c(e.bson)}const o=e.family!==void 0?e.family:0;makeConnection(o,e,t,((t,o)=>{if(t){r(t,o);return}performInitialHandshake(new n(o,e),e,r)}))}function isModernConnectionType(e){return!(e instanceof s)}function checkSupportedServer(e,t){const r=e&&typeof e.maxWireVersion==="number"&&e.maxWireVersion>=p;const n=e&&typeof e.minWireVersion==="number"&&e.minWireVersion<=d;if(r){if(n){return null}const r=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${g})`;return new i(r)}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 ${p} (MongoDB ${E})`;return new i(o)}function performInitialHandshake(e,t,r){const callback=function(t,n){if(t&&e){e.destroy()}r(t,n)};const n=t.credentials;if(n){if(!n.mechanism.match(/DEFAULT/i)&&!m[n.mechanism]){callback(new i(`authMechanism '${n.mechanism}' not supported`));return}}const o=new l(e,n,t);prepareHandshakeDocument(o,((r,s)=>{if(r){return callback(r)}const a=Object.assign({},t);if(t.connectTimeoutMS||t.connectionTimeout){a.socketTimeout=t.connectTimeoutMS||t.connectionTimeout}s.helloOk=!!t.useUnifiedTopology;const A=(new Date).getTime();e.command("admin.$cmd",s,a,((r,a)=>{if(r){callback(r);return}const c=a.result;if(c.ok===0){callback(new i(c));return}if("isWritablePrimary"in c){c.ismaster=c.isWritablePrimary}if(t.useUnifiedTopology&&c.helloOk){e.helloOk=true}const l=checkSupportedServer(c,t);if(l){callback(l);return}if(!isModernConnectionType(e)){if(c.compression){const r=s.compression.filter((e=>c.compression.indexOf(e)!==-1));if(r.length){e.agreedCompressor=r[0]}if(t.compression&&t.compression.zlibCompressionLevel){e.zlibCompressionLevel=t.compression.zlibCompressionLevel}}}e.ismaster=c;e.lastIsMasterMS=(new Date).getTime()-A;if(!c.arbiterOnly&&n){Object.assign(o,{response:c});const t=n.resolveAuthMechanism(c);const r=m[t.mechanism];r.auth(o,(t=>{if(t)return callback(t);callback(undefined,e)}));return}callback(undefined,e)}))}))}function prepareHandshakeDocument(e,t){const r=e.options;const n=e.connection.serverApi;const o=r.compression&&r.compression.compressors?r.compression.compressors:[];const s={[n?"hello":"ismaster"]:true,client:r.metadata||h(r),compression:o};const a=e.credentials;if(a){if(a.mechanism.match(/DEFAULT/i)&&a.username){Object.assign(s,{saslSupportedMechs:`${a.source}.${a.username}`});m["scram-sha-256"].prepare(s,e,t);return}const r=m[a.mechanism];if(r==null){return t(new i(`No AuthProvider for ${a.mechanism} defined.`))}r.prepare(s,e,t);return}t(undefined,s)}const C=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function parseConnectOptions(e,t){const r=typeof t.host==="string"?t.host:"localhost";if(r.indexOf("/")!==-1){return{path:r}}const n={family:e,host:r,port:typeof t.port==="number"?t.port:27017,rejectUnauthorized:false};return n}function parseSslOptions(e,t){const r=parseConnectOptions(e,t);for(const e in t){if(t[e]!=null&&C.indexOf(e)!==-1){r[e]=t[e]}}if(t.checkServerIdentity===false){r.checkServerIdentity=function(){return undefined}}else if(typeof t.checkServerIdentity==="function"){r.checkServerIdentity=t.checkServerIdentity}if(r.servername==null&&!n.isIP(r.host)){r.servername=r.host}return r}const I=new Set(["error","close","timeout","parseError"]);function makeConnection(e,t,r,s){const i=typeof t.ssl==="boolean"?t.ssl:false;const a=typeof t.keepAlive==="boolean"?t.keepAlive:true;let A=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;const c=typeof t.noDelay==="boolean"?t.noDelay:true;const l=typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:3e4;const u=typeof t.socketTimeoutMS==="number"?t.socketTimeoutMS:typeof t.socketTimeout==="number"?t.socketTimeout:0;const h=typeof t.rejectUnauthorized==="boolean"?t.rejectUnauthorized:true;if(A>u){A=Math.round(u/2)}let d;const callback=function(e,t){if(e&&d){d.destroy()}s(e,t)};try{if(i){d=o.connect(parseSslOptions(e,t));if(typeof d.disableRenegotiation==="function"){d.disableRenegotiation()}}else{d=n.createConnection(parseConnectOptions(e,t))}}catch(e){return callback(e)}d.setKeepAlive(a,A);d.setTimeout(l);d.setNoDelay(c);const g=i?"secureConnect":"connect";let p;function errorHandler(e){return t=>{I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}d.removeListener(g,connectHandler);callback(connectionFailureError(e,t))}}function connectHandler(){I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}if(d.authorizationError&&h){return callback(d.authorizationError)}d.setTimeout(u);callback(null,d)}I.forEach((e=>d.once(e,errorHandler(e))));if(r){p=errorHandler("cancel");r.once("cancel",p)}d.once(g,connectHandler)}function connectionFailureError(e,t){switch(e){case"error":return new a(t);case"timeout":return new A(`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.exports=connect},6096:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(6113);const s=r(7746).debugOptions;const i=r(7272).parseHeader;const a=r(7793).decompress;const A=r(9814).Response;const c=r(8988).BinMsg;const l=r(3111).MongoNetworkError;const u=r(3111).MongoNetworkTimeoutError;const h=r(3111).MongoError;const d=r(104);const g=r(7272).opcodes.OP_COMPRESSED;const p=r(7272).opcodes.OP_MSG;const E=r(7272).MESSAGE_HEADER_SIZE;const m=r(1867).Buffer;const C=r(9814).Query;const I=r(2337);let y=0;const B=1024*1024*16*4;const Q=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"];let b=undefined;let w=false;let S={};class Connection extends n{constructor(e,t){super();t=t||{};if(!t.bson){throw new TypeError("must pass in valid bson parser")}this.id=y++;this.options=t;this.logger=d("Connection",t);this.bson=t.bson;this.tag=t.tag;this.maxBsonMessageSize=t.maxBsonMessageSize||B;this.helloOk=undefined;this.port=t.port||27017;this.host=t.host||"localhost";this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.keepAlive=typeof t.keepAlive==="boolean"?t.keepAlive:true;this.keepAliveInitialDelay=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;this.connectionTimeout=typeof t.connectionTimeout==="number"?t.connectionTimeout:3e4;if(this.keepAliveInitialDelay>this.socketTimeout){this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)}if(this.logger.isDebug()){this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(Q,t))}]`)}this.responseOptions={promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false};this.flushing=false;this.queue=[];this.writeStream=null;this.destroyed=false;this.timedOut=false;const r=o.createHash("sha1");r.update(this.address);this.hashedName=r.digest("hex");this.workItems=[];this.socket=e;this.socket.once("error",errorHandler(this));this.socket.once("timeout",timeoutHandler(this));this.socket.once("close",closeHandler(this));this.socket.on("data",dataHandler(this));if(w){addConnection(this.id,this)}}setSocketTimeout(e){if(this.socket){this.socket.setTimeout(e)}}resetSocketTimeout(){if(this.socket){this.socket.setTimeout(this.socketTimeout)}}static enableConnectionAccounting(e){if(e){b=e}w=true;S={}}static disableConnectionAccounting(){w=false;b=undefined}static connections(){return S}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",(()=>this.socket.unref()));return}this.socket.unref()}flush(e){while(this.workItems.length>0){const t=this.workItems.shift();if(t.cb){t.cb(e)}}}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(w){deleteConnection(this.id)}if(this.socket==null){this.destroyed=true;return}if(e.force||this.timedOut){this.socket.destroy();this.destroyed=true;if(typeof t==="function")t(null,null);return}this.socket.end((e=>{this.destroyed=true;if(typeof t==="function")t(e,null)}))}write(e){if(this.logger.isDebug()){if(!Array.isArray(e)){this.logger.debug(`writing buffer [ ${e.length} ] to ${this.address}`)}else{for(let t=0;t{};function _callback(e,t){n(e,t);n=noop}function errorHandler(e){o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);if(e==null){e=new h(`runCommand failed for connection to '${o.address}'`)}o.on("error",noop);_callback(e)}function messageHandler(e){if(e.responseTo!==a.requestId){return}o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);e.parse({promoteValues:true});const t=e.documents[0];if(t.ok===0||t.$err||t.errmsg||t.code){_callback(new h(t));return}_callback(undefined,new I(t,this,e))}o.setSocketTimeout(s);v.forEach((e=>o.once(e,errorHandler)));o.on("message",messageHandler);o.write(a.toBin())}}const v=["error","close","timeout","parseError"];function deleteConnection(e){delete S[e];if(b){b.deleteConnection(e)}}function addConnection(e,t){S[e]=t;if(b){b.addConnection(e,t)}}function errorHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`)}e.emit("error",new l(t),e)}}function timeoutHandler(e){return function(){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] timed out`)}e.timedOut=true;e.emit("timeout",new u(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}function closeHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} with for [${e.address}] closed`)}if(!t){e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}}function processMessage(e,t){const r=i(t);if(r.opCode!==g){const n=r.opCode===p?c:A;e.emit("message",new n(e.bson,t,r,t.slice(E),e.responseOptions),e);return}r.fromCompressed=true;let n=E;r.opCode=t.readInt32LE(n);n+=4;r.length=t.readInt32LE(n);n+=4;const o=t[n];n++;a(o,t.slice(n),((n,o)=>{if(n){e.emit("error",n);return}if(o.length!==r.length){e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));return}const s=r.opCode===p?c:A;e.emit("message",new s(e.bson,t,r,o,e.responseOptions),e)}))}function dataHandler(e){return function(t){while(t.length>0){if(e.bytesRead>0&&e.sizeOfMessage>0){const r=e.sizeOfMessage-e.bytesRead;if(r>t.length){t.copy(e.buffer,e.bytesRead);e.bytesRead=e.bytesRead+t.length;t=m.alloc(0)}else{t.copy(e.buffer,e.bytesRead,0,r);t=t.slice(r);const n=e.buffer;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;processMessage(e,n)}}else{if(e.stubBuffer!=null&&e.stubBuffer.length>0){if(e.stubBuffer.length+t.length>4){const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=r;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null}else{const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=m.alloc(0)}}else{if(t.length>4){const r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",t,e);return}if(r>4&&rt.length){e.buffer=m.alloc(r);t.copy(e.buffer,0);e.bytesRead=t.length;e.sizeOfMessage=r;e.stubBuffer=null;t=m.alloc(0)}else if(r>4&&re.maxBsonMessageSize){const n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=m.alloc(0)}else{const n=t.slice(0,r);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=t.slice(r);processMessage(e,n)}}else{e.stubBuffer=m.alloc(t.length);t.copy(e.stubBuffer,0);t=m.alloc(0)}}}}}}e.exports=Connection},104:(e,t,r)=>{"use strict";var n=r(3837).format,o=r(3111).MongoError;var s={};var i={};var a=null;var A=process.pid;var c=null;var Logger=function(e,t){if(!(this instanceof Logger))return new Logger(e,t);t=t||{};this.className=e;if(t.logger){c=t.logger}else if(c==null){c=console.log}if(t.loggerLevel){a=t.loggerLevel||"error"}if(i[this.className]==null)s[this.className]=true};Logger.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","DEBUG",this.className,A,r,e);var a={type:"debug",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}};Logger.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","WARN",this.className,A,r,e);var a={type:"warn",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","INFO",this.className,A,r,e);var a={type:"info",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","ERROR",this.className,A,r,e);var a={type:"error",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.isInfo=function(){return a==="info"||a==="debug"},Logger.prototype.isError=function(){return a==="error"||a==="info"||a==="debug"},Logger.prototype.isWarn=function(){return a==="error"||a==="warn"||a==="info"||a==="debug"},Logger.prototype.isDebug=function(){return a==="debug"};Logger.reset=function(){a="error";i={}};Logger.currentLogger=function(){return c};Logger.setCurrentLogger=function(e){if(typeof e!=="function")throw new o("current logger must be a function");c=e};Logger.filter=function(e,t){if(e==="class"&&Array.isArray(t)){i={};t.forEach((function(e){i[e]=true}))}};Logger.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn"){throw new Error(n("%s is an illegal logging level",e))}a=e};e.exports=Logger},8988:(e,t,r)=>{"use strict";const n=r(1867).Buffer;const o=r(7272).opcodes;const s=r(7272).databaseNamespace;const i=r(4485);const a=r(3111).MongoError;let A=0;const c=1;const l=2;const u=1<<16;class Msg{constructor(e,t,r,n){if(r==null)throw new Error("query must be specified for query");this.bson=e;this.ns=t;this.command=r;this.command.$db=s(t);if(n.readPreference&&n.readPreference.mode!==i.PRIMARY){this.command.$readPreference=n.readPreference.toJSON()}this.options=n||{};this.requestId=n.requestId?n.requestId:Msg.getRequestId();this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checksumPresent=false;this.moreToCome=n.moreToCome||false;this.exhaustAllowed=typeof n.exhaustAllowed==="boolean"?n.exhaustAllowed:false}toBin(){const e=[];let t=0;if(this.checksumPresent){t|=c}if(this.moreToCome){t|=l}if(this.exhaustAllowed){t|=u}const r=n.alloc(4*4+4);e.push(r);let s=r.length;const i=this.command;s+=this.makeDocumentSegment(e,i);r.writeInt32LE(s,0);r.writeInt32LE(this.requestId,4);r.writeInt32LE(0,8);r.writeInt32LE(o.OP_MSG,12);r.writeUInt32LE(t,16);return e}makeDocumentSegment(e,t){const r=n.alloc(1);r[0]=0;const o=this.serializeBson(t);e.push(r);e.push(o);return r.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}Msg.getRequestId=function(){A=A+1&2147483647;return A};class BinMsg{constructor(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.checksumPresent=(this.responseFlags&c)!==0;this.moreToCome=(this.responseFlags&l)!==0;this.exhaustAllowed=(this.responseFlags&u)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false;this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{};this.index=4;const t=e.raw||false;const r=e.documentsReturnedIn||null;const n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;const o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;const s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;const i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;const A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};while(this.index{"use strict";const n=r(3837).inherits;const o=r(2361).EventEmitter;const s=r(3111).MongoError;const i=r(3111).MongoTimeoutError;const a=r(3111).MongoWriteConcernError;const A=r(104);const c=r(3837).format;const l=r(8988).Msg;const u=r(2337);const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(9815);const I=r(1867).Buffer;const y=r(6573);const B=r(5474).updateSessionFromResponse;const Q=r(1178).eachAsync;const b=r(1178).makeStateMachine;const w=r(1371).now;const S="disconnected";const v="connecting";const R="connected";const k="draining";const D="destroying";const N="destroyed";const T=b({[S]:[v,k,S],[v]:[v,R,k,S],[R]:[R,S,k],[k]:[k,D,N],[D]:[D,N],[N]:[N]});const O=new Set(["error","close","timeout","parseError","connect","message"]);var _=0;var Pool=function(e,t){o.call(this);this.topology=e;this.s={state:S,cancellationToken:new o};this.s.cancellationToken.setMaxListeners(Infinity);this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:true,keepAliveInitialDelay:12e4,noDelay:true,ssl:false,checkServerIdentity:true,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:false,promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false,reconnect:true,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:false,legacyCompatMode:true},t);this.id=_++;this.retriesLeft=this.options.reconnectTries;this.reconnectId=null;this.reconnectError=null;if(!t.bson||t.bson&&(typeof t.bson.serialize!=="function"||typeof t.bson.deserialize!=="function")){throw new Error("must pass in valid bson parser")}this.logger=A("Pool",t);this.availableConnections=[];this.inUseConnections=[];this.connectingConnections=0;this.executing=false;this.queue=[];this.numberOfConsecutiveTimeouts=0;this.connectionIndex=0;const r=this;this._messageHandler=messageHandler(this);this._connectionCloseHandler=function(e){const t=this;connectionFailureHandler(r,"close",e,t)};this._connectionErrorHandler=function(e){const t=this;connectionFailureHandler(r,"error",e,t)};this._connectionTimeoutHandler=function(e){const t=this;connectionFailureHandler(r,"timeout",e,t)};this._connectionParseErrorHandler=function(e){const t=this;connectionFailureHandler(r,"parseError",e,t)}};n(Pool,o);Object.defineProperty(Pool.prototype,"size",{enumerable:true,get:function(){return this.options.size}});Object.defineProperty(Pool.prototype,"minSize",{enumerable:true,get:function(){return this.options.minSize}});Object.defineProperty(Pool.prototype,"connectionTimeout",{enumerable:true,get:function(){return this.options.connectionTimeout}});Object.defineProperty(Pool.prototype,"socketTimeout",{enumerable:true,get:function(){return this.options.socketTimeout}});Object.defineProperty(Pool.prototype,"state",{enumerable:true,get:function(){return this.s.state}});function resetPoolState(e){e.inUseConnections=[];e.availableConnections=[];e.connectingConnections=0;e.executing=false;e.numberOfConsecutiveTimeouts=0;e.connectionIndex=0;e.retriesLeft=e.options.reconnectTries;e.reconnectId=null}function connectionFailureHandler(e,t,r,n){if(n){if(n._connectionFailHandled){return}n._connectionFailHandled=true;n.destroy();removeConnection(e,n);n.flush(r)}if(t==="timeout"){e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1;if(e.numberOfConsecutiveTimeouts>e.options.reconnectTries){e.numberOfConsecutiveTimeouts=0;e.destroy(true);return e.emit("close",e)}}if(e.socketCount()===0){if(e.state!==N&&e.state!==D&&e.state!==k){if(e.options.reconnect){T(e,S)}}t=t==="error"?"close":t;e.emit(t,r)}if(!e.reconnectId&&e.options.reconnect){e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e),e.options.reconnectInterval)}const o=totalConnectionCount(e);if(o{if(r==null){e.reconnectId=null;e.retriesLeft=e.options.reconnectTries;e.emit("reconnect",e)}if(typeof t==="function"){t(r,n)}}))}}function moveConnectionBetween(e,t,r){var n=t.indexOf(e);if(n!==-1){t.splice(n,1);r.push(e)}}function messageHandler(e){return function(t,r){var n=null;for(var o=0;o{if(t){if(typeof e==="function"){this.destroy();e(t);return}if(this.state===v){this.emit("error",t)}this.destroy();return}T(this,R);if(this.minSize){for(let e=0;e{for(const t of O){e.removeAllListeners(t)}e.on("error",(()=>{}));e.destroy(r,t)}),(t=>{if(t){if(typeof n==="function")n(t,null);return}resetPoolState(e);e.queue=[];T(e,N);if(typeof n==="function")n(null,null)}))}Pool.prototype.destroy=function(e,t){var r=this;if(typeof e==="function"){t=e;e=false}if(this.state===N||r.state===D){if(typeof t==="function")t(null,null);return}T(this,k);if(e){var n=r.availableConnections.concat(r.inUseConnections);while(r.queue.length>0){var o=r.queue.shift();if(typeof o.cb==="function"){o.cb(new s("Pool was force destroyed"))}}return destroy(r,n,{force:true},t)}if(this.reconnectId){clearTimeout(this.reconnectId)}function checkStatus(){if(r.state===N||r.state===D){if(typeof t==="function"){t()}return}flushMonitoringOperations(r.queue);if(r.queue.length===0){var e=r.availableConnections.concat(r.inUseConnections);for(var n=0;n0){return setTimeout(checkStatus,1)}}destroy(r,e,{force:false},t)}else{_execute(r)();setTimeout(checkStatus,1)}}checkStatus()};Pool.prototype.reset=function(e){if(this.s.state!==R){if(typeof e==="function"){e(new s("pool is not connected, reset aborted"))}return}this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);Q(t,((e,t)=>{for(const t of O){e.removeAllListeners(t)}e.destroy({force:true},t)}),(t=>{if(t){if(typeof e==="function"){e(t,null);return}}resetPoolState(this);createConnection(this,(()=>{if(typeof e==="function"){e(null,null)}}))}))};function serializeCommand(e,t,r){const n=t.toBin();const o=!!e.options.agreedCompressor;if(!o||!canCompress(t)){return r(null,n)}const s=I.concat(n);const i=s.slice(h);const a=s.readInt32LE(12);p(e,i,(function(n,o){if(n)return r(n,null);const s=I.alloc(h);s.writeInt32LE(h+d+o.length,0);s.writeInt32LE(t.requestId,4);s.writeInt32LE(0,8);s.writeInt32LE(g.OP_COMPRESSED,12);const A=I.alloc(d);A.writeInt32LE(a,0);A.writeInt32LE(i.length,4);A.writeUInt8(E[e.options.agreedCompressor],8);return r(null,[s,A,o])}))}Pool.prototype.write=function(e,t,r){var n=this;if(typeof t==="function"){r=t}t=t||{};if(!(typeof r==="function")&&!t.noResponse){throw new s("write method must provide a callback")}if(this.state===N||this.state===D){r(new s("pool destroyed"));return}if(this.state===k){r(new s("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r==="function"){var o=r;r=process.domain.bind((function(){var e=new Array(arguments.length);for(var t=0;t{if(t){n.emit("commandFailed",new C.CommandFailedEvent(this,e,t,i.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){n.emit("commandFailed",new C.CommandFailedEvent(this,e,o.result,i.started))}else{n.emit("commandSucceeded",new C.CommandSucceededEvent(this,e,o,i.started))}}if(typeof r==="function")r(t,o)}}serializeCommand(n,e,((e,r)=>{if(e)throw e;i.buffer=r;if(t.monitoring){n.queue.unshift(i)}else{n.queue.push(i)}if(!n.executing){process.nextTick((function(){_execute(n)()}))}}))};function canCompress(e){const t=e instanceof l?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function remove(e,t){for(var r=0;r{e.connectingConnections--;if(r){if(e.logger.isDebug()){e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`)}if(!e.reconnectId&&e.options.reconnect){if(e.state===v&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e,t),e.options.reconnectInterval);return}if(typeof t==="function"){t(r)}return}if(e.state===N||e.state===D){if(typeof t==="function"){t(new s("Pool was destroyed after connection creation"))}n.destroy();return}n.on("error",e._connectionErrorHandler);n.on("close",e._connectionCloseHandler);n.on("timeout",e._connectionTimeoutHandler);n.on("parseError",e._connectionParseErrorHandler);n.on("message",e._messageHandler);e.availableConnections.push(n);if(typeof t==="function"){t(null,n)}_execute(e)()}))}function flushMonitoringOperations(e){for(var t=0;t0){e.executing=false;return}while(true){const i=totalConnectionCount(e);if(e.availableConnections.length===0){flushMonitoringOperations(e.queue);if(i0){createConnection(e)}break}if(e.queue.length===0){break}var t=null;const a=e.availableConnections.filter((e=>e.workItems.length===0));if(a.length===0){t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]}else{t=a[e.connectionIndex++%a.length]}if(!t.isConnected()){removeConnection(e,t);flushMonitoringOperations(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=false;for(let r=0;r0){createConnection(e)}setTimeout((()=>_execute(e)()),10);break}}if(i0){e.queue.unshift(r);createConnection(e);break}}var o=r.buffer;if(r.monitoring){moveConnectionBetween(t,e.availableConnections,e.inUseConnections)}if(!r.noResponse){t.workItems.push(r)}if(!r.immediateRelease&&typeof r.socketTimeout==="number"){t.setSocketTimeout(r.socketTimeout)}var s=true;if(Array.isArray(o)){for(let e=0;e{"use strict";const n=r(1371).parsePackageVersion;const o=r(3111).MongoError;const s=r(3182)(require);function debugOptions(e,t){const r={};e.forEach((function(e){r[e]=t[e]}));return r}function retrieveBSON(){const e=r(4044);e.native=false;const t=s("bson-ext");const i=n(s("bson-ext/package.json")||{version:"0.0.0"});if(t){if(i.major>=4){throw new o("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver")}t.native=true;return t}return e}function noSnappyWarning(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}const i=Symbol("kPkgVersion");function retrieveSnappy(){const e=s("snappy");if(!e){return{compress:noSnappyWarning,uncompress:noSnappyWarning,compressSync:noSnappyWarning,uncompressSync:noSnappyWarning}}const t=s("snappy/package.json")||{version:"0.0.0"};const r=n(t);e[i]=r;if(r.major>=7){const t=e.compress;const r=e.uncompress;e.compress=(e,r)=>{t(e).then((e=>r(undefined,e))).catch((e=>r(e)))};e.uncompress=(e,t)=>{r(e).then((e=>t(undefined,e))).catch((e=>t(e)))}}return e}e.exports={PKG_VERSION:i,debugOptions:debugOptions,retrieveBSON:retrieveBSON,retrieveSnappy:retrieveSnappy}},4847:(e,t,r)=>{"use strict";const n=r(104);const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(1178).collationNotSupported;const A=r(4485);const c=r(1178).isUnifiedTopology;const l=r(2548);const u=r(2781).Readable;const h=r(1371).SUPPORTS;const d=r(1371).MongoDBNamespace;const g=r(1371).mergeOptions;const p=r(1018).OperationBase;const E=o();const m=E.Long;const C={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function handleCallback(e,t,r){try{e(t,r)}catch(t){process.nextTick((function(){throw t}))}}class CoreCursor extends u{constructor(e,t,r,o){super({objectMode:true});o=o||{};if(t instanceof p){this.operation=t;t=this.operation.ns.toString();o=this.operation.options;r=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=d.fromString(t);this.cmd=r;this.options=o;this.topology=e;this.cursorState={cursorId:null,cmd:r,documents:o.documents||[],cursorIndex:0,dead:false,killed:false,init:false,notified:false,limit:o.limit||r.limit||0,skip:o.skip||r.skip||0,batchSize:o.batchSize||r.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||r&&r.raw};if(typeof o.session==="object"){this.cursorState.session=o.session}const s=e.s.options;if(typeof s.promoteLongs==="boolean"){this.cursorState.promoteLongs=s.promoteLongs}else if(typeof o.promoteLongs==="boolean"){this.cursorState.promoteLongs=o.promoteLongs}if(typeof s.promoteValues==="boolean"){this.cursorState.promoteValues=s.promoteValues}else if(typeof o.promoteValues==="boolean"){this.cursorState.promoteValues=o.promoteValues}if(typeof s.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=s.promoteBuffers}else if(typeof o.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=o.promoteBuffers}if(typeof s.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=s.bsonRegExp}else if(typeof o.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=o.bsonRegExp}if(s.reconnect){this.cursorState.reconnect=s.reconnect}this.logger=n("Cursor",s);if(typeof r==="number"){this.cursorState.cursorId=m.fromNumber(r);this.cursorState.lastCursorId=this.cursorState.cursorId}else if(r instanceof m){this.cursorState.cursorId=r;this.cursorState.lastCursorId=r}if(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){nextFunction(this,e)}clone(){const e=g({},this.options);delete e.session;return this.topology.cursor(this.ns,this.cmd,e)}isDead(){return this.cursorState.dead===true}isKilled(){return this.cursorState.killed===true}isNotified(){return this.cursorState.notified===true}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex;const r=e0&&this.cursorState.currentLimit+n.length>this.cursorState.limit){n=n.slice(0,this.cursorState.limit-this.cursorState.currentLimit);this.kill()}this.cursorState.currentLimit=this.cursorState.currentLimit+n.length;this.cursorState.cursorIndex=this.cursorState.cursorIndex+n.length;return n}kill(e){this.cursorState.dead=true;this.cursorState.killed=true;this.cursorState.documents=[];if(this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===false){if(e)e(null,null);return}this.server.killCursors(this.ns,this.cursorState,e)}rewind(){if(this.cursorState.init){if(!this.cursorState.dead){this.kill()}this.cursorState.currentLimit=0;this.cursorState.init=false;this.cursorState.dead=false;this.cursorState.killed=false;this.cursorState.notified=false;this.cursorState.documents=[];this.cursorState.cursorId=null;this.cursorState.cursorIndex=0}}_read(){if(this.s&&this.s.state===C.CLOSED||this.isDead()){return this.push(null)}this._next(((e,t)=>{if(e){if(this.listeners("error")&&this.listeners("error").length>0){this.emit("error",e)}if(!this.isDead())this.close();this.emit("end");return this.emit("finish")}if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform==="function"&&t!=null){return this.push(this.cursorState.streamOptions.transform(t))}this.push(t);if(t===null&&this.isDead()){this.once("end",(()=>{this.close();this.emit("finish")}))}}))}_endSession(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};const r=this.cursorState.session;if(r&&(e.force||r.owner===this)){this.cursorState.session=undefined;if(this.operation){this.operation.clearSession()}r.endSession(t);return true}if(t){t()}return false}_getMore(e){if(this.logger.isDebug()){this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`)}let t=this.cursorState.batchSize;if(this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit){t=this.cursorState.limit-this.cursorState.currentLimit}const r=this.cursorState;this.server.getMore(this.ns,r,t,this.options,((t,n,o)=>{if(t||r.cursorId&&r.cursorId.isZero()){this._endSession()}e(t,n,o)}))}_initializeCursor(e){const t=this;if(c(t.topology)&&t.topology.shouldCheckForSessionSupport()){t.topology.selectServer(A.primaryPreferred,(t=>{if(t){e(t);return}this._initializeCursor(e)}));return}function done(r,n){const o=t.cursorState;if(r||o.cursorId&&o.cursorId.isZero()){t._endSession()}if(o.documents.length===0&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData){return setCursorNotified(t,e)}e(r,n)}const queryCallback=(e,r)=>{if(e){return done(e)}const n=r.message;if(Array.isArray(n.documents)&&n.documents.length===1){const e=n.documents[0];if(n.queryFailure){return done(new s(e),null)}if(!t.cmd.find||t.cmd.find&&t.cmd.virtual===false){if(e.$err||e.errmsg){return done(new s(e),null)}if(e.cursor!=null&&typeof e.cursor!=="string"){const r=e.cursor.id;if(e.cursor.ns){t.ns=e.cursor.ns}t.cursorState.cursorId=typeof r==="number"?m.fromNumber(r):r;t.cursorState.lastCursorId=t.cursorState.cursorId;t.cursorState.operationTime=e.operationTime;if(Array.isArray(e.cursor.firstBatch)){t.cursorState.documents=e.cursor.firstBatch}return done(null,n)}}}const o=n.cursorId||0;t.cursorState.cursorId=o instanceof m?o:m.fromNumber(o);t.cursorState.documents=n.documents;t.cursorState.lastCursorId=n.cursorId;if(t.cursorState.transforms&&typeof t.cursorState.transforms.query==="function"){t.cursorState.documents=t.cursorState.transforms.query(n)}done(null,n)};if(t.operation){if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}l(t.topology,t.operation,((e,r)=>{if(e){done(e);return}t.server=t.operation.server;t.cursorState.init=true;if(t.cursorState.cursorId!=null){return done()}queryCallback(e,r)}));return}const r={};if(t.cursorState.session){r.session=t.cursorState.session}if(t.operation){r.readPreference=t.operation.readPreference}else if(t.options.readPreference){r.readPreference=t.options.readPreference}return t.topology.selectServer(r,((r,n)=>{if(r){const n=t.disconnectHandler;if(n!=null){return n.addObjectAndMethod("cursor",t,"next",[e],e)}return e(r)}t.server=n;t.cursorState.init=true;if(a(t.server,t.cmd)){return e(new s(`server ${t.server.name} does not support collation`))}if(t.cursorState.cursorId!=null){return done()}if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}if(t.cmd.find!=null){n.query(t.ns,t.cmd,t.cursorState,t.options,queryCallback);return}const o=Object.assign({session:t.cursorState.session},t.options);n.command(t.ns,t.cmd,o,queryCallback)}))}}if(h.ASYNC_ITERATOR){CoreCursor.prototype[Symbol.asyncIterator]=r(1749).asyncIterator}function isConnectionDead(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=true;const r=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);_setCursorNotifiedImpl(e,(()=>t(r)));return true}return false}function isCursorDeadButNotkilled(e,t){if(e.cursorState.dead&&!e.cursorState.killed){e.cursorState.killed=true;setCursorNotified(e,t);return true}return false}function isCursorDeadAndKilled(e,t){if(e.cursorState.dead&&e.cursorState.killed){handleCallback(t,new s("cursor is dead"));return true}return false}function isCursorKilled(e,t){if(e.cursorState.killed){setCursorNotified(e,t);return true}return false}function setCursorDeadAndNotified(e,t){e.cursorState.dead=true;setCursorNotified(e,t)}function setCursorNotified(e,t){_setCursorNotifiedImpl(e,(()=>handleCallback(t,null,null)))}function _setCursorNotifiedImpl(e,t){e.cursorState.notified=true;e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.cursorState.session){e._endSession(t);return}return t()}function nextFunction(e,t){if(e.cursorState.notified){return t(new Error("cursor is exhausted"))}if(isCursorKilled(e,t))return;if(isCursorDeadButNotkilled(e,t))return;if(isCursorDeadAndKilled(e,t))return;if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect){return t(new s("no connection available"))}if(e.disconnectHandler!=null){if(e.topology.isDestroyed()){return t(new s("Topology was destroyed"))}e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor(((r,n)=>{if(r||n===null){t(r,n);return}nextFunction(e,t)}));return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)))}else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!m.ZERO.equals(e.cursorState.cursorId)){e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.topology.isDestroyed())return t(new i("connection destroyed, not possible to instantiate cursor"));if(isConnectionDead(e,t))return;e._getMore((function(r,n,o){if(r){return handleCallback(t,r)}e.connection=o;if(e.cursorState.documents.length===0&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===0&&e.cmd.tailable&&!m.ZERO.equals(e.cursorState.cursorId)){return nextFunction(e,t)}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){return setCursorDeadAndNotified(e,t)}nextFunction(e,t)}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&m.ZERO.equals(e.cursorState.cursorId)){setCursorDeadAndNotified(e,t)}else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill((()=>setCursorDeadAndNotified(e,(function(){handleCallback(t,new s(r?r.$err:undefined))}))));return}if(e.cursorState.transforms&&typeof e.cursorState.transforms.doc==="function"){r=e.cursorState.transforms.doc(r)}handleCallback(t,null,r)}}e.exports={CursorState:C,CoreCursor:CoreCursor}},3111:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=Symbol("errorLabels");class MongoError extends Error{constructor(e){if(e instanceof Error){super(e.message);this.stack=e.stack}else{if(typeof e==="string"){super(e)}else{super(e.message||e.errmsg||e.$err||"n/a");if(e.errorLabels){this[o]=new Set(e.errorLabels)}for(var t in e){if(t==="errorLabels"||t==="errmsg"){continue}this[t]=e[t]}}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new MongoError(e)}hasErrorLabel(e){if(this[o]==null){return false}return this[o].has(e)}addErrorLabel(e){if(this[o]==null){this[o]=new Set}this[o].add(e)}get errorLabels(){return this[o]?Array.from(this[o]):[]}}const s=Symbol("beforeHandshake");function isNetworkErrorBeforeHandshake(e){return e[s]===true}class MongoNetworkError extends MongoError{constructor(e,t){super(e);this.name="MongoNetworkError";if(t&&typeof t.beforeHandshake==="boolean"){this[s]=t.beforeHandshake}}}class MongoNetworkTimeoutError extends MongoNetworkError{constructor(e,t){super(e,t);this.name="MongoNetworkTimeoutError"}}class MongoParseError extends MongoError{constructor(e){super(e);this.name="MongoParseError"}}class MongoTimeoutError extends MongoError{constructor(e,t){if(t&&t.error){super(t.error.message||t.error)}else{super(e)}this.name="MongoTimeoutError";if(t){this.reason=t}}}class MongoServerSelectionError extends MongoTimeoutError{constructor(e,t){super(e,t);this.name="MongoServerSelectionError"}}function makeWriteConcernResultObject(e){const t=Object.assign({},e);if(t.ok===0){t.ok=1;delete t.errmsg;delete t.code;delete t.codeName}return t}class MongoWriteConcernError extends MongoError{constructor(e,t){super(e);this.name="MongoWriteConcernError";if(t&&Array.isArray(t.errorLabels)){this[o]=new Set(t.errorLabels)}if(t!=null){this.result=makeWriteConcernResultObject(t)}}}const i=new Set([n.HostUnreachable,n.HostNotFound,n.NetworkTimeout,n.ShutdownInProgress,n.PrimarySteppedDown,n.SocketException,n.NotMaster,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary]);const a=new Set([n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMaster,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary,n.PrimarySteppedDown,n.ShutdownInProgress,n.HostNotFound,n.HostUnreachable,n.NetworkTimeout,n.SocketException,n.ExceededTimeLimit]);function isRetryableEndTransactionError(e){return e.hasErrorLabel("RetryableWriteError")}function isRetryableWriteError(e){if(e instanceof MongoWriteConcernError){return a.has(e.code)||a.has(e.result.code)}return a.has(e.code)}function isRetryableError(e){return i.has(e.code)||e instanceof MongoNetworkError||e.message.match(/not master/)||e.message.match(/node is recovering/)}const A=new Set([n.ShutdownInProgress,n.PrimarySteppedDown,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterOrSecondary]);const c=new Set([n.NotMaster,n.NotMasterNoSlaveOk,n.LegacyNotPrimary]);const l=new Set([n.InterruptedAtShutdown,n.ShutdownInProgress]);function isRecoveringError(e){if(typeof e.code==="number"){return A.has(e.code)}return/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}function isNotMasterError(e){if(typeof e.code==="number"){return c.has(e.code)}if(isRecoveringError(e)){return false}return/not master/.test(e.message)}function isNodeShuttingDownError(e){return e.code&&l.has(e.code)}function isSDAMUnrecoverableError(e){if(e instanceof MongoParseError||e==null){return true}return isRecoveringError(e)||isNotMasterError(e)}e.exports={MongoError:MongoError,MongoNetworkError:MongoNetworkError,MongoNetworkTimeoutError:MongoNetworkTimeoutError,MongoParseError:MongoParseError,MongoTimeoutError:MongoTimeoutError,MongoServerSelectionError:MongoServerSelectionError,MongoWriteConcernError:MongoWriteConcernError,isRetryableError:isRetryableError,isSDAMUnrecoverableError:isSDAMUnrecoverableError,isNodeShuttingDownError:isNodeShuttingDownError,isRetryableWriteError:isRetryableWriteError,isNetworkErrorBeforeHandshake:isNetworkErrorBeforeHandshake,isRetryableEndTransactionError:isRetryableEndTransactionError}},3994:(e,t,r)=>{"use strict";let n=r(4044);const o=r(3182)(require);const s=r(1178).retrieveEJSON();try{const e=o("bson-ext");if(e){n=e}}catch(e){}const i=Object.freeze({v1:"1"});const a=Object.keys(i).map((e=>i[e]));e.exports={ServerApiVersion:i,ValidServerApiVersions:a,MongoError:r(3111).MongoError,MongoNetworkError:r(3111).MongoNetworkError,MongoParseError:r(3111).MongoParseError,MongoTimeoutError:r(3111).MongoTimeoutError,MongoServerSelectionError:r(3111).MongoServerSelectionError,MongoWriteConcernError:r(3111).MongoWriteConcernError,Connection:r(6096),Server:r(6495),ReplSet:r(1134),Mongos:r(8175),Logger:r(104),Cursor:r(4847).CoreCursor,ReadPreference:r(4485),Sessions:r(5474),BSON:n,EJSON:s,Topology:r(4149).Topology,Query:r(9814).Query,MongoCredentials:r(2222).MongoCredentials,defaultAuthProviders:r(2192).defaultAuthProviders,MongoCR:r(4228),X509:r(7324),Plain:r(8728),GSSAPI:r(2640),ScramSHA1:r(864).ScramSHA1,ScramSHA256:r(864).ScramSHA256,parseConnectionString:r(8767)}},2291:e=>{"use strict";const t="closing";const r="closed";const n="connecting";const o="connected";const s={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};const i={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function serverType(e){let t=e.s.description||e.s.serverDescription;if(t.topologyType===s.Single)return t.servers[0].type;return t.type}const a={useUnifiedTopology:true,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function drainTimerQueue(e){e.forEach(clearTimeout);e.clear()}function clearAndRemoveTimerFrom(e,t){clearTimeout(e);return t.delete(e)}e.exports={STATE_CLOSING:t,STATE_CLOSED:r,STATE_CONNECTING:n,STATE_CONNECTED:o,TOPOLOGY_DEFAULTS:a,TopologyType:s,ServerType:i,serverType:serverType,drainTimerQueue:drainTimerQueue,clearAndRemoveTimerFrom:clearAndRemoveTimerFrom}},2785:e=>{"use strict";class ServerDescriptionChangedEvent{constructor(e,t,r,n){Object.assign(this,{topologyId:e,address:t,previousDescription:r,newDescription:n})}}class ServerOpeningEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class ServerClosedEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class TopologyDescriptionChangedEvent{constructor(e,t,r){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:r})}}class TopologyOpeningEvent{constructor(e){Object.assign(this,{topologyId:e})}}class TopologyClosedEvent{constructor(e){Object.assign(this,{topologyId:e})}}class ServerHeartbeatStartedEvent{constructor(e){Object.assign(this,{connectionId:e})}}class ServerHeartbeatSucceededEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,reply:t})}}class ServerHeartbeatFailedEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,failure:t})}}e.exports={ServerDescriptionChangedEvent:ServerDescriptionChangedEvent,ServerOpeningEvent:ServerOpeningEvent,ServerClosedEvent:ServerClosedEvent,TopologyDescriptionChangedEvent:TopologyDescriptionChangedEvent,TopologyOpeningEvent:TopologyOpeningEvent,TopologyClosedEvent:TopologyClosedEvent,ServerHeartbeatStartedEvent:ServerHeartbeatStartedEvent,ServerHeartbeatSucceededEvent:ServerHeartbeatSucceededEvent,ServerHeartbeatFailedEvent:ServerHeartbeatFailedEvent}},1203:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(2361);const s=r(6573);const i=r(9820).Connection;const a=r(2291);const A=r(1178).makeStateMachine;const c=r(3111).MongoNetworkError;const l=r(7746).retrieveBSON();const u=r(1371).makeInterruptableAsyncInterval;const h=r(1371).calculateDurationInMs;const d=r(1371).now;const g=r(2785);const p=g.ServerHeartbeatStartedEvent;const E=g.ServerHeartbeatSucceededEvent;const m=g.ServerHeartbeatFailedEvent;const C=Symbol("server");const I=Symbol("monitorId");const y=Symbol("connection");const B=Symbol("cancellationToken");const Q=Symbol("rttPinger");const b=Symbol("roundTripTime");const w=a.STATE_CLOSED;const S=a.STATE_CLOSING;const v="idle";const R="monitoring";const k=A({[S]:[S,v,w],[w]:[w,R],[v]:[v,R,S],[R]:[R,v,S]});const D=new Set([S,w,R]);function isInCloseState(e){return e.s.state===w||e.s.state===S}class Monitor extends o{constructor(e,t){super(t);this[C]=e;this[y]=undefined;this[B]=new o;this[B].setMaxListeners(Infinity);this[I]=null;this.s={state:w};this.address=e.description.address;this.options=Object.freeze({connectTimeoutMS:typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof t.heartbeatFrequencyMS==="number"?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof t.minHeartbeatFrequencyMS==="number"?t.minHeartbeatFrequencyMS:500,useUnifiedTopology:t.useUnifiedTopology});const r=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:false,promoteLongs:true,promoteValues:true,promoteBuffers:true,bsonRegExp:true});delete r.credentials;delete r.autoEncrypter;this.connectOptions=Object.freeze(r)}connect(){if(this.s.state!==w){return}const e=this.options.heartbeatFrequencyMS;const t=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:e,minInterval:t,immediate:true})}requestCheck(){if(D.has(this.s.state)){return}this[I].wake()}reset(){const e=this[C].description.topologyVersion;if(isInCloseState(this)||e==null){return}k(this,S);resetMonitorState(this);k(this,v);const t=this.options.heartbeatFrequencyMS;const r=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:t,minInterval:r})}close(){if(isInCloseState(this)){return}k(this,S);resetMonitorState(this);this.emit("close");k(this,w)}}function resetMonitorState(e){if(e[I]){e[I].stop();e[I]=null}if(e[Q]){e[Q].close();e[Q]=undefined}e[B].emit("cancel");if(e[I]){clearTimeout(e[I]);e[I]=undefined}if(e[y]){e[y].destroy({force:true})}}function checkServer(e,t){let r=d();e.emit("serverHeartbeatStarted",new p(e.address));function failureHandler(n){if(e[y]){e[y].destroy({force:true});e[y]=undefined}e.emit("serverHeartbeatFailed",new m(h(r),n,e.address));e.emit("resetServer",n);e.emit("resetConnectionPool");t(n)}if(e[y]!=null&&!e[y].closed){const n=e.options.connectTimeoutMS;const o=e.options.heartbeatFrequencyMS;const s=e[C].description.topologyVersion;const i=s!=null;const a=e[y].serverApi;const A=e[y].helloOk;const c={[a||A?"hello":"ismaster"]:true};if(A)c.helloOk=A;const l={socketTimeout:n};if(i){c.maxAwaitTimeMS=o;c.topologyVersion=makeTopologyVersion(s);if(n){l.socketTimeout=n+o}l.exhaustAllowed=true;if(e[Q]==null){e[Q]=new RTTPinger(e[B],e.connectOptions)}}e[y].command("admin.$cmd",c,l,((n,o)=>{if(n){failureHandler(n);return}const s=o.result;const a=e[Q];if("isWritablePrimary"in s){s.ismaster=s.isWritablePrimary}const A=i&&a?a.roundTripTime:h(r);e.emit("serverHeartbeatSucceeded",new E(A,s,e.address));if(i&&s.topologyVersion){e.emit("serverHeartbeatStarted",new p(e.address));r=d()}else{if(e[Q]){e[Q].close();e[Q]=undefined}t(undefined,s)}}));return}s(e.connectOptions,e[B],((n,o)=>{if(o&&isInCloseState(e)){o.destroy({force:true});return}if(n){e[y]=undefined;if(!(n instanceof c)){e.emit("resetConnectionPool")}failureHandler(n);return}e[y]=o;e.emit("serverHeartbeatSucceeded",new E(h(r),o.ismaster,e.address));t(undefined,o.ismaster)}))}function monitorServer(e){return t=>{k(e,R);function done(){if(!isInCloseState(e)){k(e,v)}t()}process.nextTick((()=>e.emit("monitoring",e[C])));checkServer(e,((t,r)=>{if(t){if(e[C].description.type===n.Unknown){e.emit("resetServer",t);return done()}}if(r&&r.topologyVersion){setTimeout((()=>{if(!isInCloseState(e)){e[I].wake()}}))}done()}))}}function makeTopologyVersion(e){return{processId:e.processId,counter:l.Long.fromNumber(e.counter)}}class RTTPinger{constructor(e,t){this[y]=null;this[B]=e;this[b]=0;this.closed=false;const r=t.heartbeatFrequencyMS;this[I]=setTimeout((()=>measureRoundTripTime(this,t)),r)}get roundTripTime(){return this[b]}close(){this.closed=true;clearTimeout(this[I]);this[I]=undefined;if(this[y]){this[y].destroy({force:true})}}}function measureRoundTripTime(e,t){const r=d();const n=e[B];const o=t.heartbeatFrequencyMS;if(e.closed){return}function measureAndReschedule(n){if(e.closed){n.destroy({force:true});return}if(e[y]==null){e[y]=n}e[b]=h(r);e[I]=setTimeout((()=>measureRoundTripTime(e,t)),o)}if(e[y]==null){s(t,n,((t,r)=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule(r)}));return}e[y].command("admin.$cmd",{ismaster:1},(t=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule()}))}e.exports={Monitor:Monitor}},7062:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2529).ConnectionPool;const s=r(897).CMAP_EVENT_NAMES;const i=r(3111).MongoError;const a=r(1178).relayEvents;const A=r(7746).retrieveBSON();const c=r(104);const l=r(750).ServerDescription;const u=r(750).compareTopologyVersion;const h=r(4485);const d=r(1203).Monitor;const g=r(3111).MongoNetworkError;const p=r(3111).MongoNetworkTimeoutError;const E=r(1178).collationNotSupported;const m=r(7746).debugOptions;const C=r(3111).isSDAMUnrecoverableError;const I=r(3111).isRetryableWriteError;const y=r(3111).isNodeShuttingDownError;const B=r(3111).isNetworkErrorBeforeHandshake;const Q=r(1178).maxWireVersion;const b=r(1178).makeStateMachine;const w=r(7703).extractCommand;const S=r(2291);const v=S.ServerType;const R=r(1707).isTransactionCommand;const k=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];const D=S.STATE_CLOSING;const N=S.STATE_CLOSED;const T=S.STATE_CONNECTING;const O=S.STATE_CONNECTED;const _=b({[N]:[N,T],[T]:[T,D,O,N],[O]:[O,D,N],[D]:[D,N]});const M=Symbol("monitor");class Server extends n{constructor(e,t,r){super();this.s={description:e,options:t,logger:c("Server",t),bson:t.bson||new A([A.Binary,A.Code,A.DBRef,A.Decimal128,A.Double,A.Int32,A.Long,A.Map,A.MaxKey,A.MinKey,A.ObjectId,A.BSONRegExp,A.Symbol,A.Timestamp]),state:N,credentials:t.credentials,topology:r};this.serverApi=t.serverApi;const n=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(n);a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s));this.s.pool.on("clusterTimeReceived",(e=>{this.clusterTime=e}));this[M]=new d(this,this.s.options);a(this[M],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]);this[M].on("resetConnectionPool",(()=>{this.s.pool.clear()}));this[M].on("resetServer",(e=>markServerUnknown(this,e)));this[M].on("serverHeartbeatSucceeded",(e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:calculateRoundTripTime(this.description.roundTripTime,e.duration)}));if(this.s.state===T){_(this,O);this.emit("connect",this)}}))}get description(){return this.s.description}get supportsRetryableWrites(){return supportsRetryableWrites(this)}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter){return this.s.options.autoEncrypter}return null}connect(){if(this.s.state!==N){return}_(this,T);this[M].connect()}destroy(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{force:false},e);if(this.s.state===N){if(typeof t==="function"){t()}return}_(this,D);this[M].close();this.s.pool.close(e,(e=>{_(this,N);this.emit("closed");if(typeof t==="function"){t(e)}}))}requestCheck(){this[M].requestCheck()}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}r.serverApi=this.serverApi;if(this.s.state===D||this.s.state===N){n(new i("server is closed"));return}const o=basicReadValidations(this,r);if(o){return n(o)}r=Object.assign({},r,{wireProtocolCommand:false});if(this.s.logger.isDebug()){const n=w(t);this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:m(k,r)})}] against ${this.name}`)}if(E(this,t)){n(new i(`server ${this.name} does not support collation`));return}this.s.pool.withConnection(((n,o,s)=>{if(n){markServerUnknown(this,n);return s(n)}o.command(e,t,r,makeOperationHandler(this,o,t,r,s))}),n)}query(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.query(e,t,r,n,makeOperationHandler(this,s,t,n,i))}),o)}getMore(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.getMore(e,t,r,n,makeOperationHandler(this,s,null,n,i))}),o)}killCursors(e,t,r){if(this.s.state===D||this.s.state===N){if(typeof r==="function"){r(new i("server is closed"))}return}this.s.pool.withConnection(((r,n,o)=>{if(r){markServerUnknown(this,r);return o(r)}n.killCursors(e,t,makeOperationHandler(this,n,null,undefined,o))}),r)}insert(e,t,r,n){executeWriteOperation({server:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({server:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({server:this,op:"remove",ns:e,ops:t},r,n)}}Object.defineProperty(Server.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function supportsRetryableWrites(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==v.Standalone}function calculateRoundTripTime(e,t){if(e===-1){return t}const r=.2;return r*t+(1-r)*e}function basicReadValidations(e,t){if(t.readPreference&&!(t.readPreference instanceof h)){return new i("readPreference must be an instance of ReadPreference")}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.server;const o=e.op;const s=e.ns;const a=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===D||n.s.state===N){r(new i("server is closed"));return}if(E(n,t)){r(new i(`server ${n.name} does not support collation`));return}const A=t.writeConcern&&t.writeConcern.w===0;if(A||Q(n)<5){if((o==="update"||o==="remove")&&a.find((e=>e.hint))){r(new i(`servers < 3.4 do not support hint on ${o}`));return}}n.s.pool.withConnection(((e,r,i)=>{if(e){markServerUnknown(n,e);return i(e)}r[o](s,a,t,makeOperationHandler(n,r,a,t,i))}),r)}function markServerUnknown(e,t){if(t instanceof g&&!(t instanceof p)){e[M].reset()}e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function connectionIsStale(e,t){return t.generation!==e.generation}function shouldHandleStateChangeError(e,t){const r=t.topologyVersion;const n=e.description.topologyVersion;return u(n,r)<0}function inActiveTransaction(e,t){return e&&e.inTransaction()&&!R(t)}function makeOperationHandler(e,t,r,n,o){const s=n&&n.session;return function handleOperationResult(n,i){if(n&&!connectionIsStale(e.s.pool,t)){if(n instanceof g){if(s&&!s.hasEnded){s.serverSession.isDirty=true}if(supportsRetryableWrites(e)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(!(n instanceof p)||B(n)){markServerUnknown(e,n);e.s.pool.clear()}}else{if(Q(e)<9&&I(n)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(C(n)){if(shouldHandleStateChangeError(e,n)){if(Q(e)<=7||y(n)){e.s.pool.clear()}markServerUnknown(e,n);process.nextTick((()=>e.requestCheck()))}}}}o(n,i)}}e.exports={Server:Server}},750:(e,t,r)=>{"use strict";const n=r(1178).arrayStrictEqual;const o=r(1178).tagsStrictEqual;const s=r(1178).errorStrictEqual;const i=r(2291).ServerType;const a=r(1371).now;const A=new Set([i.RSPrimary,i.Standalone,i.Mongos]);const c=new Set([i.RSPrimary,i.RSSecondary,i.Mongos,i.Standalone]);const l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];class ServerDescription{constructor(e,t,r){r=r||{};t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t);if(t.isWritablePrimary!=null){t.ismaster=t.isWritablePrimary}this.address=e;this.error=r.error;this.roundTripTime=r.roundTripTime||-1;this.lastUpdateTime=a();this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null;this.opTime=t.lastWrite?t.lastWrite.opTime:null;this.type=parseServerType(t);this.topologyVersion=r.topologyVersion||t.topologyVersion;l.forEach((e=>{if(typeof t[e]!=="undefined")this[e]=t[e]}));if(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 c.has(this.type)}get isWritable(){return A.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||compareTopologyVersion(this.topologyVersion,e.topologyVersion)===0;return e!=null&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&n(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}}function parseServerType(e){if(!e||!e.ok){return i.Unknown}if(e.isreplicaset){return i.RSGhost}if(e.msg&&e.msg==="isdbgrid"){return i.Mongos}if(e.setName){if(e.hidden){return i.RSOther}else if(e.ismaster){return i.RSPrimary}else if(e.secondary){return i.RSSecondary}else if(e.arbiterOnly){return i.RSArbiter}else{return i.RSOther}}return i.Standalone}function compareTopologyVersion(e,t){if(e==null||t==null){return-1}if(e.processId.equals(t.processId)){if(e.counter===t.counter){return 0}else if(e.counter{"use strict";const n=r(2291).ServerType;const o=r(2291).TopologyType;const s=r(4485);const i=r(3111).MongoError;const a=1e4;const A=90;function writableServerSelector(){return function(e,t){return latencyWindowReducer(e,t.filter((e=>e.isWritable)))}}function maxStalenessReducer(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0){return r}const n=e.maxStalenessSeconds;const s=(t.heartbeatFrequencyMS+a)/1e3;if(n{const s=o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}if(t.type===o.ReplicaSetNoPrimary){if(r.length===0){return r}const n=r.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return r.reduce(((r,o)=>{const s=n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}return r}function tagSetMatch(e,t){const r=Object.keys(e);const n=Object.keys(t);for(let o=0;o{if(tagSetMatch(n,t.tags))e.push(t);return e}),[]);if(o.length){return o}}return[]}function latencyWindowReducer(e,t){const r=t.reduce(((e,t)=>e===-1?t.roundTripTime:Math.min(t.roundTripTime,e)),-1);const n=r+e.localThresholdMS;return t.reduce(((e,t)=>{if(t.roundTripTime<=n&&t.roundTripTime>=r)e.push(t);return e}),[])}function primaryFilter(e){return e.type===n.RSPrimary}function secondaryFilter(e){return e.type===n.RSSecondary}function nearestFilter(e){return e.type===n.RSSecondary||e.type===n.RSPrimary}function knownFilter(e){return e.type!==n.Unknown}function readPreferenceServerSelector(e){if(!e.isValid()){throw new TypeError("Invalid read preference specified")}return function(t,r){const n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n){throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`)}if(t.type===o.Unknown){return[]}if(t.type===o.Single||t.type===o.Sharded){return latencyWindowReducer(t,r.filter(knownFilter))}const a=e.mode;if(a===s.PRIMARY){return r.filter(primaryFilter)}if(a===s.PRIMARY_PREFERRED){const e=r.filter(primaryFilter);if(e.length){return e}}const A=a===s.NEAREST?nearestFilter:secondaryFilter;const c=latencyWindowReducer(t,tagSetReducer(e,maxStalenessReducer(e,t,r.filter(A))));if(a===s.SECONDARY_PREFERRED&&c.length===0){return r.filter(primaryFilter)}return c}}e.exports={writableServerSelector:writableServerSelector,readPreferenceServerSelector:readPreferenceServerSelector}},9663:(e,t,r)=>{"use strict";var n;const o=r(104);const s=r(2361).EventEmitter;const i=r(7578);function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}class SrvPollingEvent{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map((e=>`${e.name}:${e.port}`)))}}class SrvPoller extends s{constructor(e){super();if(!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=o("srvPoller",e);this.haMode=false;this.generation=0;this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){if(!this._timeout){this.schedule()}}stop(){if(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=false;this.schedule();this.emit("srvRecordDiscovery",new SrvPollingEvent(e))}failure(e,t){this.logger.warn(e,t);this.haMode=true;this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,((t,r)=>{if(e!==this.generation){return}if(t){this.failure("DNS error",t);return}const n=[];r.forEach((e=>{if(matchesParentDomain(e.name,this.srvHost)){n.push(e)}else{this.parentDomainMismatch(e)}}));if(!n.length){this.failure("No valid addresses found at host");return}this.success(n)}))}}n=SrvPollingEvent;e.exports.D=SrvPoller},4149:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(750).ServerDescription;const i=r(2291).ServerType;const a=r(7962).TopologyDescription;const A=r(2291).TopologyType;const c=r(2785);const l=r(7062).Server;const u=r(1178).relayEvents;const h=r(4485);const d=r(4847).CoreCursor;const g=r(3837).deprecate;const p=r(7746).retrieveBSON();const E=r(2306).createCompressionInfo;const m=r(5474).ClientSession;const C=r(3111).MongoError;const I=r(3111).MongoServerSelectionError;const y=r(2306).resolveClusterTime;const B=r(9663).D;const Q=r(2306).getMMAPError;const b=r(1178).makeStateMachine;const w=r(1178).eachAsync;const S=r(1371).emitDeprecationWarning;const v=r(5474).ServerSessionPool;const R=r(1178).makeClientMetadata;const k=r(897).CMAP_EVENT_NAMES;const D=r(750).compareTopologyVersion;const N=r(1371).emitWarning;const T=r(2291);const O=T.drainTimerQueue;const _=T.clearAndRemoveTimerFrom;const M=r(4547);const L=M.readPreferenceServerSelector;const F=M.writableServerSelector;let U=0;const P=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(k);const G=["connect","descriptionReceived","close","ended"];const Y=T.STATE_CLOSING;const V=T.STATE_CLOSED;const W=T.STATE_CONNECTING;const J=T.STATE_CONNECTED;const q=b({[V]:[V,W],[W]:[W,Y,J,V],[J]:[J,Y,V],[Y]:[Y,V]});const j=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]);const z=Symbol("cancelled");const $=Symbol("waitQueue");class Topology extends o{constructor(e,t){super();if(typeof t==="undefined"&&typeof e!=="string"){t=e;e=[];if(t.host){e.push({host:t.host,port:t.port})}}e=e||[];if(typeof e==="string"){e=parseStringSeedlist(e)}t=Object.assign({},T.TOPOLOGY_DEFAULTS,t);t=Object.freeze(Object.assign(t,{metadata:R(t),compression:{compressors:E(t)}}));j.forEach((e=>{if(t[e]){S(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}));const r=topologyTypeFromSeedlist(e,t);const o=U++;const i=e.reduce(((e,t)=>{if(t.domain_socket)t.host=t.domain_socket;const r=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;e.set(r,new s(r));return e}),new Map);this[$]=new n;this.s={id:o,options:t,seedlist:e,state:V,description:new a(r,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new p([p.Binary,p.Code,p.DBRef,p.Decimal128,p.Double,p.Int32,p.Long,p.Map,p.MaxKey,p.MinKey,p.ObjectId,p.BSONRegExp,p.Symbol,p.Timestamp]),servers:new Map,sessionPool:new v(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set};this.serverApi=t.serverApi;if(t.srvHost){this.s.srvPoller=t.srvPoller||new B({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel});this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type;const r=e.newDescription.type;if(t!==A.Sharded&&r===A.Sharded){this.s.handleSrvPolling=srvPollingHandler(this);this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling);this.s.srvPoller.start()}};this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)}this.setMaxListeners(Infinity)}get description(){return this.s.description}get parserType(){return p.native?"c++":"js"}connect(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.s.state===J){if(typeof t==="function"){t()}return}q(this,W);this.emit("topologyOpening",new c.TopologyOpeningEvent(this.s.id));this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,new a(A.Unknown),this.s.description));connectServers(this,Array.from(this.s.description.servers.values()));h.translate(e);const r=e.readPreference||h.primary;const connectHandler=e=>{if(e){this.close();if(typeof t==="function"){t(e)}else{this.emit("error",e)}return}q(this,J);this.emit("open",e,this);this.emit("connect",this);if(typeof t==="function")t(e,this)};if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:r},connectHandler);return}this.selectServer(L(r),e,connectHandler)}close(e,t){if(typeof e==="function"){t=e;e={}}if(typeof e==="boolean"){e={force:e}}e=e||{};if(this.s.state===V||this.s.state===Y){if(typeof t==="function"){t()}return}q(this,Y);drainWaitQueue(this[$],new C("Topology closed"));O(this.s.connectionTimers);if(this.s.srvPoller){this.s.srvPoller.stop();if(this.s.handleSrvPolling){this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling);delete this.s.handleSrvPolling}}if(this.s.detectTopologyDescriptionChange){this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange);delete this.s.detectTopologyDescriptionChange}this.s.sessions.forEach((e=>e.endSession()));this.s.sessionPool.endAllPooledSessions((()=>{w(Array.from(this.s.servers.values()),((t,r)=>destroyServer(t,this,e,r)),(e=>{this.s.servers.clear();this.emit("topologyClosed",new c.TopologyClosedEvent(this.s.id));q(this,V);if(typeof t==="function"){t(e)}}))}))}selectServer(e,t,r){if(typeof t==="function"){r=t;if(typeof e!=="function"){t=e;let r;if(e instanceof h){r=e}else if(typeof e==="string"){r=new h(e)}else{h.translate(t);r=t.readPreference||h.primary}e=L(r)}else{t={}}}t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const n=this.description.type===A.Sharded;const o=t.session;const s=o&&o.transaction;if(n&&s&&s.server){r(undefined,s.server);return}let i=e;if(typeof e==="object"){const t=e.readPreference?e.readPreference:h.primary;i=L(t)}const a={serverSelector:i,transaction:s,callback:r};const c=t.serverSelectionTimeoutMS;if(c){a.timer=setTimeout((()=>{a[z]=true;a.timer=undefined;const e=new I(`Server selection timed out after ${c} ms`,this.description);a.callback(e)}),c)}this[$].push(a);processWaitQueue(this)}shouldCheckForSessionSupport(){if(this.description.type===A.Single){return!this.description.hasKnownServers}return!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new m(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){if(!Array.isArray(e)){e=[e]}this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:true,serverApi:this.serverApi},(()=>{if(typeof t==="function")t()}))}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address)){return}if(isStaleServerDescription(this.s.description,e)){return}const t=this.s.description;const r=this.s.description.servers.get(e.address);const n=e.$clusterTime;if(n){y(this,n)}const o=r&&r.equals(e);this.s.description=this.s.description.update(e);if(this.s.description.compatibilityError){this.emit("error",new C(this.s.description.compatibilityError));return}if(!o){this.emit("serverDescriptionChanged",new c.ServerDescriptionChangedEvent(this.s.id,e.address,r,this.s.description.servers.get(e.address)))}updateServers(this,e);if(this[$].length>0){processWaitQueue(this)}if(!o){this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){if(typeof e==="function")t=e,e=null;if(typeof t==="function")t(null,true)}logout(e){if(typeof e==="function")e(null,true)}insert(e,t,r,n){executeWriteOperation({topology:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({topology:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({topology:this,op:"remove",ns:e,ops:t},r,n)}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}h.translate(r);const o=r.readPreference||h.primary;this.selectServer(L(o),r,((o,s)=>{if(o){n(o);return}const i=!r.retrying;const a=!!r.retryWrites;const A=!!r.session;const c=s.supportsRetryableWrites;const l=!A||!r.session.inTransaction();const u=i&&a&&A&&c&&l&&isWriteCommand(t);const cb=(o,s)=>{if(!o)return n(null,s);if(!shouldRetryOperation(o)){return n(o)}if(u){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}return n(o)};if(u){r.session.incrementTransactionNumber();r.willRetryWrite=u}s.command(e,t,r,cb)}))}cursor(e,t,r){r=r||{};const n=r.topology||this;const o=r.cursorFactory||this.s.Cursor;h.translate(r);return new o(n,e,t,r)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===J}isDestroyed(){return this.s.state===V}unref(){N("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(e.length===0)return{};const t=e.filter((e=>e.type!==i.Unknown))[0];const r=t||{maxWireVersion:this.description.commonWireVersion};return r}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(Topology.prototype,"clusterTime",{enumerable:true,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});Topology.prototype.destroy=g(Topology.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function isWriteCommand(e){return K.some((t=>e[t]))}function isStaleServerDescription(e,t){const r=e.servers.get(t.address);const n=r.topologyVersion;return D(n,t.topologyVersion)>0}function destroyServer(e,t,r,n){r=r||{};G.forEach((t=>e.removeAllListeners(t)));e.destroy(r,(()=>{t.emit("serverClosed",new c.ServerClosedEvent(t.s.id,e.description.address));P.forEach((t=>e.removeAllListeners(t)));if(typeof n==="function"){n()}}))}function parseStringSeedlist(e){return e.split(",").map((e=>({host:e.split(":")[0],port:e.split(":")[1]||27017})))}function topologyTypeFromSeedlist(e,t){if(t.directConnection){return A.Single}const r=t.replicaSet||t.setName||t.rs_name;if(r==null){return A.Unknown}return A.ReplicaSetNoPrimary}function randomSelection(e){return e[Math.floor(Math.random()*e.length)]}function createAndConnectServer(e,t,r){e.emit("serverOpening",new c.ServerOpeningEvent(e.s.id,t.address));const n=new l(t,e.s.options,e);u(n,e,P);n.on("descriptionReceived",e.serverUpdateHandler.bind(e));if(r){const t=setTimeout((()=>{_(t,e.s.connectionTimers);n.connect()}),r);e.s.connectionTimers.add(t);return n}n.connect();return n}function connectServers(e,t){e.s.servers=t.reduce(((t,r)=>{const n=createAndConnectServer(e,r);t.set(r.address,n);return t}),new Map)}function updateServers(e,t){if(t&&e.s.servers.has(t.address)){const r=e.s.servers.get(t.address);r.s.description=t}for(const t of e.description.servers.values()){if(!e.s.servers.has(t.address)){const r=createAndConnectServer(e,t);e.s.servers.set(t.address,r)}}for(const t of e.s.servers){const r=t[0];if(e.description.hasServer(r)){continue}const n=e.s.servers.get(r);e.s.servers.delete(r);destroyServer(n,e)}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.topology;const o=e.op;const s=e.ns;const i=e.ops;n.selectServer(F(),t,((n,a)=>{if(n){r(n,null);return}const A=!e.retrying;const c=!!t.retryWrites;const l=!!t.session;const u=a.supportsRetryableWrites;const h=!l||!t.session.inTransaction();const d=t.explain===undefined;const g=A&&c&&l&&u&&h&&d;const handler=(n,o)=>{if(!n)return r(null,o);if(!shouldRetryOperation(n)){n=Q(n);return r(n)}if(g){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}return r(n)};if(r.operationId){handler.operationId=r.operationId}if(g){t.session.incrementTransactionNumber();t.willRetryWrite=g}a[o](s,i,t,handler)}))}function shouldRetryOperation(e){return e instanceof C&&e.hasErrorLabel("RetryableWriteError")}function srvPollingHandler(e){return function handleSrvPolling(t){const r=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(t);if(e.s.description===r){return}updateServers(e);e.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(e.s.id,r,e.s.description))}}function drainWaitQueue(e,t){while(e.length){const r=e.shift();clearTimeout(r.timer);if(!r[z]){r.callback(t)}}}function processWaitQueue(e){if(e.s.state===V){drainWaitQueue(e[$],new C("Topology is closed, please connect"));return}const t=Array.from(e.description.servers.values());const r=e[$].length;for(let n=0;n0){e.s.servers.forEach((e=>process.nextTick((()=>e.requestCheck()))))}}e.exports={Topology:Topology}},7962:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(750).ServerDescription;const s=r(7161);const i=r(2291).TopologyType;const a=s.MIN_SUPPORTED_SERVER_VERSION;const A=s.MAX_SUPPORTED_SERVER_VERSION;const c=s.MIN_SUPPORTED_WIRE_VERSION;const l=s.MAX_SUPPORTED_WIRE_VERSION;class TopologyDescription{constructor(e,t,r,o,s,u,h){h=h||{};this.type=e||i.Unknown;this.setName=r||null;this.maxSetVersion=o||null;this.maxElectionId=s||null;this.servers=t||new Map;this.stale=false;this.compatible=true;this.compatibilityError=null;this.logicalSessionTimeoutMinutes=null;this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0;this.localThresholdMS=h.localThresholdMS||0;this.commonWireVersion=u||null;Object.defineProperty(this,"options",{value:h,enumberable:false});for(const e of this.servers.values()){if(e.type===n.Unknown)continue;if(e.minWireVersion>l){this.compatible=false;this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${A})`}if(e.maxWireVersion=0){u.delete(t)}if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){const t=updateRsNoPrimaryFromMember(u,s,e);r=t[0],s=t[1]}}if(r===i.ReplicaSetWithPrimary){if([n.Standalone,n.Mongos].indexOf(l)>=0){u.delete(t);r=checkHasPrimary(u)}else if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){r=updateRsWithPrimaryFromMember(u,s,e)}else{r=checkHasPrimary(u)}}return new TopologyDescription(r,u,s,a,A,c,this.options)}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));if(e.length>0){return e[0].error}return undefined}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==n.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}}function topologyTypeForServerType(e){if(e===n.Standalone){return i.Single}if(e===n.Mongos){return i.Sharded}if(e===n.RSPrimary){return i.ReplicaSetWithPrimary}if(e===n.RSGhost||e===n.Unknown){return i.Unknown}return i.ReplicaSetNoPrimary}function compareObjectId(e,t){if(e==null){return-1}if(t==null){return 1}if(e.id instanceof Buffer&&t.id instanceof Buffer){const r=e.id;const n=t.id;return r.compare(n)}const r=e.toString();const n=t.toString();return r.localeCompare(n)}function updateRsFromPrimary(e,t,r,s,i){t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[checkHasPrimary(e),t,s,i]}const a=r.electionId?r.electionId:null;if(r.setVersion&&a){if(s&&i){if(s>r.setVersion||compareObjectId(i,a)>0){e.set(r.address,new o(r.address));return[checkHasPrimary(e),t,s,i]}}i=r.electionId}if(r.setVersion!=null&&(s==null||r.setVersion>s)){s=r.setVersion}for(const t of e.keys()){const s=e.get(t);if(s.type===n.RSPrimary&&s.address!==r.address){e.set(t,new o(s.address));break}}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));const A=Array.from(e.keys());const c=r.allHosts;A.filter((e=>c.indexOf(e)===-1)).forEach((t=>{e.delete(t)}));return[checkHasPrimary(e),t,s,i]}function updateRsWithPrimaryFromMember(e,t,r){if(t==null){throw new TypeError("setName is required")}if(t!==r.setName||r.me&&r.address!==r.me){e.delete(r.address)}return checkHasPrimary(e)}function updateRsNoPrimaryFromMember(e,t,r){let n=i.ReplicaSetNoPrimary;t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[n,t]}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));if(r.me&&r.address!==r.me){e.delete(r.address)}return[n,t]}function checkHasPrimary(e){for(const t of e.keys()){if(e.get(t).type===n.RSPrimary){return i.ReplicaSetWithPrimary}}return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:TopologyDescription}},5474:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(2361);const s=n();const i=s.Binary;const a=r(1178).uuidV4;const A=r(3111).MongoError;const c=r(3111).isRetryableError;const l=r(3111).isRetryableEndTransactionError;const u=r(3111).MongoNetworkError;const h=r(3111).MongoWriteConcernError;const d=r(1707).Transaction;const g=r(1707).TxnState;const p=r(1178).isPromiseLike;const E=r(4485);const m=r(1371).maybePromise;const C=r(1707).isTransactionCommand;const I=r(2306).resolveClusterTime;const y=r(7272).isSharded;const B=r(1178).maxWireVersion;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;const w=8;function assertAlive(e,t){if(e.serverSession==null){const e=new A("Cannot use a session that has ended");if(typeof t==="function"){t(e,null);return false}throw e}return true}const S=Symbol("serverSession");class ClientSession extends o{constructor(e,t,r,n){super();if(e==null){throw new Error("ClientSession requires a topology")}if(t==null||!(t instanceof ServerSessionPool)){throw new Error("ClientSession requires a ServerSessionPool")}r=r||{};n=n||{};this.topology=e;this.sessionPool=t;this.hasEnded=false;this.clientOptions=n;this[S]=undefined;this.supports={causalConsistency:typeof r.causalConsistency!=="undefined"?r.causalConsistency:true};this.clusterTime=r.initialClusterTime;this.operationTime=null;this.explicit=!!r.explicit;this.owner=r.owner;this.defaultTransactionOptions=Object.assign({},r.defaultTransactionOptions);this.transaction=new d}get id(){return this.serverSession.id}get serverSession(){if(this[S]==null){this[S]=this.sessionPool.acquire()}return this[S]}endSession(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=this;return m(this,t,(e=>{if(r.hasEnded){return e()}function completeEndSession(){r.sessionPool.release(r.serverSession);r[S]=undefined;r.hasEnded=true;r.emit("ended",r);e()}if(r.serverSession&&r.inTransaction()){r.abortTransaction((t=>{if(t)return e(t);completeEndSession()}));return}completeEndSession()}))}advanceOperationTime(e){if(this.operationTime==null){this.operationTime=e;return}if(e.greaterThan(this.operationTime)){this.operationTime=e}}equals(e){if(!(e instanceof ClientSession)){return false}return this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){assertAlive(this);if(this.inTransaction()){throw new A("Transaction already in progress")}const t=B(this.topology);if(y(this.topology)&&t!=null&&tendTransaction(this,"commitTransaction",e)))}abortTransaction(e){return m(this,e,(e=>endTransaction(this,"abortTransaction",e)))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){const r=Q();return attemptTransaction(this,r,e,t)}}const v=12e4;const R=100;const k=79;const D=50;const N=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function hasNotTimedOut(e,t){return b(e){if(o instanceof A&&hasNotTimedOut(t,v)&&!isMaxTimeMSExpiredError(o)){if(o.hasErrorLabel("UnknownTransactionCommitResult")){return attemptTransactionCommit(e,t,r,n)}if(o.hasErrorLabel("TransientTransactionError")){return attemptTransaction(e,t,r,n)}}throw o}))}const T=new Set([g.NO_TRANSACTION,g.TRANSACTION_COMMITTED,g.TRANSACTION_ABORTED]);function userExplicitlyEndedTransaction(e){return T.has(e.transaction.state)}function attemptTransaction(e,t,r,n){e.startTransaction(n);let o;try{o=r(e)}catch(e){o=Promise.reject(e)}if(!p(o)){e.abortTransaction();throw new TypeError("Function provided to `withTransaction` must return a Promise")}return o.then((()=>{if(userExplicitlyEndedTransaction(e)){return}return attemptTransactionCommit(e,t,r,n)})).catch((o=>{function maybeRetryOrThrow(o){if(o instanceof A&&o.hasErrorLabel("TransientTransactionError")&&hasNotTimedOut(t,v)){return attemptTransaction(e,t,r,n)}if(isMaxTimeMSExpiredError(o)){o.addErrorLabel("UnknownTransactionCommitResult")}throw o}if(e.transaction.isActive){return e.abortTransaction().then((()=>maybeRetryOrThrow(o)))}return maybeRetryOrThrow(o)}))}function endTransaction(e,t,r){if(!assertAlive(e,r)){return}let n=e.transaction.state;if(n===g.NO_TRANSACTION){r(new A("No transaction started"));return}if(t==="commitTransaction"){if(n===g.STARTING_TRANSACTION||n===g.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(g.TRANSACTION_COMMITTED_EMPTY);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_ABORTED);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call abortTransaction twice"));return}if(n===g.TRANSACTION_COMMITTED||n===g.TRANSACTION_COMMITTED_EMPTY){r(new A("Cannot call abortTransaction after calling commitTransaction"));return}}const o={[t]:1};let s;if(e.transaction.options.writeConcern){s=Object.assign({},e.transaction.options.writeConcern)}else if(e.clientOptions&&e.clientOptions.w){s={w:e.clientOptions.w}}if(n===g.TRANSACTION_COMMITTED){s=Object.assign({wtimeout:1e4},s,{w:"majority"})}if(s){Object.assign(o,{writeConcern:s})}if(t==="commitTransaction"&&e.transaction.options.maxTimeMS){Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS})}function commandHandler(n,o){if(t==="commitTransaction"){e.transaction.transition(g.TRANSACTION_COMMITTED);if(n){if(n instanceof u||n instanceof h||c(n)||isMaxTimeMSExpiredError(n)){if(isUnknownTransactionCommitResult(n)){n.addErrorLabel("UnknownTransactionCommitResult");e.transaction.unpinServer()}}else if(n.hasErrorLabel("TransientTransactionError")){e.transaction.unpinServer()}}}else{e.transaction.transition(g.TRANSACTION_ABORTED)}r(n,o)}function transactionError(e){return t==="commitTransaction"?e:null}if(e.transaction.recoveryToken&&supportsRecoveryToken(e)){o.recoveryToken=e.transaction.recoveryToken}e.topology.command("admin.$cmd",o,{session:e},((t,r)=>{if(t&&l(t)){if(o.commitTransaction){e.transaction.unpinServer();o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})}return e.topology.command("admin.$cmd",o,{session:e},((e,t)=>commandHandler(transactionError(e),t)))}commandHandler(transactionError(t),r)}))}function supportsRecoveryToken(e){const t=e.topology;return!!t.s.options.useRecoveryToken}class ServerSession{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)};this.lastUse=Q();this.txnNumber=0;this.isDirty=false}hasTimedOut(e){const t=Math.round(b(this.lastUse)%864e5%36e5/6e4);return t>e-1}}class ServerSessionPool{constructor(e){if(e==null){throw new Error("ServerSessionPool requires a topology")}this.topology=e;this.sessions=[]}endAllPooledSessions(e){if(this.sessions.length){this.topology.endSessions(this.sessions.map((e=>e.id)),(()=>{this.sessions=[];if(typeof e==="function"){e()}}));return}if(typeof e==="function"){e()}}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const t=this.sessions.shift();if(!t.hasTimedOut(e)){return t}}return new ServerSession}release(e){const t=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const e=this.sessions[this.sessions.length-1];if(e.hasTimedOut(t)){this.sessions.pop()}else{break}}if(!e.hasTimedOut(t)){if(e.isDirty){return}this.sessions.unshift(e)}}}function commandSupportsReadConcern(e,t){if(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch){return true}if(e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline")){return true}return false}function applySession(e,t,r){if(e.hasEnded){return new A("Cannot use a session that has ended")}if(r&&r.writeConcern&&r.writeConcern.w===0){return}const n=e.serverSession;n.lastUse=Q();t.lsid=n.id;const o=e.inTransaction()||C(t);const i=r.willRetryWrite;const a=commandSupportsReadConcern(t,r);if(n.txnNumber&&(i||o)){t.txnNumber=s.Long.fromNumber(n.txnNumber)}if(!o){if(e.transaction.state!==g.NO_TRANSACTION){e.transaction.transition(g.NO_TRANSACTION)}if(e.supports.causalConsistency&&e.operationTime&&a){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}return}if(r.readPreference&&!r.readPreference.equals(E.primary)){return new A(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`)}t.autocommit=false;if(e.transaction.state===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_IN_PROGRESS);t.startTransaction=true;const r=e.transaction.options.readConcern||e.clientOptions.readConcern;if(r){t.readConcern=r}if(e.supports.causalConsistency&&e.operationTime){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}}}function updateSessionFromResponse(e,t){if(t.$clusterTime){I(e,t.$clusterTime)}if(t.operationTime&&e&&e.supports.causalConsistency){e.advanceOperationTime(t.operationTime)}if(t.recoveryToken&&e&&e.inTransaction()){e.transaction._recoveryToken=t.recoveryToken}}e.exports={ClientSession:ClientSession,ServerSession:ServerSession,ServerSessionPool:ServerSessionPool,TxnState:g,applySession:applySession,updateSessionFromResponse:updateSessionFromResponse,commandSupportsReadConcern:commandSupportsReadConcern}},8175:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4847).CoreCursor;const a=r(104);const A=r(7746).retrieveBSON;const c=r(3111).MongoError;const l=r(6495);const u=r(2306).diff;const h=r(2306).cloneOptions;const d=r(2306).SessionMixins;const g=r(2306).isRetryableWritesSupported;const p=r(1178).relayEvents;const E=A();const m=r(2306).getMMAPError;const C=r(1178).makeClientMetadata;const I=r(2306).legacyIsRetryableWriteError;var y="disconnected";var B="connecting";var Q="connected";var b="unreferenced";var w="destroying";var S="destroyed";function stateTransition(e,t){var r={disconnected:[B,w,S,y],connecting:[B,w,S,Q,y],connected:[Q,y,w,S,b],unreferenced:[b,w,S],destroyed:[S]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{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 v=1;var R=["connect","close","error","timeout","parseError"];var Mongos=function(e,t){t=t||{};this.id=v++;if(Array.isArray(e)){e=e.reduce(((e,t)=>{if(e.find((e=>e.host===t.host&&e.port===t.port))){return e}e.push(t);return e}),[])}this.s={options:Object.assign({metadata:C(t)},t),bson:t.bson||new E([E.Binary,E.Code,E.DBRef,E.Decimal128,E.Double,E.Int32,E.Long,E.Map,E.MaxKey,E.MinKey,E.ObjectId,E.BSONRegExp,E.Symbol,E.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false,localThresholdMS:t.localThresholdMS||15};if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0){e.emit(t,r)}}const k=["serverDescriptionChanged","error","close","timeout","parseError"];function destroyServer(e,t,r){t=t||{};k.forEach((t=>e.removeAllListeners(t)));e.destroy(t,r)}Mongos.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,B);var r=this.s.seedlist.map((function(r){const n=new l(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,parent:t}));p(n,t,["serverDescriptionChanged"]);return n}));emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectProxies(t,r)};Mongos.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};function handleEvent(e){return function(){if(e.state===S||e.state===w){return}moveServerFrom(e.connectedProxies,e.disconnectedProxies,this);emitTopologyDescriptionChanged(e);e.emit("left","mongos",this);e.emit("serverClosed",{topologyId:e.id,address:this.name})}}function handleInitialConnectEvent(e,t){return function(){var r=this;if(e.state===S){emitTopologyDescriptionChanged(e);moveServerFrom(e.connectingProxies,e.disconnectedProxies,this);return this.destroy()}if(t==="connect"){e.ismaster=r.lastIsMaster();if(e.ismaster.msg==="isdbgrid"){for(let t=0;t0&&e.state===B){stateTransition(e,Q);e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.disconnectedProxies.length===0){if(e.s.logger.isWarn()){e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset"))}return e.emit("error",new c("no mongos proxies found in seed list"))}topologyMonitor(e,{firstConnect:true})}}}function connectProxies(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function connect(t,r){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name});emitTopologyDescriptionChanged(e);t.once("close",handleInitialConnectEvent(e,"close"));t.once("timeout",handleInitialConnectEvent(e,"timeout"));t.once("parseError",handleInitialConnectEvent(e,"parseError"));t.once("error",handleInitialConnectEvent(e,"error"));t.once("connect",handleInitialConnectEvent(e,"connect"));p(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}t.forEach((e=>connect(e,r++)))}function pickProxy(e,t){const r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected()){return r.server}else{r.unpinServer()}}var n=e.connectedProxies.slice(0);var o=Number.MAX_VALUE;for(var s=0;s0&&e.state===B){e.emit("error",new c("no mongos proxy available"))}else{e.emit("close",e)}return reconnectProxies(e,e.disconnectedProxies,(function(){if(e.state===S||e.state===w||e.state===b){return}if(e.state===B&&t.firstConnect){e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.isConnected()){e.emit("reconnect",e)}else if(!e.isConnected()&&e.listeners("close").length>0){e.emit("close",e)}topologyMonitor(e)}))}for(var o=0;o{n--;if(n>0){return}emitTopologyDescriptionChanged(this);emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});stateTransition(this,S);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name});destroyServer(t,e,serverDestroyed);moveServerFrom(this.connectedProxies,this.disconnectedProxies,t)}))};Mongos.prototype.isConnected=function(){return this.connectedProxies.length>0};Mongos.prototype.isDestroyed=function(){return this.state===S};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const o=e.op;const s=e.ns;const i=e.ops;let a=pickProxy(n,t.session);if(!a)return r(new c("no mongos proxy available"));const A=!e.retrying&&!!t.retryWrites&&t.session&&g(n)&&!t.session.inTransaction()&&t.explain===undefined;const handler=(o,s)=>{if(!o)return r(null,s);if(!I(o,n)||!A){o=m(o);return r(o)}a=pickProxy(n,t.session);if(!a){return r(o)}const i=Object.assign({},e,{retrying:true});return executeWriteOperation(i,t,r)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}a[o](s,i,t,handler)}Mongos.prototype.insert=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("insert",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};Mongos.prototype.update=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("update",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};Mongos.prototype.remove=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("remove",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const D=["findAndModify","insert","update","delete"];function isWriteCommand(e){return D.some((t=>e[t]))}Mongos.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}var s=this;var i=pickProxy(s,r.session);if((i==null||!i.isConnected())&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}if(i==null){return n(new c("no mongos proxy available"))}var a=h(r);a.topology=s;const A=!r.retrying&&r.retryWrites&&r.session&&g(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(r,o)=>{if(!r)return n(null,o);if(!I(r,s)){return n(r)}if(A){const r=Object.assign({},a,{retrying:true});return this.command(e,t,r,n)}return n(r)};if(A){a.session.incrementTransactionNumber();a.willRetryWrite=A}i.command(e,t,a,cb)};Mongos.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Mongos.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;t=t||{};const n=pickProxy(this,t.session);if(n==null){r(new c("server selection failed"));return}if(this.s.debug)this.emit("pickedServer",null,n);r(null,n)};Mongos.prototype.connections=function(){var e=[];for(var t=0;t0){var t="Unknown";if(e.connectedProxies.length>0){t="Sharded"}var r={topologyType:t,servers:[]};var n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map((function(e){var t=e.getDescription();t.type="Unknown";return t})));r.servers=r.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();t.type="Mongos";return t})));var o=u(e.topologyDescription,r);var s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:o};if(o.servers.length>0){e.emit("topologyDescriptionChanged",s)}e.topologyDescription=r}}e.exports=Mongos},4485:(e,t,r)=>{"use strict";const n=r(1371).emitWarningOnce;const ReadPreference=function(e,t,r){if(!ReadPreference.isValid(e)){throw new TypeError(`Invalid read preference mode ${e}`)}if(t&&!Array.isArray(t)){n("ReadPreference tags must be an array, this will change in the next major version");const e=typeof t.maxStalenessSeconds!=="undefined";const o=typeof t.hedge!=="undefined";const s=e||o;if(s){r=t;t=undefined}else{t=[t]}}this.mode=e;this.tags=t;this.hedge=r&&r.hedge;r=r||{};if(r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0){throw new TypeError("maxStalenessSeconds must be a positive integer")}this.maxStalenessSeconds=r.maxStalenessSeconds;this.minWireVersion=5}if(this.mode===ReadPreference.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(ReadPreference.prototype,"preference",{enumerable:true,get:function(){return this.mode}});ReadPreference.PRIMARY="primary";ReadPreference.PRIMARY_PREFERRED="primaryPreferred";ReadPreference.SECONDARY="secondary";ReadPreference.SECONDARY_PREFERRED="secondaryPreferred";ReadPreference.NEAREST="nearest";const o=[ReadPreference.PRIMARY,ReadPreference.PRIMARY_PREFERRED,ReadPreference.SECONDARY,ReadPreference.SECONDARY_PREFERRED,ReadPreference.NEAREST,null];ReadPreference.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const r=e.readPreferenceTags;const n=e.maxStalenessSeconds;if(typeof t==="string"){return new ReadPreference(t,r)}else if(!(t instanceof ReadPreference)&&typeof t==="object"){const e=t.mode||t.preference;if(e&&typeof e==="string"){return new ReadPreference(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}}return t};ReadPreference.resolve=function(e,t){t=t||{};const r=t.session;const n=e&&e.readPreference;let o;if(t.readPreference){o=ReadPreference.fromOptions(t)}else if(r&&r.inTransaction()&&r.transaction.options.readPreference){o=r.transaction.options.readPreference}else if(n!=null){o=n}else{o=ReadPreference.primary}return typeof o==="string"?new ReadPreference(o):o};ReadPreference.translate=function(e){if(e.readPreference==null)return e;const t=e.readPreference;if(typeof t==="string"){e.readPreference=new ReadPreference(t)}else if(t&&!(t instanceof ReadPreference)&&typeof t==="object"){const r=t.mode||t.preference;if(r&&typeof r==="string"){e.readPreference=new ReadPreference(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds})}}else if(!(t instanceof ReadPreference)){throw new TypeError("Invalid read preference: "+t)}return e};ReadPreference.isValid=function(e){return o.indexOf(e)!==-1};ReadPreference.prototype.isValid=function(e){return ReadPreference.isValid(typeof e==="string"?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];ReadPreference.prototype.slaveOk=function(){return s.indexOf(this.mode)!==-1};ReadPreference.prototype.equals=function(e){return e.mode===this.mode};ReadPreference.prototype.toJSON=function(){const e={mode:this.mode};if(Array.isArray(this.tags))e.tags=this.tags;if(this.maxStalenessSeconds)e.maxStalenessSeconds=this.maxStalenessSeconds;if(this.hedge)e.hedge=this.hedge;return e};ReadPreference.primary=new ReadPreference("primary");ReadPreference.primaryPreferred=new ReadPreference("primaryPreferred");ReadPreference.secondary=new ReadPreference("secondary");ReadPreference.secondaryPreferred=new ReadPreference("secondaryPreferred");ReadPreference.nearest=new ReadPreference("nearest");e.exports=ReadPreference},1134:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4485);const a=r(4847).CoreCursor;const A=r(7746).retrieveBSON;const c=r(104);const l=r(3111).MongoError;const u=r(6495);const h=r(8742);const d=r(2306).Timeout;const g=r(2306).Interval;const p=r(2306).SessionMixins;const E=r(2306).isRetryableWritesSupported;const m=r(1178).relayEvents;const C=A();const I=r(2306).getMMAPError;const y=r(1178).makeClientMetadata;const B=r(2306).legacyIsRetryableWriteError;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;var w="disconnected";var S="connecting";var v="connected";var R="unreferenced";var k="destroyed";function stateTransition(e,t){var r={disconnected:[S,k,w],connecting:[S,k,v,w],connected:[v,w,k,R],unreferenced:[R,k],destroyed:[k]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}}var D=1;var N=["connect","close","error","timeout","parseError"];var ReplSet=function(e,t){var r=this;t=t||{};if(!Array.isArray(e))throw new l("seedlist must be an array");if(e.length===0)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if(typeof e.host!=="string"||typeof e.port!=="number")throw new l("seedlist entry must contain a host and port")}));s.call(this);this.id=D++;var n=t.localThresholdMS||15;if(t.acceptableLatency)n=t.acceptableLatency;var i=c("ReplSet",t);this.s={options:Object.assign({metadata:y(t)},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]),Cursor:t.cursorFactory||a,logger:i,seedlist:e,replicaSetState:new h({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false};this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){r.emit("topologyDescriptionChanged",e)}));if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoute.name===t));if(r>=0){const t=e.s.connectingServers[r];t.destroy({force:true});e.s.connectingServers.splice(r,1);return done()}var n=new u(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:false,monitoring:false,parent:e}));n.once("connect",_handleEvent(e,"connect"));n.once("close",_handleEvent(e,"close"));n.once("timeout",_handleEvent(e,"timeout"));n.once("error",_handleEvent(e,"error"));n.once("parseError",_handleEvent(e,"parseError"));n.on("serverOpening",(t=>e.emit("serverOpening",t)));n.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));n.on("serverClosed",(t=>e.emit("serverClosed",t)));m(n,e,["commandStarted","commandSucceeded","commandFailed"]);e.s.connectingServers.push(n);n.connect(e.s.connectOptions)}),r)}for(var s=0;se.emit("serverOpening",t)));t.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));t.on("serverClosed",(t=>e.emit("serverClosed",t)));m(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}while(t.length>0){connect(t.shift(),r++)}}function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}ReplSet.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,S);var r=this.s.seedlist.map((function(r){return new u(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,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)))}emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectServers(t,r)};ReplSet.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};ReplSet.prototype.destroy=function(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};let r=this.s.connectingServers.length+1;const serverDestroyed=()=>{r--;if(r>0){return}emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});if(typeof t==="function"){t(null,null)}};if(this.state===k){if(typeof t==="function")t(null,null);return}stateTransition(this,k);if(this.haTimeoutId)clearTimeout(this.haTimeoutId);for(var n=0;n{if(b(s)>=T){if(o!=null){r(o,null)}else{r(new l("Server selection timed out"))}return}const e=this.s.replicaSetState.pickServer(n);if(e==null){setTimeout(_selectServer,O);return}if(!(e instanceof u)){o=e;setTimeout(_selectServer,O);return}if(this.s.debug)this.emit("pickedServer",t.readPreference,e);r(null,e)};_selectServer()};ReplSet.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const s=e.op;const i=e.ns;const a=e.ops;if(n.state===k){return r(new l(o("topology was destroyed")))}const A=!e.retrying&&!!t.retryWrites&&t.session&&E(n)&&!t.session.inTransaction()&&t.explain===undefined;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler){return n.s.disconnectHandler.add(s,i,a,t,r)}else if(!A){return r(new l("no primary server found"))}}const handler=(o,s)=>{if(!o)return r(null,s);if(!B(o,n)){o=I(o);return r(o)}if(A){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}if(n.s.replicaSetState.primary){n.s.replicaSetState.primary.destroy();n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:true})}return r(o)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}n.s.replicaSetState.primary[s](i,a,t,handler)}ReplSet.prototype.insert=function(e,t,r,n){executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};ReplSet.prototype.update=function(e,t,r,n){executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};ReplSet.prototype.remove=function(e,t,r,n){executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const _=["findAndModify","insert","update","delete"];function isWriteCommand(e){return _.some((t=>e[t]))}ReplSet.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===k)return n(new l(o("topology was destroyed")));var s=this;var a=r.readPreference?r.readPreference:i.primary;if(a.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}var A=this.s.replicaSetState.pickServer(a);if(!(A instanceof u))return n(A);if(s.s.debug)s.emit("pickedServer",i.primary,A);if(A==null){return n(new l(o("no server found that matches the provided readPreference %s",a)))}const c=!r.retrying&&!!r.retryWrites&&r.session&&E(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(o,i)=>{if(!o)return n(null,i);if(!B(o,s)){return n(o)}if(c){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}if(this.s.replicaSetState.primary){this.s.replicaSetState.primary.destroy();this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:true})}return n(o)};if(c){r.session.incrementTransactionNumber();r.willRetryWrite=c}A.command(e,t,r,cb)};ReplSet.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};e.exports=ReplSet},8742:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2306).diff,i=r(2361).EventEmitter,a=r(104),A=r(4485),c=r(3111).MongoError,l=r(1867).Buffer;var u={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};var h={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};var ReplSetState=function(e){e=e||{};i.call(this);this.topologyType=e.setName?u.ReplicaSetNoPrimary:u.Unknown;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=undefined};n(ReplSetState,i);ReplSetState.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};ReplSetState.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};ReplSetState.prototype.hasPrimary=function(){return this.primary!=null};ReplSetState.prototype.hasSecondary=function(){return this.secondaries.length>0};ReplSetState.prototype.get=function(e){var t=this.allServers();for(var r=0;r{n--;if(n>0){return}this.secondaries=[];this.arbiters=[];this.passives=[];this.ghosts=[];this.unknownServers=[];this.set={};this.primary=null;emitTopologyDescriptionChanged(this);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>t.destroy(e,serverDestroyed)))};ReplSetState.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase();var n=this.primary?[this.primary]:[];n=n.concat(this.secondaries);n=n.concat(this.arbiters);n=n.concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;ReplSetState.prototype.update=function(e){var t=this;const r=e.lastIsMaster();if(r&&r.isWritablePrimary)r.ismaster=r.isWritablePrimary;var n=e.name.toLowerCase();if(r){var s=Array.isArray(r.hosts)?r.hosts:[];s=s.concat(Array.isArray(r.arbiters)?r.arbiters:[]);s=s.concat(Array.isArray(r.passives)?r.passives:[]);s=s.map((function(e){return e.toLowerCase()}));for(var i=0;il){return false}}else if(!p&&a&&l){if(l=5&&e.ismaster.secondary&&this.hasPrimary()){e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t}else if(e.ismaster.maxWireVersion>=5&&e.ismaster.secondary){e.staleness=r-e.lastWriteDate+t}};ReplSetState.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var o=pickNearest(this,e);if(o){return o}}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e);if(o){return o}}if(e.equals(A.secondaryPreferred)){return this.primary}return null}if(e.equals(A.primaryPreferred)){o=null;if(this.primary){return this.primary}if(n.length>0&&e.maxStalenessSeconds==null){o=pickNearest(this,e)}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e)}if(o)return o}return this.primary};var filterByTags=function(e,t){if(e.tags==null)return t;var r=[];var n=Array.isArray(e.tags)?e.tags:[e.tags];for(var o=0;o0?r[0].lastIsMasterMS:0;r=r.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}));if(r.length===0){return null}e.index=e.index%r.length;var s=r[e.index];e.index=e.index+1;return s}function inList(e,t,r){for(var n=0;n0){var t="Unknown";var r=e.setName;if(e.hasPrimaryAndSecondary()){t="ReplicaSetWithPrimary"}else if(!e.hasPrimary()&&e.hasSecondary()){t="ReplicaSetNoPrimary"}var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary";n.servers.push(o)}n.servers=n.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));n.servers=n.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();t.type="RSArbiter";return t})));n.servers=n.servers.concat(e.passives.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));var i=s(e.replicasetDescription,n);var a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:i};e.emit("topologyDescriptionChanged",a);e.replicasetDescription=n}}e.exports=ReplSetState},6495:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2361).EventEmitter,i=r(4485),a=r(104),A=r(7746).debugOptions,c=r(7746).retrieveBSON,l=r(5500),u=r(3111).MongoError,h=r(3111).MongoNetworkError,d=r(9206),g=r(4847).CoreCursor,p=r(2306),E=r(2306).createCompressionInfo,m=r(2306).resolveClusterTime,C=r(2306).SessionMixins,I=r(7703).extractCommand,y=r(1178).relayEvents;const B=r(1178).collationNotSupported;const Q=r(1178).makeClientMetadata;var b=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];var w=0;var S=false;var v={};var R=c();function topologyId(e){return e.s.parent==null?e.id:e.s.parent.id}var Server=function(e){e=e||{};s.call(this);this.id=w++;this.s={options:Object.assign({metadata:Q(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||g,bson:e.bson||new R([R.Binary,R.Code,R.DBRef,R.Decimal128,R.Double,R.Int32,R.Long,R.Map,R.MaxKey,R.MinKey,R.ObjectId,R.BSONRegExp,R.Symbol,R.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring==="boolean"?e.monitoring:true,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval==="number"?e.monitoringInterval:5e3,compression:{compressors:E(e)},parent:e.parent};if(!this.s.parent){this.s.clusterTime=null}this.ismaster=null;this.lastIsMasterMS=-1;this.monitoringProcessId=null;this.initialConnect=true;this._type="server";this.lastUpdateTime=0;this.lastWriteDate=0;this.staleness=0};n(Server,s);Object.assign(Server.prototype,C);Object.defineProperty(Server.prototype,"type",{enumerable:true,get:function(){return this._type}});Object.defineProperty(Server.prototype,"parserType",{enumerable:true,get:function(){return R.native?"c++":"js"}});Object.defineProperty(Server.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){if(!this.ismaster)return null;return this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(Server.prototype,"clientMetadata",{enumerable:true,get:function(){return this.s.options.metadata}});Object.defineProperty(Server.prototype,"clusterTime",{enumerable:true,set:function(e){const t=this.s.parent?this.s.parent:this.s;m(t,e)},get:function(){const e=this.s.parent?this.s.parent:this.s;return e.clusterTime||null}});Server.enableServerAccounting=function(){S=true;v={}};Server.disableServerAccounting=function(){S=false};Server.servers=function(){return v};Object.defineProperty(Server.prototype,"name",{enumerable:true,get:function(){return this.s.options.host+":"+this.s.options.port}});function disconnectHandler(e,t,r,n,s,i){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!s.monitoring){e.s.disconnectHandler.add(t,r,n,s,i);return true}if(!e.s.pool.isConnected()){i(new u(o("no connection available to server %s",e.name)));return true}}function monitoringProcess(e){return function(){if(e.s.pool.isDestroyed())return;e.emit("monitoring",e);var t=(new Date).getTime();e.command("admin.$cmd",{ismaster:true},{socketTimeout:typeof e.s.options.connectionTimeout!=="number"?2e3:e.s.options.connectionTimeout,monitoring:true},((r,n)=>{e.lastIsMasterMS=(new Date).getTime()-t;if(e.s.pool.isDestroyed())return;if(n){e.ismaster=n.result}e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}))}}var eventHandler=function(e,t){return function(r,n){if(e.s.logger.isInfo()){var s=r instanceof u?JSON.stringify(r):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,s))}if(t==="connect"){e.initialConnect=false;e.ismaster=n.ismaster;e.lastIsMasterMS=n.lastIsMasterMS;if(n.agreedCompressor){e.s.pool.options.agreedCompressor=n.agreedCompressor}if(n.zlibCompressionLevel){e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel}if(n.ismaster.$clusterTime){const t=n.ismaster.$clusterTime;e.clusterTime=t}if(e.ismaster.msg==="isdbgrid"){e._type="mongos"}if(e.s.monitoring){e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});if(!e.s.inTopology){p.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)}]})}if(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==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(S&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1){if(!e.s.inTopology){e.emit("topologyOpening",{topologyId:e.id})}delete v[e.id]}if(t==="close"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"})}if(t==="reconnectFailed"){e.emit("reconnectFailed",r);if(e.listeners("error").length>0){e.emit("error",r)}return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1){e.initialConnect=false;return e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,r)))}if(t==="reconnect"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});return e.emit(t,e)}e.emit(t,r)}}};Server.prototype.connect=function(e){var t=this;e=e||{};if(S)v[this.id]=this;if(t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed()){throw new u(o("server instance in invalid state %s",t.s.pool.state))}t.s.pool=new l(this,Object.assign(t.s.options,e,{bson:this.s.bson}));t.s.pool.on("close",eventHandler(t,"close"));t.s.pool.on("error",eventHandler(t,"error"));t.s.pool.on("timeout",eventHandler(t,"timeout"));t.s.pool.on("parseError",eventHandler(t,"parseError"));t.s.pool.on("connect",eventHandler(t,"connect"));t.s.pool.on("reconnect",eventHandler(t,"reconnect"));t.s.pool.on("reconnectFailed",eventHandler(t,"reconnectFailed"));y(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]);if(!t.s.inTopology){this.emit("topologyOpening",{topologyId:topologyId(t)})}t.emit("serverOpening",{topologyId:topologyId(t),address:t.name});t.s.pool.connect()};Server.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};Server.prototype.getDescription=function(){var e=this.ismaster||{};var t={type:p.getTopologyType(this),address:this.name};if(e.hosts)t.hosts=e.hosts;if(e.arbiters)t.arbiters=e.arbiters;if(e.passives)t.passives=e.passives;if(e.setName)t.setName=e.setName;return t};Server.prototype.lastIsMaster=function(){return this.ismaster};Server.prototype.unref=function(){this.s.pool.unref()};Server.prototype.isConnected=function(){if(!this.s.pool)return false;return this.s.pool.isConnected()};Server.prototype.isDestroyed=function(){if(!this.s.pool)return false;return this.s.pool.isDestroyed()};function basicWriteValidations(e){if(!e.s.pool)return new u("server instance is not connected");if(e.s.pool.isDestroyed())return new u("server instance pool was destroyed")}function basicReadValidations(e,t){basicWriteValidations(e,t);if(t.readPreference&&!(t.readPreference instanceof i)){throw new Error("readPreference must be an instance of ReadPreference")}}Server.prototype.command=function(e,t,r,n){var s=this;if(typeof r==="function"){n=r,r={},r=r||{}}var i=basicReadValidations(s,r);if(i)return n(i);r=Object.assign({},r,{wireProtocolCommand:false});if(s.s.logger.isDebug()){const n=I(t);s.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:A(b,r)}),s.name))}if(disconnectHandler(s,"command",e,t,r,n))return;if(B(this,t)){return n(new u(`server ${this.name} does not support collation`))}d.command(s,e,t,r,n)};Server.prototype.query=function(e,t,r,n,o){d.query(this,e,t,r,n,o)};Server.prototype.getMore=function(e,t,r,n,o){d.getMore(this,e,t,r,n,o)};Server.prototype.killCursors=function(e,t,r){d.killCursors(this,e,t,r)};Server.prototype.insert=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"insert",e,t,r,n))return;t=Array.isArray(t)?t:[t];return d.insert(o,e,t,r,n)};Server.prototype.update=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"update",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.update(o,e,t,r,n)};Server.prototype.remove=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"remove",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.remove(o,e,t,r,n)};Server.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Server.prototype.equals=function(e){if(typeof e==="string")return this.name.toLowerCase()===e.toLowerCase();if(e.name)return this.name.toLowerCase()===e.name.toLowerCase();return false};Server.prototype.connections=function(){return this.s.pool.allConnections()};Server.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;r(null,this)};var k=["close","error","timeout","parseError","connect"];Server.prototype.destroy=function(e,t){if(this._destroyed){if(typeof t==="function")t(null,null);return}if(typeof e==="function"){t=e;e={}}e=e||{};var r=this;if(S)delete v[this.id];if(this.monitoringProcessId){clearTimeout(this.monitoringProcessId)}if(!r.s.pool||this._destroyed){this._destroyed=true;if(typeof t==="function")t(null,null);return}this._destroyed=true;if(e.emitClose){r.emit("close",r)}if(e.emitDestroy){r.emit("destroy",r)}k.forEach((function(e){r.s.pool.removeAllListeners(e)}));if(r.listeners("serverClosed").length>0)r.emit("serverClosed",{topologyId:topologyId(r),address:r.name});if(r.listeners("topologyClosed").length>0&&!r.s.inTopology){r.emit("topologyClosed",{topologyId:topologyId(r)})}if(r.s.logger.isDebug()){r.s.logger.debug(o("destroy called on server %s",r.name))}this.s.pool.destroy(e.force,t)};e.exports=Server},2306:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(4485);const s=r(2291).TopologyType;const i=r(3111).MongoError;const a=r(3111).isRetryableWriteError;const A=r(1178).maxWireVersion;const c=r(3111).MongoNetworkError;const l=n.IllegalOperation;function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}function createCompressionInfo(e){if(!e.compression||!e.compression.compressors){return[]}e.compression.compressors.forEach((function(e){if(e!=="snappy"&&e!=="zlib"){throw new Error("compressors must be at least one of snappy or zlib")}}));return e.compression.compressors}function clone(e){return JSON.parse(JSON.stringify(e))}var getPreviousDescription=function(e){if(!e.s.serverDescription){e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}}return e.s.serverDescription};var emitServerDescriptionChanged=function(e,t){if(e.listeners("serverDescriptionChanged").length>0){e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousDescription(e),newDescription:t});e.s.serverDescription=t}};var getPreviousTopologyDescription=function(e){if(!e.s.topologyDescription){e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}}return e.s.topologyDescription};var emitTopologyDescriptionChanged=function(e,t){if(e.listeners("topologyDescriptionChanged").length>0){e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousTopologyDescription(e),newDescription:t});e.s.serverDescription=t}};var changedIsMaster=function(e,t,r){var n=getTopologyType(e,t);var o=getTopologyType(e,r);if(o!==n)return true;return false};var getTopologyType=function(e,t){if(!t){t=e.ismaster}if(!t)return"Unknown";if(t.ismaster&&t.msg==="isdbgrid")return"Mongos";if(t.ismaster&&!t.hosts)return"Standalone";if(t.ismaster)return"RSPrimary";if(t.secondary)return"RSSecondary";if(t.arbiterOnly)return"RSArbiter";return"Unknown"};var inquireServerState=function(e){return function(t){if(e.s.state==="destroyed")return;var r=(new Date).getTime();emitSDAMEvent(e,"serverHeartbeatStarted",{connectionId:e.name});e.command("admin.$cmd",{ismaster:true},{monitoring:true},(function(n,o){if(!n){e.emit("ismaster",o,e);var s=(new Date).getTime()-r;emitSDAMEvent(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name});if(changedIsMaster(e,e.s.ismaster,o.result)){emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:!e.s.inTopology?"Standalone":getTopologyType(e)})}e.s.ismaster=o.result;e.s.isMasterLatencyMS=s}else{emitSDAMEvent(e,"serverHeartbeatFailed",{durationMS:s,failure:n,connectionId:e.name})}if(typeof t==="function"){return t(n,o)}e.s.inquireServerStateTimeout=setTimeout(inquireServerState(e),e.s.haInterval)}))}};var cloneOptions=function(e){var t={};for(var r in e){t[r]=e[r]}return t};function Interval(e,t){var r=false;this.start=function(){if(!this.isRunning()){r=setInterval(e,t)}return this};this.stop=function(){clearInterval(r);r=false;return this};this.isRunning=function(){return r!==false}}function Timeout(e,t){var r=false;var func=()=>{if(r){clearTimeout(r);r=false;e()}};this.start=function(){if(!this.isRunning()){r=setTimeout(func,t)}return this};this.stop=function(){clearTimeout(r);r=false;return this};this.isRunning=function(){return r!==false}}function diff(e,t){var r={servers:[]};if(!e){e={servers:[]}}for(var n=0;n{if(typeof t==="function")t()}))}};function topologyType(e){if(e.description){return e.description.type}if(e.type==="mongos"){return s.Sharded}else if(e.type==="replset"){return s.ReplicaSetWithPrimary}return s.Single}const h=6;const isRetryableWritesSupported=function(e){const t=e.lastIsMaster().maxWireVersion;if(t{"use strict";const n=r(3111).MongoError;const o=r(4485);const s=r(7289);const i=r(2481);let a;let A;(()=>{const e="NO_TRANSACTION";const t="STARTING_TRANSACTION";const r="TRANSACTION_IN_PROGRESS";const n="TRANSACTION_COMMITTED";const o="TRANSACTION_COMMITTED_EMPTY";const s="TRANSACTION_ABORTED";a={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:o,TRANSACTION_ABORTED:s};A={[e]:[e,t],[t]:[r,n,o,s],[r]:[r,n,s],[n]:[n,o,t,e],[s]:[t,e],[o]:[o,e]}})();class Transaction{constructor(e){e=e||{};this.state=a.NO_TRANSACTION;this.options={};const t=i.fromOptions(e);if(t){if(t.w<=0){throw new n("Transactions do not support unacknowledged write concern")}this.options.writeConcern=t}if(e.readConcern){this.options.readConcern=s.fromOptions(e)}if(e.readPreference){this.options.readPreference=o.fromOptions(e)}if(e.maxCommitTimeMS){this.options.maxTimeMS=e.maxCommitTimeMS}this._pinnedServer=undefined;this._recoveryToken=undefined}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(e){const t=A[this.state];if(t&&t.indexOf(e)!==-1){this.state=e;if(this.state===a.NO_TRANSACTION||this.state===a.STARTING_TRANSACTION||this.state===a.TRANSACTION_ABORTED){this.unpinServer()}return}throw new n(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){if(this.isActive){this._pinnedServer=e}}unpinServer(){this._pinnedServer=undefined}}function isTransactionCommand(e){return!!(e.commitTransaction||e.abortTransaction)}e.exports={TxnState:a,Transaction:Transaction,isTransactionCommand:isTransactionCommand}},8767:(e,t,r)=>{"use strict";const n=r(7310);const o=r(3477);const s=r(7578);const i=r(3111).MongoParseError;const a=r(4485);const A=r(1371).emitWarningOnce;const c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;const l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map((e=>e.toLowerCase())));function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}function parseSrvConnectionString(e,t,r){const a=n.parse(e,true);if(t.directConnection||t.directconnection){return r(new i("directConnection not supported with SRV URI"))}if(a.hostname.split(".").length<3){return r(new i("URI does not have hostname, domain name and tld"))}a.domainLength=a.hostname.split(".").length;const A=e.substring("mongodb+srv://".length).split("/")[0];if(A.match(",")){return r(new i("Invalid URI, cannot contain multiple hostnames"))}if(a.port){return r(new i(`Ports not accepted with '${m}' URIs`))}const c=a.host;s.resolveSrv(`_mongodb._tcp.${c}`,((e,A)=>{if(e)return r(e);if(A.length===0){return r(new i("No addresses found at host"))}for(let e=0;e`${e.name}:${e.port}`)).join(",");if(!("ssl"in t)&&(!a.search||!("ssl"in a.query)||a.query.ssl===null)){a.query.ssl=true}s.resolveTxt(c,((e,s)=>{if(e){if(e.code!=="ENODATA"&&e.code!=="ENOTFOUND"){return r(e)}s=null}if(s){if(s.length>1){return r(new i("Multiple text records not allowed"))}s=o.parse(s[0].join(""));if(Object.keys(s).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(Object.keys(s).some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new i("Text record must only set `authSource` or `replicaSet`"))}a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);const A=n.format(a);parseConnectionString(A,t,((e,t)=>{if(e){r(e);return}r(null,Object.assign({},t,{srvHost:c}))}))}))}))}function parseQueryStringItemValue(e,t){if(Array.isArray(t)){t=t.filter(((e,r)=>t.indexOf(e)===r));if(t.length===1)t=t[0]}else if(t.indexOf(":")>0){t=t.split(",").reduce(((t,r)=>{const n=r.split(":");t[n[0]]=parseQueryStringItemValue(e,n[1]);return t}),{})}else if(t.indexOf(",")>0){t=t.split(",").map((t=>parseQueryStringItemValue(e,t)))}else if(t.toLowerCase()==="true"||t.toLowerCase()==="false"){t=t.toLowerCase()==="true"}else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);if(!Number.isNaN(e)){t=parseFloat(t)}}return t}const u=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]);const h=new Set(["authsource","replicaset"]);const d=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]);const g={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 applyConnectionStringOption(e,t,r,n){if(t==="journal"){t="j"}else if(t==="wtimeoutms"){t="wtimeout"}if(u.has(t)){r=r==="true"||r===true}else if(t==="appname"){r=decodeURIComponent(r)}else if(t==="readconcernlevel"){e["readConcernLevel"]=r;t="readconcern";r={level:r}}if(t==="compressors"){r=Array.isArray(r)?r:[r];if(!r.every((e=>e==="snappy"||e==="zlib"))){throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`")}}if(t==="authmechanism"&&!d.has(r)){throw new i(`Value for authMechanism must be one of: ${Array.from(d).join(", ")}, found: ${r}`)}if(t==="readpreference"&&!a.isValid(r)){throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`")}if(t==="zlibcompressionlevel"&&(r<-1||r>9)){throw new i("zlibCompressionLevel must be an integer between -1 and 9")}if(t==="compressors"||t==="zlibcompressionlevel"){e.compression=e.compression||{};e=e.compression}if(t==="authmechanismproperties"){if(typeof r.SERVICE_NAME==="string")e.gssapiServiceName=r.SERVICE_NAME;if(typeof r.SERVICE_REALM==="string")e.gssapiServiceRealm=r.SERVICE_REALM;if(typeof r.CANONICALIZE_HOST_NAME!=="undefined"){e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME}}if(t==="readpreferencetags"){r=Array.isArray(r)?splitArrayOfMultipleReadPreferenceTags(r):[r]}if(n.caseTranslate&&g[t]){e[g[t]]=r;return}e[t]=r}const p=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function splitArrayOfMultipleReadPreferenceTags(e){const t=[];for(let r=0;r{const n=e.split(":");t[r][n[0]]=n[1]}))}return t}function applyAuthExpectations(e){if(e.options==null){return}const t=e.options;const r=t.authsource||t.authSource;if(r!=null){e.auth=Object.assign({},e.auth,{db:r})}const n=t.authmechanism||t.authMechanism;if(n!=null){if(p.has(n)&&(!e.auth||e.auth.username==null)){throw new i(`Username required for mechanism \`${n}\``)}if(n==="GSSAPI"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null){throw new i(`Password not allowed for mechanism \`${n}\``)}if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="PLAIN"){if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"$external"})}}}if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"admin"})}return e}function parseQueryString(e,t){const r={};let n=o.parse(e);checkTLSOptions(n);for(const e in n){const o=n[e];if(o===""||o==null){throw new i("Incomplete key value pair for option")}const s=e.toLowerCase();if(s==="serverapi"){throw new i("URI cannot contain `serverApi`, it can only be passed to the client")}const a=l.has(s)?o:parseQueryStringItemValue(s,o);applyConnectionStringOption(r,s,a,t)}if(r.wtimeout&&r.wtimeoutms){delete r.wtimeout;A("Unsupported option `wtimeout` specified")}return Object.keys(r).length?r:null}function translateTLSOptions(e){if(e.tls){e.ssl=e.tls}if(e.tlsInsecure){e.checkServerIdentity=false;e.sslValidate=false}else{Object.assign(e,{checkServerIdentity:e.tlsAllowInvalidHostnames?false:true,sslValidate:e.tlsAllowInvalidCertificates?false:true})}if(e.tlsCAFile){e.ssl=true;e.sslCA=e.tlsCAFile}if(e.tlsCertificateKeyFile){e.ssl=true;if(e.tlsCertificateFile){e.sslCert=e.tlsCertificateFile;e.sslKey=e.tlsCertificateKeyFile}else{e.sslKey=e.tlsCertificateKeyFile;e.sslCert=e.tlsCertificateKeyFile}}if(e.tlsCertificateKeyFilePassword){e.ssl=true;e.sslPass=e.tlsCertificateKeyFilePassword}return e}function checkTLSOptions(e){const t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1)){throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.")}const r=assertTlsOptionsAreEqual("tls",e,t);const n=assertTlsOptionsAreEqual("ssl",e,t);if(r!=null&&n!=null){if(r!==n){throw new i("All values of `tls` and `ssl` must be the same.")}}}function assertTlsOptionsAreEqual(e,t,r){const n=r.indexOf(e)!==-1;let o;if(Array.isArray(t[e])){o=t[e][0]}else{o=t[e]}if(n){if(Array.isArray(t[e])){const r=t[e][0];t[e].forEach((t=>{if(t!==r){throw new i(`All values of ${e} must be the same.`)}}))}}return o}const E="mongodb";const m="mongodb+srv";const C=[E,m];function parseConnectionString(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},{caseTranslate:true},t);try{n.parse(e)}catch(e){return r(new i("URI malformed, cannot be parsed"))}const s=e.match(c);if(!s){return r(new i("Invalid connection string"))}const a=s[1];if(C.indexOf(a)===-1){return r(new i("Invalid protocol provided"))}const A=s[4].split("?");const l=A.length>0?A[0]:null;const u=A.length>1?A[1]:null;let h;try{h=parseQueryString(u,t)}catch(e){return r(e)}h=Object.assign({},h,t);if(Object.keys(h).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(a===m){return parseSrvConnectionString(e,h,r)}const d={username:null,password:null,db:l&&l!==""?o.unescape(l):null};if(h.auth){if(h.auth.username)d.username=h.auth.username;if(h.auth.user)d.username=h.auth.user;if(h.auth.password)d.password=h.auth.password}else{if(h.username)d.username=h.username;if(h.user)d.username=h.user;if(h.password)d.password=h.password}if(s[4].split("?")[0].indexOf("@")!==-1){return r(new i("Unescaped slash in userinfo section"))}const g=s[3].split("@");if(g.length>2){return r(new i("Unescaped at-sign in authority section"))}if(g[0]==null||g[0]===""){return r(new i("No username provided in authority section"))}if(g.length>1){const e=g.shift().split(":");if(e.length>2){return r(new i("Unescaped colon in authority section"))}if(e[0]===""){return r(new i("Invalid empty username provided"))}if(!d.username)d.username=o.unescape(e[0]);if(!d.password)d.password=e[1]?o.unescape(e[1]):null}let p=null;const E=g.shift().split(",").map((e=>{let t=n.parse(`mongodb://${e}`);if(t.path==="/:"){p=new i("Double colon in host identifier");return null}if(e.match(/\.sock/)){t.hostname=o.unescape(e);t.port=null}if(Number.isNaN(t.port)){p=new i("Invalid port (non-numeric string)");return}const r={host:t.hostname,port:t.port?parseInt(t.port):27017};if(r.port===0){p=new i("Invalid port (zero) with hostname");return}if(r.port>65535){p=new i("Invalid port (larger than 65535) with hostname");return}if(r.port<0){p=new i("Invalid port (negative number)");return}return r})).filter((e=>!!e));if(p){return r(p)}if(E.length===0||E[0].host===""||E[0].host===null){return r(new i("No hostname or hostnames provided in connection string"))}const I=!!h.directConnection;if(I&&E.length!==1){return r(new i("directConnection option requires exactly one host"))}if(h.directConnection==null&&E.length===1&&h.replicaSet==null){h.directConnection=true}const y={hosts:E,auth:d.db||d.username?d:null,options:Object.keys(h).length?h:null};if(y.auth&&y.auth.db){y.defaultDatabase=y.auth.db}else{y.defaultDatabase="test"}y.options=translateTLSOptions(y.options);try{applyAuthExpectations(y)}catch(e){return r(e)}r(null,y)}e.exports=parseConnectionString},1178:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6113);const s=r(3182)(require);const uuidV4=()=>{const e=o.randomBytes(16);e[6]=e[6]&15|64;e[8]=e[8]&63|128;return e};function relayEvents(e,t,r){r.forEach((r=>e.on(r,(e=>t.emit(r,e)))))}function retrieveKerberos(){let e;try{e=s("kerberos")}catch(e){if(e.code==="MODULE_NOT_FOUND"){throw new Error("The `kerberos` module was not found. Please install it and try again.")}throw e}return e}const noEJSONError=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function retrieveEJSON(){let e=s("mongodb-extjson");if(!e){e={parse:noEJSONError,deserialize:noEJSONError,serialize:noEJSONError,stringify:noEJSONError,setBSONModule:noEJSONError,BSON:noEJSONError}}return e}function maxWireVersion(e){if(e){if(e.ismaster){return e.ismaster.maxWireVersion}if(typeof e.lastIsMaster==="function"){const t=e.lastIsMaster();if(t){return t.maxWireVersion}}if(e.description){return e.description.maxWireVersion}}return 0}function collationNotSupported(e,t){return t&&t.collation&&maxWireVersion(e)<5}function isPromiseLike(e){return e&&typeof e.then==="function"}function eachAsync(e,t,r){e=e||[];let n=0;let o=0;for(n=0;ne===t[r]))}function tagsStrictEqual(e,t){const r=Object.keys(e);const n=Object.keys(t);return r.length===n.length&&r.every((r=>t[r]===e[r]))}function errorStrictEqual(e,t){if(e===t){return true}if(e==null&&t!=null||e!=null&&t==null){return false}if(e.constructor.name!==t.constructor.name){return false}if(e.message!==t.message){return false}return true}function makeStateMachine(e){return function stateTransition(t,r){const n=e[t.s.state];if(n&&n.indexOf(r)<0){throw new TypeError(`illegal state transition from [${t.s.state}] => [${r}], allowed: [${n}]`)}t.emit("stateChanged",t.s.state,r);t.s.state=r}}function makeClientMetadata(e){e=e||{};const t={driver:{name:"nodejs",version:r(1693).i8},os:{type:n.type(),name:process.platform,architecture:process.arch,version:n.release()},platform:`'Node.js ${process.version}, ${n.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo){if(e.driverInfo.name){t.driver.name=`${t.driver.name}|${e.driverInfo.name}`}if(e.driverInfo.version){t.version=`${t.driver.version}|${e.driverInfo.version}`}if(e.driverInfo.platform){t.platform=`${t.platform}|${e.driverInfo.platform}`}}if(e.appname){const r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}const noop=()=>{};e.exports={uuidV4:uuidV4,relayEvents:relayEvents,collationNotSupported:collationNotSupported,retrieveEJSON:retrieveEJSON,retrieveKerberos:retrieveKerberos,maxWireVersion:maxWireVersion,isPromiseLike:isPromiseLike,eachAsync:eachAsync,eachAsyncSeries:eachAsyncSeries,isUnifiedTopology:isUnifiedTopology,arrayStrictEqual:arrayStrictEqual,tagsStrictEqual:tagsStrictEqual,errorStrictEqual:errorStrictEqual,makeStateMachine:makeStateMachine,makeClientMetadata:makeClientMetadata,noop:noop}},7276:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(8988).Msg;const s=r(3111).MongoError;const i=r(7272).getReadPreference;const a=r(7272).isSharded;const A=r(7272).databaseNamespace;const c=r(1707).isTransactionCommand;const l=r(5474).applySession;const u=r(3111).MongoNetworkError;const h=r(1178).maxWireVersion;function isClientEncryptionEnabled(e){const t=h(e);return t&&e.autoEncrypter}function command(e,t,r,n,o){if(typeof n==="function")o=n,n={};n=n||{};if(r==null){return o(new s(`command ${JSON.stringify(r)} does not return a cursor`))}if(!isClientEncryptionEnabled(e)){_command(e,t,r,n,o);return}const i=h(e);if(typeof i!=="number"||i<8){o(new s("Auto-encryption requires a minimum MongoDB version of 4.2"));return}_cryptCommand(e,t,r,n,o)}function _command(e,t,r,h,d){const g=e.s.bson;const p=e.s.pool;const E=i(r,h);const m=supportsOpMsg(e);const C=h.session;const I=e.clusterTime;let y=I;let B=Object.assign({},r);const Q=h.serverApi;if(Q){B.apiVersion=Q.version||Q;if(Q.strict!=null){B.apiStrict=Q.strict}if(Q.deprecationErrors!=null){B.apiDeprecationErrors=Q.deprecationErrors}}if(hasSessionSupport(e)&&C){const e=C.clusterTime;if(I&&I.clusterTime&&e&&e.clusterTime&&e.clusterTime.greaterThan(I.clusterTime)){y=e}if(!C.transaction.isActive&&C.transaction.isPinned&&!B.startTransaction&&!B.commitTransaction){C.transaction.unpinServer()}const t=l(C,B,h);if(t){return d(t)}}if(y){B.$clusterTime=y}if(a(e)&&!m&&E&&E.mode!=="primary"){B={$query:B,$readPreference:E.toJSON()}}const b=Object.assign({command:true,numberToSkip:0,numberToReturn:-1,checkKeys:false},h);b.slaveOk=E.slaveOk();const w=`${A(t)}.$cmd`;const S=m?new o(g,w,B,b):new n(g,w,B,b);const v=C&&(C.inTransaction()||c(B));const R=v?function(e){if(e&&e instanceof u&&!e.hasErrorLabel("TransientTransactionError")){e.addErrorLabel("TransientTransactionError")}if(!r.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")){C.transaction.unpinServer()}return d.apply(null,arguments)}:d;try{p.write(S,b,R)}catch(e){R(e)}}function hasSessionSupport(e){if(e==null)return false;if(e.description){return e.description.maxWireVersion>=6}return e.ismaster==null?false:e.ismaster.maxWireVersion>=6}function supportsOpMsg(e){const t=e.ismaster?e.ismaster:e.description;if(t==null){return false}return t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}function _cryptCommand(e,t,r,n,o){const s=e.autoEncrypter;function commandResponseHandler(e,t){if(e||t==null){o(e,t);return}s.decrypt(t.result,n,((e,r)=>{if(e){o(e,null);return}t.result=r;t.message.documents=[r];o(null,t)}))}s.encrypt(t,r,n,((r,s)=>{if(r){o(r,null);return}_command(e,t,s,n,commandResponseHandler)}))}e.exports=command},7793:(e,t,r)=>{"use strict";const n=r(7746).retrieveSnappy();const o=r(9796);const s={snappy:1,zlib:2};const i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function compress(e,t,r){switch(e.options.agreedCompressor){case"snappy":n.compress(t,r);break;case"zlib":var s={};if(e.options.zlibCompressionLevel){s.level=e.options.zlibCompressionLevel}o.deflate(t,s,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}function decompress(e,t,r){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:n.uncompress(t,r);break;case s.zlib:o.inflate(t,r);break;default:r(null,t)}}e.exports={compressorIDs:s,uncompressibleCommands:i,compress:compress,decompress:decompress}},7161:e=>{"use strict";const t="2.6";const r="5.0";const n=2;const o=13;e.exports={MIN_SUPPORTED_SERVER_VERSION:t,MAX_SUPPORTED_SERVER_VERSION:r,MIN_SUPPORTED_WIRE_VERSION:n,MAX_SUPPORTED_WIRE_VERSION:o}},1971:(e,t,r)=>{"use strict";const n=r(9814).GetMore;const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=o();const A=a.Long;const c=r(7272).collectionNamespace;const l=r(1178).maxWireVersion;const u=r(7272).applyCommonQueryOptions;const h=r(7276);function getMore(e,t,r,o,a,d){a=a||{};const g=l(e);function queryCallback(e,t){if(e)return d(e);const n=t.message;if(n.cursorNotFound){return d(new i("cursor killed or timed out"),null)}if(g<4){const e=typeof n.cursorId==="number"?A.fromNumber(n.cursorId):n.cursorId;r.documents=n.documents;r.cursorId=e;d(null,null,n.connection);return}if(n.documents[0].ok===0){return d(new s(n.documents[0]))}const o=typeof n.documents[0].cursor.id==="number"?A.fromNumber(n.documents[0].cursor.id):n.documents[0].cursor.id;r.documents=n.documents[0].cursor.nextBatch;r.cursorId=o;d(null,n.documents[0],n.connection)}if(g<4){const s=e.s.bson;const i=new n(s,t,r.cursorId,{numberToReturn:o});const a=u({},r);e.s.pool.write(i,a,queryCallback);return}const p=r.cursorId instanceof A?r.cursorId:A.fromNumber(r.cursorId);const E={getMore:p,collection:c(t),batchSize:Math.abs(o)};if(r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS==="number"){E.maxTimeMS=r.cmd.maxAwaitTimeMS}const m=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},a);if(r.session){m.session=r.session}h(e,t,E,m,queryCallback)}e.exports=getMore},9206:(e,t,r)=>{"use strict";const n=r(779);e.exports={insert:function insert(e,t,r,o,s){n(e,"insert","documents",t,r,o,s)},update:function update(e,t,r,o,s){n(e,"update","updates",t,r,o,s)},remove:function remove(e,t,r,o,s){n(e,"delete","deletes",t,r,o,s)},killCursors:r(6044),getMore:r(1971),query:r(1820),command:r(7276)}},6044:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(3111).MongoError;const s=r(3111).MongoNetworkError;const i=r(7272).collectionNamespace;const a=r(1178).maxWireVersion;const A=r(1178).emitWarning;const c=r(7276);function killCursors(e,t,r,l,u){if(typeof l==="function"){u=l;l={}}u=typeof u==="function"?u:()=>{};const h=r.cursorId;if(a(e)<4){const o=e.s.bson;const s=e.s.pool;const i=new n(o,t,[h]);const a={immediateRelease:true,noResponse:true};if(typeof r.session==="object"){a.session=r.session}if(s&&s.isConnected()){try{s.write(i,a,u)}catch(e){if(typeof u==="function"){u(e,null)}else{A(e)}}}return}const d={killCursors:i(t),cursors:[h]};const g=l||{};if(typeof r.session==="object")g.session=r.session;c(e,t,d,g,((e,t)=>{if(e){return u(e)}const r=t.message;if(r.cursorNotFound){return u(new s("cursor killed or timed out"),null)}if(!Array.isArray(r.documents)||r.documents.length===0){return u(new o(`invalid killCursors result returned for cursor id ${h}`))}u(null,r.documents[0])}))}e.exports=killCursors},1820:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(3111).MongoError;const s=r(7272).getReadPreference;const i=r(7272).collectionNamespace;const a=r(7272).isSharded;const A=r(1178).maxWireVersion;const c=r(7272).applyCommonQueryOptions;const l=r(7276);const u=r(1371).decorateWithExplain;const h=r(5293).Explain;function query(e,t,r,n,i,a){i=i||{};if(n.cursorId!=null){return a()}if(r==null){return a(new o(`command ${JSON.stringify(r)} does not return a cursor`))}if(A(e)<4){const o=prepareLegacyFindQuery(e,t,r,n,i);const s=c({},n);if(typeof o.documentsReturnedIn==="string"){s.documentsReturnedIn=o.documentsReturnedIn}e.s.pool.write(o,s,a);return}const d=s(r,i);let g=prepareFindCommand(e,t,r,n,i);try{const e=h.fromOptions(i);if(e){g=u(g,e)}}catch(e){return a(e)}r.virtual=false;const p=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:d.slaveOk()},i);if(r.readPreference){p.readPreference=d}if(n.session){p.session=n.session}l(e,t,g,p,a)}function prepareFindCommand(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;const o={find:i(t)};if(r.query){if(r.query["$query"]){o.filter=r.query["$query"]}else{o.filter=r.query}}let s=r.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];if(t==="asc"){t=1}else if(t==="desc"){t=-1}e[s[0]]=t}else{for(let t=0;t0&&i.batchSize===0){u=i.limit}else{u=i.batchSize}const h=i.skip||0;const d={};if(a(e)&&l){d["$readPreference"]=l.toJSON()}if(r.sort)d["$orderby"]=r.sort;if(r.hint)d["$hint"]=r.hint;if(r.snapshot)d["$snapshot"]=r.snapshot;if(typeof r.returnKey!=="undefined")d["$returnKey"]=r.returnKey;if(r.maxScan)d["$maxScan"]=r.maxScan;if(r.min)d["$min"]=r.min;if(r.max)d["$max"]=r.max;if(typeof r.showDiskLoc!=="undefined")d["$showDiskLoc"]=r.showDiskLoc;if(r.comment)d["$comment"]=r.comment;if(r.maxTimeMS)d["$maxTimeMS"]=r.maxTimeMS;if(A.explain!==undefined){u=-Math.abs(r.limit||0);d["$explain"]=true}d["$query"]=r.query;if(r.readConcern&&r.readConcern.level!=="local"){throw new o(`server find command does not support a readConcern level of ${r.readConcern.level}`)}if(r.readConcern){r=Object.assign({},r);delete r["readConcern"]}const g=typeof A.serializeFunctions==="boolean"?A.serializeFunctions:false;const p=typeof A.ignoreUndefined==="boolean"?A.ignoreUndefined:false;const E=new n(c,t,d,{numberToSkip:h,numberToReturn:u,pre32Limit:typeof r.limit!=="undefined"?r.limit:undefined,checkKeys:false,returnFieldSelector:r.fields,serializeFunctions:g,ignoreUndefined:p});if(typeof r.tailable==="boolean")E.tailable=r.tailable;if(typeof r.oplogReplay==="boolean")E.oplogReplay=r.oplogReplay;if(typeof r.noCursorTimeout==="boolean")E.noCursorTimeout=r.noCursorTimeout;if(typeof r.awaitData==="boolean")E.awaitData=r.awaitData;if(typeof r.partial==="boolean")E.partial=r.partial;E.slaveOk=l.slaveOk();return E}e.exports=query},7272:(e,t,r)=>{"use strict";const n=r(4485);const o=r(3111).MongoError;const s=r(2291).ServerType;const i=r(7962).TopologyDescription;const a=16;const A=9;var c={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};var getReadPreference=function(e,t){var r=e.readPreference||new n("primary");if(t.readPreference){r=t.readPreference}if(typeof r==="string"){r=new n(r)}if(!(r instanceof n)){throw new o("read preference must be a ReadPreference instance")}return r};var parseHeader=function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}};function applyCommonQueryOptions(e,t){Object.assign(e,{raw:typeof t.raw==="boolean"?t.raw:false,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,monitoring:typeof t.monitoring==="boolean"?t.monitoring:false,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false});if(typeof t.socketTimeout==="number"){e.socketTimeout=t.socketTimeout}if(t.session){e.session=t.session}if(typeof t.documentsReturnedIn==="string"){e.documentsReturnedIn=t.documentsReturnedIn}return e}function isSharded(e){if(e.type==="mongos")return true;if(e.description&&e.description.type===s.Mongos){return true}if(e.description&&e.description instanceof i){const t=Array.from(e.description.servers.values());return t.some((e=>e.type===s.Mongos))}return false}function databaseNamespace(e){return e.split(".")[0]}function collectionNamespace(e){return e.split(".").slice(1).join(".")}e.exports={getReadPreference:getReadPreference,MESSAGE_HEADER_SIZE:a,COMPRESSION_DETAILS_SIZE:A,opcodes:c,parseHeader:parseHeader,applyCommonQueryOptions:applyCommonQueryOptions,isSharded:isSharded,databaseNamespace:databaseNamespace,collectionNamespace:collectionNamespace}},779:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(7272).collectionNamespace;const s=r(7276);const i=r(1371).decorateWithExplain;const a=r(5293).Explain;function writeCommand(e,t,r,A,c,l,u){if(c.length===0)throw new n(`${t} must contain at least one document`);if(typeof l==="function"){u=l;l={}}l=l||{};const h=typeof l.ordered==="boolean"?l.ordered:true;const d=l.writeConcern;let g={};g[t]=o(A);g[r]=c;g.ordered=h;if(d&&Object.keys(d).length>0){g.writeConcern=d}if(l.collation){for(let e=0;e{"use strict";const n=r(2781).Transform;const o=r(2781).PassThrough;const s=r(3837).deprecate;const i=r(1371).handleCallback;const a=r(3994).ReadPreference;const A=r(3994).MongoError;const c=r(4847).CoreCursor;const l=r(4847).CursorState;const u=r(3994).BSON.Map;const h=r(1371).maybePromise;const d=r(2548);const g=r(1371).formattedOrderClause;const p=r(5293).Explain;const E=r(1018).Aspect;const m=r(3554).each;const C=r(7885);const I=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];const y=["numberOfRetries","tailableRetryInterval"];class Cursor extends c{constructor(e,t,r,n){super(e,t,r,n);if(this.operation){n=this.operation.options}const o=n.numberOfRetries||5;const s=n.tailableRetryInterval||500;const i=o;const a=n.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!n.explicitlyIgnoreSession};if(!n.explicitlyIgnoreSession&&n.session){this.cursorState.session=n.session}if(this.options.noCursorTimeout===true){this.addCursorFlag("noCursorTimeout",true)}let A=1e3;if(this.cmd.cursor&&this.cmd.cursor.batchSize){A=this.cmd.cursor.batchSize}else if(n.cursor&&n.cursor.batchSize){A=n.cursor.batchSize}else if(typeof n.batchSize==="number"){A=n.batchSize}this.setCursorBatchSize(A)}get readPreference(){if(this.operation){return this.operation.readPreference}return this.options.readPreference}get sortValue(){return this.cmd.sort}set session(e){this.cursorState.session=e}_initializeCursor(e){if(this.operation&&this.operation.session!=null){this.cursorState.session=this.operation.session}else{if(!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()){this.cursorState.session=this.topology.startSession({owner:this});if(this.operation){this.operation.session=this.cursorState.session}}}super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}return h(this,e,(e=>{const t=this;if(t.isNotified()){return e(null,false)}t._next(((r,n)=>{if(r)return e(r);if(n==null||t.s.state===Cursor.CLOSED||t.isDead()){return e(null,false)}t.s.state=l.OPEN;t.cursorState.cursorIndex--;if(t.cursorState.limit>0){t.cursorState.currentLimit--}e(null,true)}))}))}next(e){return h(this,e,(e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead()){e(A.create({message:"Cursor is closed",driver:true}));return}if(t.s.state===l.INIT&&t.cmd.sort){try{t.cmd.sort=g(t.cmd.sort)}catch(t){return e(t)}}t._next(((r,n)=>{if(r)return e(r);t.s.state=l.OPEN;e(null,n)}))}))}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.query=e;return this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxScan=e;return this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.hint=e;return this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.min=e;return this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.max=e;return this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.returnKey=e;return this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.showDiskLoc=e;return this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.snapshot=e;return this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(y.indexOf(e)===-1){throw A.create({message:`option ${e} is not a supported option ${y}`,driver:true})}this.s[e]=t;if(e==="numberOfRetries")this.s.currentNumberOfRetries=t;return this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(I.indexOf(e)===-1){throw A.create({message:`flag ${e} is not a supported flag ${I}`,driver:true})}if(typeof t!=="boolean"){throw A.create({message:`flag ${e} must be a boolean value`,driver:true})}this.cmd[e]=t;return this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(e[0]!=="$"){throw A.create({message:`${e} is not a valid query modifier`,driver:true})}const r=e.substr(1);this.cmd[r]=t;if(r==="orderby")this.cmd.sort=this.cmd[r];return this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.comment=e;return this}maxAwaitTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxAwaitTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxAwaitTimeMS=e;return this}maxTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxTimeMS=e;return this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.fields=e;return this}sort(e,t){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support sorting",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}let r=e;if(Array.isArray(r)&&Array.isArray(r[0])){r=new u(r.map((e=>{const t=[e[0],null];if(e[1]==="asc"){t[1]=1}else if(e[1]==="desc"){t[1]=-1}else if(e[1]===1||e[1]===-1||e[1].$meta){t[1]=e[1]}else{throw new A("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}return t})))}if(t!=null){r=[[e,t]]}this.cmd.sort=r;return this}batchSize(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support batchSize",driver:true})}if(this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"batchSize requires an integer",driver:true})}this.cmd.batchSize=e;this.setCursorBatchSize(e);return this}collation(e){this.cmd.collation=e;return this}limit(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support limit",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"limit requires an integer",driver:true})}this.cmd.limit=e;this.setCursorLimit(e);return this}skip(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support skip",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"skip requires an integer",driver:true})}this.cmd.skip=e;this.setCursorSkip(e);return this}each(e){this.rewind();this.s.state=l.INIT;m(this,e)}forEach(e,t){this.rewind();this.s.state=l.INIT;if(typeof t==="function"){m(this,((r,n)=>{if(r){t(r);return false}if(n!=null){try{e(n)}catch(e){t(e);return false}return true}if(n==null&&t){const e=t;t=null;e(null);return false}}))}else{return new this.s.promiseLibrary(((t,r)=>{m(this,((n,o)=>{if(n){r(n);return false}else if(o==null){t(null);return false}else{try{e(o)}catch(e){r(e);return false}return true}}))}))}}setReadPreference(e){if(this.s.state!==l.INIT){throw A.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof a){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new a(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}toArray(e){if(this.options.tailable){throw A.create({message:"Tailable cursor cannot be converted to array",driver:true})}return h(this,e,(e=>{const t=this;const r=[];t.rewind();t.s.state=l.INIT;const fetchDocs=()=>{t._next(((n,o)=>{if(n){return i(e,n)}if(o==null){return t.close({skipKillCursors:true},(()=>i(e,null,r)))}r.push(o);if(t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(r,e)}fetchDocs()}))};fetchDocs()}))}count(e,t,r){if(this.cmd.query==null)throw A.create({message:"count can only be used with find command",driver:true});if(typeof t==="function")r=t,t={};t=t||{};if(typeof e==="function"){r=e;e=true}if(this.cursorState.session){t=Object.assign({},t,{session:this.cursorState.session})}const n=new C(this,e,t);return d(this.topology,n,r)}close(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{skipKillCursors:false},e);return h(this,t,(t=>{this.s.state=l.CLOSED;if(!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=r=>e(t(r))}else{this.cursorState.transforms={doc:e}}return this}isClosed(){return this.isDead()}destroy(e){if(e)this.emit("error",e);this.pause();this.close()}stream(e){this.cursorState.streamOptions=e||{};return this}transformStream(e){const t=e||{};if(typeof t.transform==="function"){const e=new n({objectMode:true,transform:function(e,r,n){this.push(t.transform(e));n()}});return this.pipe(e)}return this.pipe(new o({objectMode:true}))}explain(e,t){if(typeof e==="function")t=e,e=true;if(e===undefined)e=true;if(!this.operation||!this.operation.hasAspect(E.EXPLAINABLE)){throw new A("This command cannot be explained")}this.operation.explain=new p(e);return h(this,t,(e=>{c.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}Cursor.prototype.maxTimeMs=Cursor.prototype.maxTimeMS;s(Cursor.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");s(Cursor.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");s(Cursor.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");e.exports=Cursor},6662:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(3837).inherits;const s=r(1371).getSingleProperty;const i=r(538);const a=r(1371).handleCallback;const A=r(1371).filterOptions;const c=r(1371).toError;const l=r(3994).ReadPreference;const u=r(3994).MongoError;const h=r(3994).ObjectID;const d=r(3994).Logger;const g=r(5193);const p=r(1371).conditionallyMergeWriteConcern;const E=r(1371).executeLegacyOperation;const m=r(1117);const C=r(3837).deprecate;const I=r(1371).deprecateOptions;const y=r(1371).MongoDBNamespace;const B=r(147);const Q=r(2481);const b=r(7289);const w=r(7429);const S=r(2226).createListener;const v=r(2226).ensureIndex;const R=r(2226).evaluate;const k=r(2226).profilingInfo;const D=r(2226).validateDatabaseName;const N=r(1554);const T=r(7057);const O=r(286);const _=r(499);const M=r(1363);const L=r(5561);const F=r(6394);const U=r(2360).DropCollectionOperation;const P=r(2360).DropDatabaseOperation;const G=r(1681);const Y=r(4245);const V=r(840);const W=r(3969);const J=r(1969);const q=r(2808);const j=r(6301);const z=r(2548);const $=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function Db(e,t,r){r=r||{};if(!(this instanceof Db))return new Db(e,t,r);n.call(this);const o=r.promiseLibrary||Promise;r=A(r,$);r.promiseLibrary=o;this.s={dbCache:{},children:[],topology:t,options:r,logger:d("Db",r),bson:t?t.bson:null,readPreference:l.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||h,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:o,noListener:typeof r.noListener==="boolean"?r.noListener:false,readConcern:b.fromOptions(r),writeConcern:Q.fromOptions(r),namespace:new y(e)};D(e);s(this,"serverConfig",this.s.topology);s(this,"bufferMaxEntries",this.s.bufferMaxEntries);s(this,"databaseName",this.s.namespace.db);if(r.parentDb)return;if(this.s.noListener)return;t.on("error",S(this,"error",this));t.on("timeout",S(this,"timeout",this));t.on("close",S(this,"close",this));t.on("parseError",S(this,"parseError",this));t.once("open",S(this,"open",this));t.once("fullsetup",S(this,"fullsetup",this));t.once("all",S(this,"all",this));t.on("reconnect",S(this,"reconnect",this))}o(Db,n);Db.prototype.on=C((function(){return Db.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Db.prototype.once=C((function(){return Db.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(Db.prototype,"topology",{enumerable:true,get:function(){return this.s.topology}});Object.defineProperty(Db.prototype,"options",{enumerable:true,get:function(){return this.s.options}});Object.defineProperty(Db.prototype,"slaveOk",{enumerable:true,get:function(){if(this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")){return true}return false}});Object.defineProperty(Db.prototype,"readConcern",{enumerable:true,get:function(){return this.s.readConcern}});Object.defineProperty(Db.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return l.primary}return this.s.readPreference}});Object.defineProperty(Db.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(Db.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Db.prototype.command=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);const n=new M(this,e,t);return z(this.s.topology,n,r)};Db.prototype.aggregate=function(e,t,r){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}const n=new w(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Db.prototype.admin=function(){const e=r(3238);return new e(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];Db.prototype.collection=I({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t=Object.assign({},t);t.promiseLibrary=this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;if(this.s.options.ignoreUndefined){t.ignoreUndefined=this.s.options.ignoreUndefined}for(const e of K){if(!(e in t)&&this.s.options[e]!==undefined){t[e]=this.s.options[e]}}t=p(t,this.s.options);if(t==null||!t.strict){try{const n=new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);if(r)r(null,n);return n}catch(e){if(e instanceof u&&r)return r(e);throw e}}if(typeof r!=="function"){throw c(`A callback is required in strict mode. While getting collection ${e}`)}if(this.serverConfig&&this.serverConfig.isDestroyed()){return r(new u("topology was destroyed"))}const n=Object.assign({},t,{nameOnly:true});this.listCollections({name:e},n).toArray(((n,o)=>{if(n!=null)return a(r,n,null);if(o.length===0)return a(r,c(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(r,null,new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(n){return a(r,n,null)}}))}));Db.prototype.createCollection=I({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;const n=new L(this,e,t);return z(this.s.topology,n,r)}));Db.prototype.stats=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={dbStats:true};if(e["scale"]!=null)r["scale"]=e["scale"];if(e.readPreference==null&&this.s.readPreference){e.readPreference=this.s.readPreference}const n=new _(this,e,null,r);return z(this.s.topology,n,t)};Db.prototype.listCollections=function(e,t){e=e||{};t=t||{};return new i(this.s.topology,new V(this,e,t),t)};Db.prototype.eval=C((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():t;r=o.length?o.shift()||{}:{};return E(this.s.topology,R,[this,e,t,r,n])}),"Db.eval is deprecated as of MongoDB version 3.2");Db.prototype.renameCollection=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r,{readPreference:l.PRIMARY});r.new_collection=true;const o=new q(this.collection(e),t,r);return z(this.s.topology,o,n)};Db.prototype.dropCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new U(this,e,t);return z(this.s.topology,n,r)};Db.prototype.dropDatabase=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new P(this,e);return z(this.s.topology,r,t)};Db.prototype.collections=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new O(this,e);return z(this.s.topology,r,t)};Db.prototype.executeDbAdminCommand=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.readPreference=l.resolve(this,t);const n=new G(this,e,t);return z(this.s.topology,n,r)};Db.prototype.createIndex=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r?Object.assign({},r):{};const o=new F(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.ensureIndex=C((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return E(this.s.topology,v,[this,e,t,r,n])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");Db.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};Db.prototype.addUser=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}const o=new T(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.removeUser=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new J(this,e,t);return z(this.s.topology,n,r)};Db.prototype.setProfilingLevel=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new j(this,e,t);return z(this.s.topology,n,r)};Db.prototype.profilingInfo=C((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return E(this.s.topology,k,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly.");Db.prototype.profilingLevel=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new W(this,e);return z(this.s.topology,r,t)};Db.prototype.indexInformation=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new Y(this,e,t);return z(this.s.topology,n,r)};Db.prototype.unref=function(){this.s.topology.unref()};Db.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Db.prototype.getLogger=function(){return this.s.logger};Db.SYSTEM_NAMESPACE_COLLECTION=B.SYSTEM_NAMESPACE_COLLECTION;Db.SYSTEM_INDEX_COLLECTION=B.SYSTEM_INDEX_COLLECTION;Db.SYSTEM_PROFILE_COLLECTION=B.SYSTEM_PROFILE_COLLECTION;Db.SYSTEM_USER_COLLECTION=B.SYSTEM_USER_COLLECTION;Db.SYSTEM_COMMAND_COLLECTION=B.SYSTEM_COMMAND_COLLECTION;Db.SYSTEM_JS_COLLECTION=B.SYSTEM_JS_COLLECTION;e.exports=Db},8275:(e,t,r)=>{"use strict";let n;let o;let s;function loadCollection(){if(!n){n=r(5193)}return n}function loadCursor(){if(!o){o=r(7159)}return o}function loadDb(){if(!s){s=r(6662)}return s}e.exports={loadCollection:loadCollection,loadCursor:loadCursor,loadDb:loadDb}},3012:(e,t,r)=>{"use strict";const n=r(1545);const o=r(7746).retrieveBSON();const s=r(3111).MongoError;let i=undefined;try{i=r(5764)}catch(e){throw new s("Auto-encryption requested, but the module is not installed. "+"Please add `mongodb-client-encryption` as a dependency of your project")}if(i===undefined||typeof i.extension!=="function"){throw new s("loaded version of `mongodb-client-encryption` does not have property `extension`. "+"Please make sure you are loading the correct version of `mongodb-client-encryption`")}const a=i.extension(r(5517)).AutoEncrypter;const A=Symbol("internalClient");class Encrypter{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption;this.needsConnecting=false;if(t.maxPoolSize===0&&t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=e}else if(t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=this.getInternalClient(e)}if(this.bypassAutoEncryption){t.autoEncryption.metadataClient=undefined}else if(t.maxPoolSize===0){t.autoEncryption.metadataClient=e}else{t.autoEncryption.metadataClient=this.getInternalClient(e)}t.autoEncryption.bson=Encrypter.makeBSON(t);this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[A]){const t={};for(const r of Object.keys(e.s.options)){if(["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(r)!==-1)continue;t[r]=e.s.options[r]}t.minPoolSize=0;const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[A]=new n(e.s.url,t);for(const t of r){for(const r of e.listeners(t)){this[A].on(t,r)}}e.on("newListener",((e,t)=>{this[A].on(e,t)}));this.needsConnecting=true}return this[A]}connectInternalClient(e){if(this.needsConnecting){this.needsConnecting=false;return this[A].connect(e)}return e()}close(e,t,r){this.autoEncrypter.teardown((n=>{if(this[A]&&e!==this[A]){return this[A].close(t,r)}r(n)}))}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:Encrypter}},9386:(e,t,r)=>{"use strict";const n=r(3994).MongoNetworkError;const o=r(8072).MONGODB_ERROR_CODES;const s=new Set([o.HostUnreachable,o.HostNotFound,o.NetworkTimeout,o.ShutdownInProgress,o.PrimarySteppedDown,o.ExceededTimeLimit,o.SocketException,o.NotMaster,o.InterruptedAtShutdown,o.InterruptedDueToReplStateChange,o.NotMasterNoSlaveOk,o.NotMasterOrSecondary,o.StaleShardVersion,o.StaleEpoch,o.StaleConfig,o.RetryChangeStream,o.FailedToSatisfyReadPreference,o.CursorNotFound]);function isResumableError(e,t){if(e instanceof n){return true}if(t>=9){if(e.code===o.CursorNotFound){return true}return e.hasErrorLabel("ResumableChangeStreamError")}return s.has(e.code)}e.exports={GET_MORE_RESUMABLE_CODES:s,isResumableError:isResumableError,MONGODB_ERROR_CODES:o}},8072:e=>{"use strict";const t=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});e.exports=Object.freeze({MONGODB_ERROR_CODES:t})},5293:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class Explain{constructor(e){if(typeof e==="boolean"){this.verbosity=e?"allPlansExecution":"queryPlanner"}else{this.verbosity=e}}static fromOptions(e){if(e==null||e.explain===undefined){return}const t=e.explain;if(typeof t==="boolean"||typeof t==="string"){return new Explain(e.explain)}throw new n(`explain must be a string or a boolean`)}}e.exports={Explain:Explain}},4190:(e,t,r)=>{"use strict";var n=r(2781),o=r(3837);e.exports=GridFSBucketReadStream;function GridFSBucketReadStream(e,t,r,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:false,expectedEnd:0,file:null,options:s,readPreference:r};n.Readable.call(this)}o.inherits(GridFSBucketReadStream,n.Readable);GridFSBucketReadStream.prototype._read=function(){var e=this;if(this.destroyed){return}waitForFile(e,(function(){doRead(e)}))};GridFSBucketReadStream.prototype.start=function(e){throwIfInitialized(this);this.s.options.start=e;return this};GridFSBucketReadStream.prototype.end=function(e){throwIfInitialized(this);this.s.options.end=e;return this};GridFSBucketReadStream.prototype.abort=function(e){var t=this;this.push(null);this.destroyed=true;if(this.s.cursor){this.s.cursor.close((function(r){t.emit("close");e&&e(r)}))}else{if(!this.s.init){t.emit("close")}e&&e()}};function throwIfInitialized(e){if(e.s.init){throw new Error("You cannot change options after the stream has entered"+"flowing mode!")}}function doRead(e){if(e.destroyed){return}e.s.cursor.next((function(t,r){if(e.destroyed){return}if(t){return __handleError(e,t)}if(!r){e.push(null);process.nextTick((()=>{e.s.cursor.close((function(t){if(t){__handleError(e,t);return}e.emit("close")}))}));return}var n=e.s.file.length-e.s.bytesRead;var o=e.s.expected++;var s=Math.min(e.s.file.chunkSize,n);if(r.n>o){var i="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+o;return __handleError(e,new Error(i))}if(r.n0){i["n"]={$gte:a}}}e.s.cursor=e.s.chunks.find(i).sort({n:1});if(e.s.readPreference){e.s.cursor.setReadPreference(e.s.readPreference)}e.s.expectedEnd=Math.ceil(r.length/r.chunkSize);e.s.file=r;try{e.s.bytesToTrim=handleEndOption(e,r,e.s.cursor,e.s.options)}catch(t){return __handleError(e,t)}e.emit("file",r)}))}function waitForFile(e,t){if(e.s.file){return t()}if(!e.s.init){init(e);e.s.init=true}e.once("file",(function(){t()}))}function handleStartOption(e,t,r){if(r&&r.start!=null){if(r.start>t.length){throw new Error("Stream start ("+r.start+") must not be "+"more than the length of the file ("+t.length+")")}if(r.start<0){throw new Error("Stream start ("+r.start+") must not be "+"negative")}if(r.end!=null&&r.endt.length){throw new Error("Stream end ("+n.end+") must not be "+"more than the length of the file ("+t.length+")")}if(n.start<0){throw new Error("Stream end ("+n.end+") must not be "+"negative")}var o=n.start!=null?Math.floor(n.start/t.chunkSize):0;r.limit(Math.ceil(n.end/t.chunkSize)-o);e.s.expectedEnd=Math.ceil(n.end/t.chunkSize);return Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}function __handleError(e,t){e.emit("error",t)}},2573:(e,t,r)=>{"use strict";var n=r(2361).EventEmitter;var o=r(4190);var s=r(1413);var i=r(1371).shallowClone;var a=r(1371).toError;var A=r(3837);var c=r(1371).executeLegacyOperation;const l=r(1371).deprecateOptions;var u={bucketName:"fs",chunkSizeBytes:255*1024};e.exports=GridFSBucket;function GridFSBucket(e,t){n.apply(this);this.setMaxListeners(0);if(t&&typeof t==="object"){t=i(t);var r=Object.keys(u);for(var o=0;o=0){r={uploadDate:1};n=t.revision}else{n=-t.revision-1}}var s={filename:e};t={sort:r,skip:n,start:t&&t.start,end:t&&t.end};return new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)};GridFSBucket.prototype.rename=function(e,t,r){return c(this.s.db.s.topology,_rename,[this,e,t,r],{skipSessions:true})};function _rename(e,t,r,n){var o={_id:t};var s={$set:{filename:r}};e.s._filesCollection.updateOne(o,s,(function(e,r){if(e){return n(e)}if(!r.result.n){return n(a("File with id "+t+" not found"))}n()}))}GridFSBucket.prototype.drop=function(e){return c(this.s.db.s.topology,_drop,[this,e],{skipSessions:true})};GridFSBucket.prototype.getLogger=function(){return this.s.db.s.logger};function _drop(e,t){e.s._filesCollection.drop((function(r){if(r){return t(r)}e.s._chunksCollection.drop((function(e){if(e){return t(e)}return t()}))}))}},1413:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(3994);const s=r(6113);const i=r(2781);const a=r(3837);const A=r(1867).Buffer;const c=r(1371).deprecateOptions;const l=c({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},(function(e,t,r){r=r||{};i.Writable.call(this,r);this.bucket=e;this.chunks=e.s._chunksCollection;this.filename=t;this.files=e.s._filesCollection;this.options=r;this.done=false;this.id=r.id?r.id:o.BSON.ObjectId();this.chunkSizeBytes=this.options.chunkSizeBytes;this.bufToStore=A.alloc(this.chunkSizeBytes);this.length=0;this.md5=!r.disableMD5&&s.createHash("md5");this.n=0;this.pos=0;this.state={streamEnd:false,outstandingRequests:0,errored:false,aborted:false,promiseLibrary:this.bucket.s.promiseLibrary};if(!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=true;var n=this;checkIndexes(this,(function(){n.bucket.s.checkedIndexes=true;n.bucket.emit("index")}))}}));a.inherits(l,i.Writable);l.prototype.write=function(e,t,r){var n=this;return waitForIndexes(this,(function(){return doWrite(n,e,t,r)}))};l.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}if(this.state.aborted){t=new Error("Cannot call abort() on a stream twice");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}this.state.aborted=true;this.chunks.deleteMany({files_id:this.id},(function(t){if(typeof e==="function")e(t)}))};l.prototype.end=function(e,t,r){var n=this;if(typeof e==="function"){r=e,e=null,t=null}else if(typeof t==="function"){r=t,t=null}if(checkAborted(this,r)){return}this.state.streamEnd=true;if(r){this.once("finish",(function(e){r(null,e)}))}if(!e){waitForIndexes(this,(function(){writeRemnant(n)}));return}this.write(e,t,(function(){writeRemnant(n)}))};function __handleError(e,t,r){if(e.state.errored){return}e.state.errored=true;if(r){return r(t)}e.emit("error",t)}function createChunkDoc(e,t,r){return{_id:o.BSON.ObjectId(),files_id:e,n:t,data:r}}function checkChunksIndex(e,t){e.chunks.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={files_id:1,n:1};e.chunks.createIndex(s,{background:false,unique:true},(function(e){if(e){return t(e)}t()}));return}return t(r)}var i=false;o.forEach((function(e){if(e.key){var t=Object.keys(e.key);if(t.length===2&&e.key.files_id===1&&e.key.n===1){i=true}}}));if(i){t()}else{s={files_id:1,n:1};var a=getWriteOptions(e);a.background=false;a.unique=true;e.chunks.createIndex(s,a,(function(e){if(e){return t(e)}t()}))}}))}function checkDone(e,t){if(e.done)return true;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=true;var r=createFilesDoc(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);if(checkAborted(e,t)){return false}e.files.insertOne(r,getWriteOptions(e),(function(n){if(n){return __handleError(e,n,t)}e.emit("finish",r);e.emit("close")}));return true}return false}function checkIndexes(e,t){e.files.findOne({},{_id:1},(function(r,o){if(r){return t(r)}if(o){return t()}e.files.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={filename:1,uploadDate:1};e.files.createIndex(s,{background:false},(function(r){if(r){return t(r)}checkChunksIndex(e,t)}));return}return t(r)}var i=false;o.forEach((function(e){var t=Object.keys(e.key);if(t.length===2&&e.key.filename===1&&e.key.uploadDate===1){i=true}}));if(i){checkChunksIndex(e,t)}else{s={filename:1,uploadDate:1};var a=getWriteOptions(e);a.background=false;e.files.createIndex(s,a,(function(r){if(r){return t(r)}checkChunksIndex(e,t)}))}}))}))}function createFilesDoc(e,t,r,n,o,s,i,a){var A={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:o};if(n){A.md5=n}if(s){A.contentType=s}if(i){A.aliases=i}if(a){A.metadata=a}return A}function doWrite(e,t,r,n){if(checkAborted(e,n)){return false}var o=A.isBuffer(t)?t:A.from(t,r);e.length+=o.length;if(e.pos+o.length0){var l=o.length-s;o.copy(e.bufToStore,e.pos,l,l+a);e.pos+=a;i-=a;if(i===0){if(e.md5){e.md5.update(e.bufToStore)}var u=createChunkDoc(e.id,e.n,A.from(e.bufToStore));++e.state.outstandingRequests;++c;if(checkAborted(e,n)){return false}e.chunks.insertOne(u,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;--c;if(!c){e.emit("drain",u);n&&n();checkDone(e)}}));i=e.chunkSizeBytes;e.pos=0;++e.n}s-=a;a=Math.min(i,s)}return false}function getWriteOptions(e){var t={};if(e.options.writeConcern){t.w=e.options.writeConcern.w;t.wtimeout=e.options.writeConcern.wtimeout;t.j=e.options.writeConcern.j}return t}function waitForIndexes(e,t){if(e.bucket.s.checkedIndexes){return t(false)}e.bucket.once("index",(function(){t(true)}));return true}function writeRemnant(e,t){if(e.pos===0){return checkDone(e,t)}++e.state.outstandingRequests;var r=A.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);if(e.md5){e.md5.update(r)}var n=createChunkDoc(e.id,e.n,r);if(checkAborted(e,t)){return false}e.chunks.insertOne(n,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;checkDone(e)}))}function checkAborted(e,t){if(e.state.aborted){if(typeof t==="function"){t(new Error("this stream has been aborted"))}return true}return false}e.exports=l},3890:(e,t,r)=>{"use strict";var n=r(3994).BSON.Binary,o=r(3994).BSON.ObjectID;var s=r(1867).Buffer;var Chunk=function(e,t,r){if(!(this instanceof Chunk))return new Chunk(e,t);this.file=e;var i=t==null?{}:t;this.writeConcern=r||{w:1};this.objectId=i._id==null?new o:i._id;this.chunkNumber=i.n==null?0:i.n;this.data=new n;if(typeof i.data==="string"){var a=s.alloc(i.data.length);a.write(i.data,0,i.data.length,"binary");this.data=new n(a)}else if(Array.isArray(i.data)){a=s.alloc(i.data.length);var A=i.data.join("");a.write(A,0,A.length,"binary");this.data=new n(a)}else if(i.data&&i.data._bsontype==="Binary"){this.data=i.data}else if(!s.isBuffer(i.data)&&!(i.data==null)){throw Error("Illegal chunk format")}this.internalPosition=0};Chunk.prototype.write=function(e,t){this.data.write(e,this.internalPosition,e.length,"binary");this.internalPosition=this.data.length();if(t!=null)return t(null,this);return this};Chunk.prototype.read=function(e){e=e==null||e===0?this.length():e;if(this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);this.internalPosition=this.internalPosition+e;return t}else{return""}};Chunk.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;if(this.data.buffer!=null){t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e)}else{t=s.alloc(e);e=this.data.readInto(t,this.internalPosition)}this.internalPosition=this.internalPosition+e;return t}else{return null}};Chunk.prototype.eof=function(){return this.internalPosition===this.length()?true:false};Chunk.prototype.getc=function(){return this.read(1)};Chunk.prototype.rewind=function(){this.internalPosition=0;this.data=new n};Chunk.prototype.save=function(e,t){var r=this;if(typeof e==="function"){t=e;e={}}r.file.chunkCollection((function(n,o){if(n)return t(n);var s={upsert:true};for(var i in e)s[i]=e[i];for(i in r.writeConcern)s[i]=r.writeConcern[i];if(r.data.length()>0){r.buildMongoObject((function(e){var n={forceServerObjectId:true};for(var i in r.writeConcern){n[i]=r.writeConcern[i]}o.replaceOne({_id:r.objectId},e,s,(function(e){t(e,r)}))}))}else{t(null,r)}}))};Chunk.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};if(this.objectId!=null)t._id=this.objectId;e(t)};Chunk.prototype.length=function(){return this.data.length()};Object.defineProperty(Chunk.prototype,"position",{enumerable:true,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Chunk.DEFAULT_CHUNK_SIZE=1024*255;e.exports=Chunk},9406:(e,t,r)=>{"use strict";const n=r(3890);const o=r(3994).BSON.ObjectID;const s=r(3994).ReadPreference;const i=r(1867).Buffer;const a=r(7147);const A=r(3837).format;const c=r(3837);const l=r(3994).MongoError;const u=c.inherits;const h=r(2781).Duplex;const d=r(1371).shallowClone;const g=r(1371).executeLegacyOperation;const p=r(3837).deprecate;var E=0,m=1;const C=p((()=>{}),"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var I=function GridStore(e,t,r,i,a){C();if(!(this instanceof GridStore))return new GridStore(e,t,r,i,a);this.db=e;if(typeof a==="undefined")a={};if(typeof i==="undefined"){i=r;r=undefined}else if(typeof i==="object"){a=i;i=r;r=undefined}if(t&&t._bsontype==="ObjectID"){this.referenceBy=m;this.fileId=t;this.filename=r}else if(typeof r==="undefined"){this.referenceBy=E;this.filename=t;if(i.indexOf("w")!=null){this.fileId=new o}}else{this.referenceBy=m;this.fileId=t;this.filename=r}this.mode=i==null?"r":i;this.options=a||{};this.isOpen=false;this.root=this.options["root"]==null?GridStore.DEFAULT_ROOT_COLLECTION:this.options["root"];this.position=0;this.readPreference=this.options.readPreference||e.options.readPreference||s.primary;this.writeConcern=_getWriteConcern(e,this.options);this.internalChunkSize=this.options["chunkSize"]==null?n.DEFAULT_CHUNK_SIZE:this.options["chunkSize"];var A=this.options.promiseLibrary||Promise;this.promiseLibrary=A;Object.defineProperty(this,"chunkSize",{enumerable:true,get:function(){return this.internalChunkSize},set:function(e){if(!(this.mode[0]==="w"&&this.position===0&&this.uploadDate==null)){this.internalChunkSize=this.internalChunkSize}else{this.internalChunkSize=e}}});Object.defineProperty(this,"md5",{enumerable:true,get:function(){return this.internalMd5}});Object.defineProperty(this,"chunkNumber",{enumerable:true,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};I.prototype.open=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r"){throw l.create({message:"Illegal mode "+this.mode,driver:true})}return g(this.db.s.topology,open,[this,e,t],{skipSessions:true})};var open=function(e,t,r){var n=_getWriteConcern(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var o=e.collection();o.ensureIndex([["filename",1]],n,(function(){var t=e.chunkCollection();var o=d(n);o.unique=true;t.ensureIndex([["files_id",1],["n",1]],o,(function(){_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}))}))}else{_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}};I.prototype.eof=function(){return this.position===this.length?true:false};I.prototype.getc=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,getc,[this,e,t],{skipSessions:true})};var getc=function(e,t,r){if(e.eof()){r(null,null)}else if(e.currentChunk.eof()){nthChunk(e,e.currentChunk.chunkNumber+1,(function(t,n){e.currentChunk=n;e.position=e.position+1;r(t,e.currentChunk.getc())}))}else{e.position=e.position+1;r(null,e.currentChunk.getc())}};I.prototype.puts=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};var n=e.match(/\n$/)==null?e+"\n":e;return g(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:true})};I.prototype.stream=function(){return new GridStoreStream(this)};I.prototype.write=function write(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return g(this.db.s.topology,_writeNormal,[this,e,t,r,n],{skipSessions:true})};I.prototype.destroy=function destroy(){if(!this.writable)return;this.readable=false;if(this.writable){this.writable=false;this._q.length=0;this.emit("close")}};I.prototype.writeFile=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return g(this.db.s.topology,writeFile,[this,e,t,r],{skipSessions:true})};var writeFile=function(e,t,r,o){if(typeof t==="string"){a.open(t,"r",(function(t,r){if(t)return o(t);e.writeFile(r,o)}));return}e.open((function(e,r){if(e)return o(e,r);a.fstat(t,(function(e,s){if(e)return o(e,r);var A=0;var c=0;var writeChunk=function(){var e=i.alloc(r.chunkSize);a.read(t,e,0,e.length,A,(function(e,i,l){if(e)return o(e,r);A=A+i;var u=new n(r,{n:c++},r.writeConcern);u.write(l.slice(0,i),(function(e,n){if(e)return o(e,r);n.save({},(function(e){if(e)return o(e,r);r.position=r.position+i;r.currentChunk=n;if(A>=s.size){a.close(t,(function(e){if(e)return o(e);r.close((function(e){if(e)return o(e,r);return o(null,r)}))}))}else{return process.nextTick(writeChunk)}}))}))}))};process.nextTick(writeChunk)}))}))};I.prototype.close=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,close,[this,e,t],{skipSessions:true})};var close=function(e,t,r){if(e.mode[0]==="w"){t=Object.assign({},e.writeConcern,t);if(e.currentChunk!=null&&e.currentChunk.position>0){e.currentChunk.save({},(function(n){if(n&&typeof r==="function")return r(n);e.collection((function(n,o){if(n&&typeof r==="function")return r(n);if(e.uploadDate!=null){buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}else{e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}}))}))}else{e.collection((function(n,o){if(n&&typeof r==="function")return r(n);e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}))}}else if(e.mode[0]==="r"){if(typeof r==="function")r(null,null)}else{if(typeof r==="function")r(l.create({message:A("Illegal mode %s",e.mode),driver:true}))}};I.prototype.chunkCollection=function(e){if(typeof e==="function")return this.db.collection(this.root+".chunks",e);return this.db.collection(this.root+".chunks")};I.prototype.unlink=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,unlink,[this,e,t],{skipSessions:true})};var unlink=function(e,t,r){deleteChunks(e,(function(t){if(t!==null){t.message="at deleteChunks: "+t.message;return r(t)}e.collection((function(t,n){if(t!==null){t.message="at collection: "+t.message;return r(t)}n.remove({_id:e.fileId},e.writeConcern,(function(t){r(t,e)}))}))}))};I.prototype.collection=function(e){if(typeof e==="function")this.db.collection(this.root+".files",e);return this.db.collection(this.root+".files")};I.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift():"\n";e=e||"\n";t=n.length?n.shift():{};return g(this.db.s.topology,readlines,[this,e,t,r],{skipSessions:true})};var readlines=function(e,t,r,n){e.read((function(e,r){if(e)return n(e);var o=r.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var A=e.currentChunk.readSlice(s-a._index);A.copy(a,a._index);e.position=e.position+a.length;if(s===0&&a.length===0)return o(l.create({message:"File does not exist",driver:true}),null);return o(null,a)}A=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position);A.copy(a,a._index);a._index+=A.length;nthChunk(e,e.currentChunk.chunkNumber+1,(function(r,n){if(r)return o(r);if(n.length()>0){e.currentChunk=n;e.read(t,a,o)}else{if(a._index>0){o(null,a)}else{o(l.create({message:"no chunks found for file, possibly corrupt",driver:true}),null)}}}))};I.prototype.tell=function(e){var t=this;if(typeof e==="function")return e(null,this.position);return new t.promiseLibrary((function(e){e(t.position)}))};I.prototype.seek=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():null;r=o.length?o.shift():{};return g(this.db.s.topology,seek,[this,e,t,r,n],{skipSessions:true})};var seek=function(e,t,r,n,o){if(e.mode!=="r"){return o(l.create({message:"seek is only supported for mode r",driver:true}))}var s=r==null?I.IO_SEEK_SET:r;var i=t;var a=0;if(s===I.IO_SEEK_CUR){a=e.position+i}else if(s===I.IO_SEEK_END){a=e.length+i}else{a=i}var A=Math.floor(a/e.chunkSize);var seekChunk=function(){nthChunk(e,A,(function(t,r){if(t)return o(t,null);if(r==null)return o(new Error("no chunk found"));e.currentChunk=r;e.position=a;e.currentChunk.position=e.position%e.chunkSize;o(t,e)}))};seekChunk()};var _open=function(e,t,r){var s=e.collection();var i=e.referenceBy===m?{_id:e.fileId}:{filename:e.filename};i=null==e.fileId&&e.filename==null?null:i;t.readPreference=e.readPreference;if(i!=null){s.findOne(i,t,(function(s,i){if(s){return error(s)}if(i!=null){e.fileId=i._id;e.filename=e.mode==="r"||e.filename===undefined?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(e.mode!=="r"){e.fileId=e.fileId==null?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0}else{e.length=0;var a=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return error(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?a:e.filename),driver:true}),e)}if(e.mode==="r"){nthChunk(e,0,t,(function(t,n){if(t)return error(t);e.currentChunk=n;e.position=0;r(null,e)}))}else if(e.mode==="w"&&i){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w"){e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}))}else{e.fileId=null==e.fileId?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0;if(e.mode==="w"){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}function error(e){if(error.err)return;r(error.err=e)}};var writeBuffer=function(e,t,r,o){if(typeof r==="function"){o=r;r=null}var s=typeof r==="boolean"?r:false;if(e.mode!=="w"){o(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?e.referenceBy:e.filename),driver:true}),null)}else{if(e.currentChunk.position+t.length>=e.chunkSize){var i=e.currentChunk.chunkNumber;var a=e.chunkSize-e.currentChunk.position;var c=t.slice(0,a);var u=t.slice(a);var h=[e.currentChunk.write(c)];while(u.length>=e.chunkSize){var d=new n(e,{n:i+1},e.writeConcern);c=u.slice(0,e.chunkSize);u=u.slice(e.chunkSize);i=i+1;d.write(c);h.push(d)}e.currentChunk=new n(e,{n:i+1},e.writeConcern);if(u.length>0)e.currentChunk.write(u);e.position=e.position+t.length;var g=h.length;for(var p=0;p=t.length)return s("offset larger than size of file",null);if(r&&r>t.length)return s("length is larger than the size of the file",null);if(n&&r&&n+r>t.length)return s("offset and length is larger than the size of the file",null);if(n!=null){t.seek(n,(function(e,t){if(e)return s(e);t.read(r,s)}))}else{t.read(r,s)}}))};I.readlines=function(e,t,r,n,o){var s=Array.prototype.slice.call(arguments,2);o=typeof s[s.length-1]==="function"?s.pop():undefined;r=s.length?s.shift():null;n=s.length?s.shift():null;n=n||{};return g(e.s.topology,readlinesStatic,[e,t,r,n,o],{skipSessions:true})};var readlinesStatic=function(e,t,r,n,o){var s=r==null?"\n":r;new I(e,t,"r",n).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};I.unlink=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift():{};r=r||{};return g(e.s.topology,unlinkStatic,[this,e,t,r,n],{skipSessions:true})};var unlinkStatic=function(e,t,r,n,o){var s=_getWriteConcern(t,n);if(r.constructor===Array){var i=0;for(var a=0;ae.totalBytesToRead){e.totalBytesToRead=e.totalBytesToRead-r._index;e.push(r.slice(0,r._index))}if(e.totalBytesToRead<=0){e.endCalled=true}}))};var t=e.gs.length{"use strict";const n=r(1117);const o=r(6662);const s=r(2361).EventEmitter;const i=r(3837).inherits;const a=r(3994).MongoError;const A=r(3994).ValidServerApiVersions;const c=r(3837).deprecate;const l=r(2481);const u=r(1371).MongoDBNamespace;const h=r(4485);const d=r(1371).maybePromise;const g=r(2632);const p=r(5210).connect;const E=r(5210).validOptions;function MongoClient(e,t){t=t||{};if(!(this instanceof MongoClient))return new MongoClient(e,t);s.call(this);if(t.autoEncryption)r(3012);if(t.serverApi){const e=typeof t.serverApi==="string"?{version:t.serverApi}:t.serverApi;const r=e&&e.version;if(!r){throw new a(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${A.join('", "')}"]`)}if(!A.some((e=>e===r))){throw new a(`Invalid server API version=${r}; must be in the following enum: ["${A.join('", "')}"]`)}t.serverApi=e}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:l.fromOptions(t),readPreference:h.fromOptions(t)||h.primary,namespace:new u("admin")}}i(MongoClient,s);Object.defineProperty(MongoClient.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(MongoClient.prototype,"readPreference",{enumerable:true,get:function(){return this.s.readPreference}});MongoClient.prototype.connect=function(e){if(typeof e==="string"){throw new TypeError("`connect` only accepts a callback")}const t=this;return d(this,e,(e=>{const r=E(t.s.options);if(r)return e(r);p(t,t.s.url,t.s.options,(r=>{if(r)return e(r);e(null,t)}))}))};MongoClient.prototype.logout=c((function(e,t){if(typeof e==="function")t=e,e={};if(typeof t==="function")t(null,true)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");MongoClient.prototype.close=function(e,t){if(typeof e==="function"){t=e;e=false}const r=this;return d(this,t,(t=>{const completeClose=e=>{r.emit("close",r);if(!(r.topology instanceof g)){for(const e of r.s.dbCache){e[1].emit("close",r)}}r.removeAllListeners("close");t(e)};if(r.topology==null){completeClose();return}r.topology.close(e,(t=>{const n=r.topology.s.options.encrypter;if(n){return n.close(r,e,(e=>{completeClose(t||e)}))}completeClose(t)}))}))};MongoClient.prototype.db=function(e,t){t=t||{};if(!e){e=this.s.options.dbName}const r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==true){return this.s.dbCache.get(e)}r.promiseLibrary=this.s.promiseLibrary;if(!this.topology){throw new a("MongoClient must be connected before calling MongoClient.prototype.db")}const n=new o(e,this.topology,r);this.s.dbCache.set(e,n);return n};MongoClient.prototype.isConnected=c((function(e){e=e||{};if(!this.topology)return false;return this.topology.isConnected(e)}),"isConnected is deprecated and will be removed in the next major version");MongoClient.connect=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():null;t=t||{};const o=new MongoClient(e,t);return o.connect(r)};MongoClient.prototype.startSession=function(e){e=Object.assign({explicit:true},e);if(!this.topology){throw new a("Must connect to a server before calling this method")}return this.topology.startSession(e,this.s.options)};MongoClient.prototype.withSession=function(e,t){if(typeof e==="function")t=e,e=undefined;const r=this.startSession(e);let cleanupHandler=(e,t,n)=>{cleanupHandler=()=>{throw new ReferenceError("cleanupHandler was called too many times")};n=Object.assign({throw:true},n);r.endSession();if(e){if(n.throw)throw e;return Promise.reject(e)}};try{const e=t(r);return Promise.resolve(e).then((e=>cleanupHandler(null,e))).catch((e=>cleanupHandler(e,null,{throw:true})))}catch(e){return cleanupHandler(e,null,{throw:false})}};MongoClient.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new n(this,e,t)};MongoClient.prototype.getLogger=function(){return this.s.options.logger};e.exports=MongoClient},7057:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(6113);const a=r(1371).handleCallback;const A=r(1371).toError;const c=r(1371).emitWarning;class AddUserOperation extends o{constructor(e,t,r,n){super(e,n);this.username=t;this.password=r}_buildCommand(){const e=this.db;const t=this.username;const r=this.password;const n=this.options;let o=[];if(Array.isArray(n.roles))o=n.roles;if(typeof n.roles==="string")o=[n.roles];if(o.length===0){c("Creating a user without roles is deprecated in MongoDB >= 2.6")}if((e.databaseName.toLowerCase()==="admin"||n.dbName==="admin")&&!Array.isArray(n.roles)){o=["root"]}else if(!Array.isArray(n.roles)){o=["dbOwner"]}const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=r;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+r);a=e.digest("hex")}const A={createUser:t,customData:n.customData||{},roles:o,digestPassword:s};if(typeof r==="string"){A.pwd=a}return A}execute(e){const t=this.options;if(t.digestPassword!=null){return e(A("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."))}super.execute(((t,r)=>{if(!t){return a(e,t,r)}return a(e,t,null)}))}}s(AddUserOperation,n.WRITE_OPERATION);e.exports=AddUserOperation},1554:(e,t,r)=>{"use strict";const n=r(1189);const o=r(3994).MongoError;const s=r(1178).maxWireVersion;const i=r(3994).ReadPreference;const a=r(1018).Aspect;const A=r(1018).defineAspects;const c=1;const l=8;class AggregateOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:c;this.pipeline=t;this.hasWriteStage=false;if(typeof r.out==="string"){this.pipeline=this.pipeline.concat({$out:r.out});this.hasWriteStage=true}else if(t.length>0){const e=t[t.length-1];if(e.$out||e.$merge){this.hasWriteStage=true}}if(this.hasWriteStage){this.readPreference=i.primary}if(this.explain&&this.writeConcern){throw new o('"explain" cannot be used on an aggregate call with writeConcern')}if(r.cursor!=null&&typeof r.cursor!=="object"){throw new o("cursor options must be an object")}}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const r=this.options;const n=s(e);const o={aggregate:this.target,pipeline:this.pipeline};if(this.hasWriteStage&&n=5){if(this.hasWriteStage&&this.writeConcern){Object.assign(o,{writeConcern:this.writeConcern})}}if(r.bypassDocumentValidation===true){o.bypassDocumentValidation=r.bypassDocumentValidation}if(typeof r.allowDiskUse==="boolean"){o.allowDiskUse=r.allowDiskUse}if(r.hint){o.hint=r.hint}if(this.explain){r.full=false}o.cursor=r.cursor||{};if(r.batchSize&&!this.hasWriteStage){o.cursor.batchSize=r.batchSize}super.executeCommand(e,o,t)}}A(AggregateOperation,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]);e.exports=AggregateOperation},6976:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(3994).MongoError;const i=r(1018).OperationBase;class BulkWriteOperation extends i{constructor(e,t,r){super(r);this.collection=e;this.operations=t}execute(e){const t=this.collection;const r=this.operations;let i=this.options;if(t.s.options.ignoreUndefined){i=Object.assign({},i);i.ignoreUndefined=t.s.options.ignoreUndefined}const a=i.ordered===true||i.ordered==null?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let A=false;try{for(let e=0;e{if(!r&&t){return e(t,null)}e(null,r)}))}}e.exports=BulkWriteOperation},6716:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(2226).createIndex;const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(2226).ensureIndex;const c=r(2226).evaluate;const l=r(2226).executeCommand;const u=r(1371).handleCallback;const h=r(2226).indexInformation;const d=r(3994).BSON.Long;const g=r(3994).MongoError;const p=r(3994).ReadPreference;const E=r(2296).insertDocuments;const m=r(2296).updateDocuments;const C='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}';function createIndex(e,t,r,n){s(e.s.db,e.collectionName,t,r,n)}function createIndexes(e,t,r,n){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}));h.group.key=e}d=Object.assign({},d);d.readPreference=p.resolve(e,d);a(h,e,d);try{i(h,e,d)}catch(e){return g(e,null)}l(e.s.db,h,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.retval)}))}else{const i=s!=null&&s._bsontype==="Code"?s.scope:{};i.ns=e.collectionName;i.keys=t;i.condition=r;i.initial=n;const a=C.replace(/ reduce;/,s.toString()+";");c(e.s.db,new o(a,i),null,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.result||t)}))}}function indexes(e,t,r){t=Object.assign({},{full:true},t);h(e.s.db,e.collectionName,t,r)}function indexExists(e,t,r,n){indexInformation(e,r,((e,r)=>{if(e!=null)return u(n,e,null);if(!Array.isArray(t))return u(n,null,r[t]!=null);for(let e=0;e{if(n)return u(r,n,null);if(s==null)return u(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:true},t);const i=[];if(o)t.raw=o;for(let r=0;r{if(o==null)return;if(t==null)return u(o,null,null);if(e)return u(o,e,null);u(o,null,r)}))}e.exports={createIndex:createIndex,createIndexes:createIndexes,ensureIndex:ensureIndex,group:group,indexes:indexes,indexExists:indexExists,indexInformation:indexInformation,parallelCollectionScan:parallelCollectionScan,save:save}},286:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;let s;function loadCollection(){if(!s){s=r(5193)}return s}class CollectionsOperation extends n{constructor(e,t){super(t);this.db=e}execute(e){const t=this.db;let r=this.options;let n=loadCollection();r=Object.assign({},r,{nameOnly:true});t.listCollections({},r).toArray(((r,s)=>{if(r!=null)return o(e,r,null);s=s.filter((e=>e.name.indexOf("$")===-1));o(e,null,s.map((e=>new n(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options))))}))}}e.exports=CollectionsOperation},499:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(1371).applyWriteConcern;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=r(1371).MongoDBNamespace;const u=r(7703).extractCommand;const h=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];class CommandOperation extends o{constructor(e,t,r,o){super(t);if(!this.hasAspect(n.WRITE_OPERATION)){if(r!=null){this.options.readPreference=c.resolve(r,t)}else{this.options.readPreference=c.resolve(e,t)}}else{if(r!=null){s(this.options,{db:e,coll:r},this.options)}else{s(this.options,{db:e},this.options)}this.options.readPreference=c.primary}this.db=e;if(o!=null){this.command=o}if(r!=null){this.collection=r}}_buildCommand(){if(this.command!=null){return this.command}}execute(e){const t=this.db;const r=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new A("topology was destroyed"))}let o;try{o=this._buildCommand()}catch(t){return e(t)}const s=r.dbName||r.authdb||t.databaseName;if(this.hasAspect(n.WRITE_OPERATION)){if(r.writeConcern&&(!r.session||!r.session.inTransaction())){o.writeConcern=r.writeConcern}}if(t.s.logger.isDebug()){const e=u(o);t.s.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:o)} against ${s}.$cmd with options [${JSON.stringify(i(h,r))}]`)}const c=this.namespace!=null?this.namespace:new l(s,"$cmd");t.s.topology.command(c,o,r,((t,n)=>{if(t)return a(e,t);if(r.full)return a(e,null,n);a(e,null,n.result)}))}}e.exports=CommandOperation},1189:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(3994).ReadPreference;const i=r(7289);const a=r(2481);const A=r(1178).maxWireVersion;const c=r(1371).decorateWithExplain;const l=r(5474).commandSupportsReadConcern;const u=r(3111).MongoError;const h=r(7703).extractCommand;const d=5;class CommandOperationV2 extends o{constructor(e,t,r){super(t);this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(n.NO_INHERIT_OPTIONS)?undefined:e;this.readPreference=this.hasAspect(n.WRITE_OPERATION)?s.primary:s.resolve(o,this.options);this.readConcern=resolveReadConcern(o,this.options);this.writeConcern=resolveWriteConcern(o,this.options);if(r&&typeof r.fullResponse==="boolean"){this.fullResponse=true}this.options.readPreference=this.readPreference;if(e.s.logger){this.logger=e.s.logger}else if(e.s.db&&e.s.db.logger){this.logger=e.s.db.logger}}executeCommand(e,t,r){this.server=e;const o=this.options;const s=A(e);const i=this.session&&this.session.inTransaction();if(this.readConcern&&l(t)&&!i){Object.assign(t,{readConcern:this.readConcern})}if(o.collation&&s=d){if(this.writeConcern&&this.hasAspect(n.WRITE_OPERATION)){Object.assign(t,{writeConcern:this.writeConcern})}if(o.collation&&typeof o.collation==="object"){Object.assign(t,{collation:o.collation})}}if(typeof o.maxTimeMS==="number"){t.maxTimeMS=o.maxTimeMS}if(typeof o.comment==="string"){t.comment=o.comment}if(this.hasAspect(n.EXPLAINABLE)&&this.explain){if(s<6&&t.aggregate){t.explain=true}else{t=c(t,this.explain)}}if(this.logger&&this.logger.isDebug()){const e=h(t);this.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:t)} against ${this.ns}`)}e.command(this.ns.toString(),t,this.options,((e,t)=>{if(e){r(e,null);return}if(this.fullResponse){r(null,t);return}r(null,t.result)}))}}function resolveWriteConcern(e,t){return a.fromOptions(t)||e&&e.writeConcern}function resolveReadConcern(e,t){return i.fromOptions(t)||e&&e.readConcern}e.exports=CommandOperationV2},2296:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).MongoError;const u=r(3994).ReadPreference;const h=r(1371).toError;const d=r(4847).CursorState;const g=r(1178).maxWireVersion;function buildCountCommand(e,t,r){const n=r.skip;const o=r.limit;let a=r.hint;const A=r.maxTimeMS;t=t||{};const c={count:r.collectionName,query:t};if(e.s.numberOfRetries){if(e.options.hint){a=e.options.hint}else if(e.cmd.hint){a=e.cmd.hint}s(c,e,e.cmd)}else{s(c,e,r)}if(typeof n==="number")c.skip=n;if(typeof o==="number")c.limit=o;if(typeof A==="number")c.maxTimeMS=A;if(a)c.hint=a;i(c,e);return c}function findAndModify(e,t,r,i,l,h){const d={findAndModify:e.collectionName,query:t};r=A(r);if(r){d.sort=r}d.new=l.new?true:false;d.remove=l.remove?true:false;d.upsert=l.upsert?true:false;const g=l.projection||l.fields;if(g){d.fields=g}if(l.arrayFilters){d.arrayFilters=l.arrayFilters;delete l.arrayFilters}if(i&&!l.remove){d.update=i}if(l.maxTimeMS)d.maxTimeMS=l.maxTimeMS;l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions;l.checkKeys=false;let p=Object.assign({},l);p=n(p,e.s.db);p=o(p,{db:e.s.db,collection:e},l);if(p.writeConcern){d.writeConcern=p.writeConcern}if(p.bypassDocumentValidation===true){d.bypassDocumentValidation=p.bypassDocumentValidation}p.readPreference=u.primary;try{s(d,e,p)}catch(e){return h(e,null)}a(e.s.db,d,p,((e,t)=>{if(e)return c(h,e,null);return c(h,null,t)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new l("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(h(e));if(!Array.isArray(t))return c(n,null,[]);if(o)return c(n,null,t);c(n,null,processResults(t))}))}function prepareDocs(e,t,r){const n=typeof r.forceServerObjectId==="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;if(n===true){return t}return t.map((t=>{if(n!==true&&t._id==null){t._id=e.s.pkFactory.createPk()}return t}))}function nextObject(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead()){return c(t,l.create({message:"Cursor is closed",driver:true}))}if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort){try{e.cmd.sort=A(e.cmd.sort)}catch(e){return c(t,e)}}e._next(((r,n)=>{e.s.state=d.OPEN;if(r)return c(t,r);c(t,null,n)}))}function insertDocuments(e,t,r,s){if(typeof r==="function")s=r,r={};r=r||{};t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=n(i,e.s.db);i=o(i,{db:e.s.db,collection:e},r);if(i.keepGoing===true)i.ordered=false;i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions;t=prepareDocs(e,t,r);e.s.topology.insert(e.s.namespace,t,i,((e,r)=>{if(s==null)return;if(e)return c(s,e);if(r==null)return c(s,null,null);if(r.result.code)return c(s,h(r.result));if(r.result.writeErrors)return c(s,h(r.result.writeErrors[0]));r.ops=t;c(s,null,r)}))}function removeDocuments(e,t,r,i){if(typeof r==="function"){i=r,r={}}else if(typeof t==="function"){i=t;r={};t={}}r=r||{};let a=Object.assign({},r);a=n(a,e.s.db);a=o(a,{db:e.s.db,collection:e},r);if(t==null)t={};const A={q:t,limit:0};if(r.single){A.limit=1}else if(a.retryWrites){a.retryWrites=false}if(r.hint){A.hint=r.hint}try{s(a,e,r)}catch(e){return i(e,null)}if(r.explain!==undefined&&g(e.s.topology)<3){return i?i(new l(`server does not support explain on remove`)):undefined}e.s.topology.remove(e.s.namespace,[A],a,((e,t)=>{if(i==null)return;if(e)return c(i,e,null);if(t==null)return c(i,null,null);if(t.result.code)return c(i,h(t.result));if(t.result.writeErrors){return c(i,h(t.result.writeErrors[0]))}c(i,null,t)}))}function updateDocuments(e,t,r,i,a){if("function"===typeof i)a=i,i=null;if(i==null)i={};if(!("function"===typeof a))a=null;if(t==null||typeof t!=="object")return a(h("selector must be a valid JavaScript object"));if(r==null||typeof r!=="object")return a(h("document must be a valid JavaScript object"));let A=Object.assign({},i);A=n(A,e.s.db);A=o(A,{db:e.s.db,collection:e},i);A.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const u={q:t,u:r};u.upsert=i.upsert!==void 0?!!i.upsert:false;u.multi=i.multi!==void 0?!!i.multi:false;if(i.hint){u.hint=i.hint}if(A.arrayFilters){u.arrayFilters=A.arrayFilters;delete A.arrayFilters}if(A.retryWrites&&u.multi){A.retryWrites=false}try{s(A,e,i)}catch(e){return a(e,null)}if(i.explain!==undefined&&g(e.s.topology)<3){return a?a(new l(`server does not support explain on update`)):undefined}e.s.topology.update(e.s.namespace,[u],A,((e,t)=>{if(a==null)return;if(e)return c(a,e,null);if(t==null)return c(a,null,null);if(t.result.code)return c(a,h(t.result));if(t.result.writeErrors)return c(a,h(t.result.writeErrors[0]));c(a,null,t)}))}e.exports={buildCountCommand:buildCountCommand,findAndModify:findAndModify,indexInformation:indexInformation,nextObject:nextObject,prepareDocs:prepareDocs,insertDocuments:insertDocuments,removeDocuments:removeDocuments,updateDocuments:updateDocuments}},5210:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(3994).Logger;const s=r(3994).MongoCredentials;const i=r(3994).MongoError;const a=r(2048);const A=r(2632);const c=r(3994).parseConnectionString;const l=r(7289);const u=r(3994).ReadPreference;const h=r(382);const d=r(8421);const g=r(3994).Sessions.ServerSessionPool;const p=r(1371).emitDeprecationWarning;const E=r(1371).emitWarningOnce;const m=r(7147);const C=r(2481);const I=r(897).CMAP_EVENT_NAMES;let y;function loadClient(){if(!y){y=r(1545)}return y}const B=n(r(8729),"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.");const Q={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"};const b=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"];const w=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]);const S=["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","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","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"];const v=["native_parser"];const R=["server","replset","replSet","mongos","db"];function validOptions(e){const t=S.concat(R);for(const r in e){if(v.indexOf(r)!==-1){continue}if(t.indexOf(r)===-1){if(e.validateOptions){return new i(`option ${r} is not supported`)}else{E(`the options [${r}] is not supported`)}}if(R.indexOf(r)!==-1){E(`the server/replset/mongos/db options are deprecated, `+`all their options are supported at the top level of the options object [${S}]`)}}}const k=S.reduce(((e,t)=>{e[t.toLowerCase()]=t;return e}),{});function addListeners(e,t){t.on("authenticated",createListener(e,"authenticated"));t.on("error",createListener(e,"error"));t.on("timeout",createListener(e,"timeout"));t.on("close",createListener(e,"close"));t.on("parseError",createListener(e,"parseError"));t.once("open",createListener(e,"open"));t.once("fullsetup",createListener(e,"fullsetup"));t.once("all",createListener(e,"all"));t.on("reconnect",createListener(e,"reconnect"))}function assignTopology(e,t){e.topology=t;if(!(t instanceof A)){t.s.sessionPool=new g(t.s.coreTopology)}}function clearAllEvents(e){b.forEach((t=>e.removeAllListeners(t)))}function collectEvents(e,t){let r=loadClient();const n=[];if(e instanceof r){b.forEach((r=>{t.on(r,((t,o)=>{if(r==="open"){n.push({event:r,object1:e})}else{n.push({event:r,object1:t,object2:o})}}))}))}return n}function resolveTLSOptions(e){if(e.tls==null){return}["sslCA","sslKey","sslCert"].forEach((t=>{if(e[t]){e[t]=m.readFileSync(e[t])}}))}function connect(e,t,r,n){r=Object.assign({},r);if(n==null){throw new Error("no callback function provided")}let s=false;const A=o("MongoClient",r);if(t instanceof d||t instanceof h||t instanceof a){return connectWithUrl(e,t,r,connectCallback)}const l=r.useNewUrlParser!==false;const g=l?c:B;const p=l?transformUrlOptions:legacyTransformUrlOptions;g(t,r,((t,o)=>{if(t)return n(t);const i=p(o);const a=createUnifiedOptions(i,r);if(a.socketTimeoutMS==null)a.socketTimeoutMS=0;if(a.connectTimeoutMS==null)a.connectTimeoutMS=1e4;if(a.retryWrites==null)a.retryWrites=true;if(a.useRecoveryToken==null)a.useRecoveryToken=true;if(a.readPreference==null)a.readPreference="primary";if(a.db_options&&a.db_options.auth){delete a.db_options.auth}resolveTLSOptions(a);e.s.options=a;e.s.readPreference=u.fromOptions(a);e.s.writeConcern=C.fromOptions(a);if(i.servers.length===0){return n(new Error("connection string must contain at least one seed host"))}if(a.auth&&!a.credentials){try{s=true;a.credentials=generateCredentials(e,a.auth.user,a.auth.password,a)}catch(t){return n(t)}}if(a.useUnifiedTopology){return createTopology(e,"unified",a,connectCallback)}E("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.");if(a.replicaSet||a.rs_name){return createTopology(e,"replicaset",a,connectCallback)}else if(i.servers.length>1){return createTopology(e,"mongos",a,connectCallback)}else{return createServer(e,a,connectCallback)}}));function connectCallback(t,r){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&&t.message==="no mongos proxies found in seed list"){if(A.isWarn()){A.warn(o)}return n(new i(o))}if(s){e.emit("authenticated",null,true)}n(t,r)}}function connectWithUrl(e,t,r,n){assignTopology(e,t);addListeners(e,t);relayEvents(e,t);let o=Object.assign({},r);if(typeof r.readPreference==="string"||typeof r.read_preference==="string"){o.readPreference=new u(r.readPreference||r.read_preference)}const s=o.user||o.password||o.authMechanism;if(s&&!o.credentials){try{o.credentials=generateCredentials(e,o.user,o.password,o)}catch(e){return n(e,t)}}return t.connect(o,n)}function createListener(e,t){const r=new Set(["all","fullsetup","open","reconnect"]);return(n,o)=>{if(r.has(t)){return e.emit(t,e)}e.emit(t,n,o)}}function createServer(e,t,r){t.promiseLibrary=e.s.promiseLibrary;const n=translateOptions(t);const o=n[0];const s=collectEvents(e,o);o.connect(t,((n,i)=>{if(n){o.close(true);return r(n)}clearAllEvents(o);relayEvents(e,o);addListeners(e,o);const a=i.lastIsMaster();assignTopology(e,i);if(a&&a.msg==="isdbgrid"){i.close();return createTopology(e,"mongos",t,r)}replayEvents(e,s);r(n,i)}))}const D=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function registerDeprecatedEventNotifiers(e){e.on("newListener",(e=>{if(D.has(e)){p(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}))}function createTopology(e,t,n,o){n.promiseLibrary=e.s.promiseLibrary;const s={};if(t==="unified")s.createServers=false;const i=translateOptions(n,s);if(n.autoEncryption!=null){const t=r(3012).Encrypter;n.encrypter=new t(e,n);n.autoEncrypter=n.encrypter.autoEncrypter}let c;if(t==="mongos"){c=new a(i,n)}else if(t==="replicaset"){c=new h(i,n)}else if(t==="unified"){c=new A(n.servers,n);registerDeprecatedEventNotifiers(e)}addListeners(e,c);relayEvents(e,c);assignTopology(e,c);if(n.autoEncrypter){n.autoEncrypter.init((e=>{if(e){o(e);return}c.connect(n,(e=>{if(e){c.close(true);o(e);return}n.encrypter.connectInternalClient((e=>{if(e)return o(e);o(undefined,c)}))}))}));return}c.connect(n,(e=>{if(e){c.close(true);return o(e)}o(undefined,c);return}))}function createUnifiedOptions(e,t){const r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"];const n=["readconcern","compression","autoencryption"];const o=["w","wtimeout","j","journal","fsync","writeconcern"];for(const s in t){if(o.indexOf(s.toLowerCase())!==-1){continue}else if(n.indexOf(s.toLowerCase())!==-1){e[s]=t[s]}else if(r.indexOf(s.toLowerCase())!==-1){e=mergeOptions(e,t[s],false)}else{if(t[s]&&typeof t[s]==="object"&&!Buffer.isBuffer(t[s])&&!Array.isArray(t[s])){e=mergeOptions(e,t[s],true)}else{e[s]=t[s]}}}const s=C.fromOptions(t);if(s){e.writeConcern=Object.assign({},e.writeConcern,s)}return e}function generateCredentials(e,t,r,n){n=Object.assign({},n);const o=n.authSource||n.authdb||n.dbName;const a=n.authMechanism||"DEFAULT";const A=a.toUpperCase();const c=n.authMechanismProperties;if(!w.has(A)){throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:true})}return new s({mechanism:Q[A],mechanismProperties:c,source:o,username:t,password:r})}function legacyTransformUrlOptions(e){return mergeOptions(createUnifiedOptions({},e),e,false)}function mergeOptions(e,t,r){for(const n in t){if(t[n]&&typeof t[n]==="object"&&r){e=mergeOptions(e,t[n],r)}else{e[n]=t[n]}}return e}function relayEvents(e,t){const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(I);r.forEach((r=>{t.on(r,((t,n)=>{e.emit(r,t,n)}))}))}function replayEvents(e,t){for(let r=0;rt.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e)))}e.exports={validOptions:validOptions,connect:connect}},7885:(e,t,r)=>{"use strict";const n=r(2296).buildCountCommand;const o=r(1018).OperationBase;class CountOperation extends o{constructor(e,t,r){super(r);this.cursor=e;this.applySkipLimit=t}execute(e){const t=this.cursor;const r=this.applySkipLimit;const o=this.options;if(r){if(typeof t.cursorSkip()==="number")o.skip=t.cursorSkip();if(typeof t.cursorLimit()==="number")o.limit=t.cursorLimit()}if(o.readPreference){t.setReadPreference(o.readPreference)}if(typeof o.maxTimeMS!=="number"&&t.cmd&&typeof t.cmd.maxTimeMS==="number"){o.maxTimeMS=t.cmd.maxTimeMS}let s={};s.skip=o.skip;s.limit=o.limit;s.hint=o.hint;s.maxTimeMS=o.maxTimeMS;s.collectionName=t.namespace.collection;let i;try{i=n(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology;t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,((t,r)=>{e(t,r?r.result.n:null)}))}}e.exports=CountOperation},5131:(e,t,r)=>{"use strict";const n=r(1554);class CountDocumentsOperation extends n{constructor(e,t,r){const n=[{$match:t}];if(typeof r.skip==="number"){n.push({$skip:r.skip})}if(typeof r.limit==="number"){n.push({$limit:r.limit})}n.push({$group:{_id:1,n:{$sum:1}}});super(e,n,r)}execute(e,t){super.execute(e,((e,r)=>{if(e){t(e,null);return}const n=r.result;if(n.cursor==null||n.cursor.firstBatch==null){t(null,0);return}const o=n.cursor.firstBatch;t(null,o.length?o[0].n:0)}))}}e.exports=CountDocumentsOperation},5561:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(8275).loadCollection;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class CreateCollectionOperation extends s{constructor(e,t,r){super(e,r);this.name=t}_buildCommand(){const e=this.name;const t=this.options;const r={create:e};for(let e in t){if(t[e]!=null&&typeof t[e]!=="function"&&!l.has(e)){r[e]=t[e]}}return r}execute(e){const t=this.db;const r=this.name;const n=this.options;const o=a();let s=Object.assign({nameOnly:true,strict:false},n);s=i(s,{db:t},s);function done(s){if(s){return e(s)}try{e(null,new o(t,t.s.topology,t.databaseName,r,t.s.pkFactory,n))}catch(s){e(s)}}const l=s.strict;if(l){t.listCollections({name:r},s).setReadPreference(c.PRIMARY).toArray(((t,n)=>{if(t){return e(t)}if(n.length>0){return e(new A(`Collection ${r} already exists. Currently in strict mode.`))}super.execute(done)}));return}super.execute(done)}}o(CreateCollectionOperation,n.WRITE_OPERATION);e.exports=CreateCollectionOperation},6394:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(3994).MongoError;const a=r(1371).parseIndexOptions;const A=r(1178).maxWireVersion;const c=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class CreateIndexesOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=t;if(!Array.isArray(r)||Array.isArray(r[0])){this.onlyReturnNameOfCreatedIndex=true;const e=a(r);const t=typeof n.name==="string"?n.name:e.name;const o={name:t,key:e.fieldHash};for(let e in n){if(c.has(e)){o[e]=n[e]}}this.indexes=[o];return}this.indexes=r}execute(e,t){const r=this.options;const n=this.indexes;const o=A(e);for(let r=0;r{if(e){t(e);return}t(null,this.onlyReturnNameOfCreatedIndex?n[0].name:r)}))}}o(CreateIndexesOperation,[n.WRITE_OPERATION,n.EXECUTE_WITH_SELECTION]);e.exports=CreateIndexesOperation},3554:(e,t,r)=>{"use strict";const n=r(6716).buildCountCommand;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=Array.prototype.push;const a=r(4847).CursorState;function count(e,t,r,o){if(t){if(typeof e.cursorSkip()==="number")r.skip=e.cursorSkip();if(typeof e.cursorLimit()==="number")r.limit=e.cursorLimit()}if(r.readPreference){e.setReadPreference(r.readPreference)}if(typeof r.maxTimeMS!=="number"&&e.cmd&&typeof e.cmd.maxTimeMS==="number"){r.maxTimeMS=e.cmd.maxTimeMS}let s={};s.skip=r.skip;s.limit=r.limit;s.hint=r.hint;s.maxTimeMS=r.maxTimeMS;s.collectionName=e.namespace.collection;let i;try{i=n(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology;e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,((e,t)=>{o(e,t?t.result.n:null)}))}function each(e,t){if(!t)throw s.create({message:"callback is mandatory",driver:true});if(e.isNotified())return;if(e.s.state===a.CLOSED||e.isDead()){return o(t,s.create({message:"Cursor is closed",driver:true}))}if(e.s.state===a.INIT){e.s.state=a.OPEN}let r=null;if(e.bufferedCount()>0){while(r=loop(e,t))r(e,t);each(e,t)}else{e.next(((r,n)=>{if(r)return o(t,r);if(n==null){return e.close({skipKillCursors:true},(()=>o(t,null,null)))}if(o(t,null,n)===false)return;each(e,t)}))}}function loop(e,t){if(e.bufferedCount()===0)return;e._next(t);return loop}function toArray(e,t){const r=[];e.rewind();e.s.state=a.INIT;const fetchDocs=()=>{e._next(((n,s)=>{if(n){return o(t,n)}if(s==null){return e.close({skipKillCursors:true},(()=>o(t,null,r)))}r.push(s);if(e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());if(e.s.transforms&&typeof e.s.transforms.doc==="function"){t=t.map(e.s.transforms.doc)}i.apply(r,t)}fetchDocs()}))};fetchDocs()}e.exports={count:count,each:each,toArray:toArray}},2226:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1371).applyWriteConcern;const s=r(3994).BSON.Code;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(1371).parseIndexOptions;const l=r(3994).ReadPreference;const u=r(1371).toError;const h=r(7703).extractCommand;const d=r(147);const g=r(1371).MongoDBNamespace;const p=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function createIndex(e,t,r,s,i){let c=Object.assign({},{readPreference:l.PRIMARY},s);c=o(c,{db:e},s);if(c.writeConcern&&typeof i!=="function"){throw A.create({message:"Cannot use a writeConcern without a provided callback",driver:true})}if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new A("topology was destroyed"));createIndexUsingCreateIndexes(e,t,r,c,((o,l)=>{if(o==null)return a(i,o,l);if(o.code===n.CannotCreateIndex||o.code===n.DuplicateKey||o.code===n.IndexOptionsConflict||o.code===n.IndexKeySpecsConflict||o.code===n.InterruptedAtShutdown||o.code===n.InvalidIndexSpecificationOption){return a(i,o,l)}const u=createCreateIndexCommand(e,t,r,s);c.checkKeys=false;e.s.topology.insert(e.s.namespace.withCollection(d.SYSTEM_INDEX_COLLECTION),u,c,((e,t)=>{if(i==null)return;if(e)return a(i,e);if(t==null)return a(i,null,null);if(t.result.writeErrors)return a(i,A.create(t.result.writeErrors[0]),null);a(i,null,u.name)}))}))}function createListener(e,t,r){function listener(n){if(r.listeners(t).length>0){r.emit(t,n,e);for(let r=0;r{if(o!=null&&o.code!==n.NamespaceNotFound){return a(i,o,null)}if(A==null||!A[h]){createIndex(e,t,r,s,i)}else{if(typeof i==="function")return a(i,null,h)}}))}function evaluate(e,t,r,n,o){let i=t;let c=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return o(new A("topology was destroyed"));if(!(i&&i._bsontype==="Code"))i=new s(i);if(r!=null&&!Array.isArray(r)&&typeof r!=="function"){c=[r]}else if(r!=null&&Array.isArray(r)&&typeof r!=="function"){c=r}let u={$eval:i,args:c};if(n["nolock"]){u["nolock"]=n["nolock"]}n.readPreference=new l(l.PRIMARY);executeCommand(e,u,n,((e,t)=>{if(e)return a(o,e,null);if(t&&t.ok===1)return a(o,null,t.retval);if(t)return a(o,A.create({message:`eval failed: ${t.errmsg}`,driver:true}),null);a(o,e,t)}))}function executeCommand(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));const o=r.dbName||r.authdb||e.databaseName;r.readPreference=l.resolve(e,r);if(e.s.logger.isDebug()){const n=h(t);e.s.logger.debug(`executing command ${JSON.stringify(n.shouldRedact?`${n.name} details REDACTED`:t)} against ${o}.$cmd with options [${JSON.stringify(i(p,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,((e,t)=>{if(e)return a(n,e);if(r.full)return a(n,null,t);a(n,null,t.result)}))}function executeDbAdminCommand(e,t,r,n){const o=new g("admin","$cmd");e.s.topology.command(o,t,r,((t,r)=>{if(e.serverConfig&&e.serverConfig.isDestroyed()){return n(new A("topology was destroyed"))}if(t)return a(n,t);a(n,null,r.result)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(u(e));if(!Array.isArray(t))return a(n,null,[]);if(o)return a(n,null,t);a(n,null,processResults(t))}))}function profilingInfo(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(e){return r(e,null)}}function validateDatabaseName(e){if(typeof e!=="string")throw A.create({message:"database name must be a string",driver:true});if(e.length===0)throw A.create({message:"database name cannot be the empty string",driver:true});if(e==="$external")return;const t=[" ",".","$","/","\\"];for(let r=0;r{if(e)return a(s,e,null);if(t.ok===0)return a(s,u(t),null);a(s,null,h)}))}e.exports={createListener:createListener,createIndex:createIndex,ensureIndex:ensureIndex,evaluate:evaluate,executeCommand:executeCommand,executeDbAdminCommand:executeDbAdminCommand,indexInformation:indexInformation,profilingInfo:profilingInfo,validateDatabaseName:validateDatabaseName}},323:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=false;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteManyOperation,[s.EXPLAINABLE]);e.exports=DeleteManyOperation},6352:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteOneOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=true;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteOneOperation,[s.EXPLAINABLE]);e.exports=DeleteOneOperation},6469:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(1178).maxWireVersion;const c=r(9386).MongoError;class DistinctOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=e;this.key=t;this.query=r}execute(e,t){const r=this.collection;const n=this.key;const o=this.query;const s=this.options;const l={distinct:r.collectionName,key:n,query:o};if(typeof s.maxTimeMS==="number"){l.maxTimeMS=s.maxTimeMS}a(l,r,s);try{i(l,r,s)}catch(e){return t(e,null)}if(this.explain&&A(e)<4){t(new c(`server does not support explain on distinct`));return}super.executeCommand(e,l,((e,r)=>{if(e){t(e);return}t(null,this.options.full||this.explain?r:r.values)}))}}o(DistinctOperation,[n.READ_OPERATION,n.RETRYABLE,n.EXECUTE_WITH_SELECTION,n.EXPLAINABLE]);e.exports=DistinctOperation},2360:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;class DropOperation extends o{constructor(e,t){const r=Object.assign({},t,e.s.options);if(t.session){r.session=t.session}super(e,r)}execute(e){super.execute(((t,r)=>{if(t)return i(e,t);if(r.ok)return i(e,null,true);i(e,null,false)}))}}s(DropOperation,n.WRITE_OPERATION);class DropCollectionOperation extends DropOperation{constructor(e,t,r){super(e,r);this.name=t;this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}}class DropDatabaseOperation extends DropOperation{_buildCommand(){return{dropDatabase:1}}}e.exports={DropOperation:DropOperation,DropCollectionOperation:DropCollectionOperation,DropDatabaseOperation:DropDatabaseOperation}},3560:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(1371).handleCallback;class DropIndexOperation extends s{constructor(e,t,r){super(e.s.db,r,e);this.collection=e;this.indexName=t}_buildCommand(){const e=this.collection;const t=this.indexName;const r=this.options;let n={dropIndexes:e.collectionName,index:t};n=i(n,{db:e.s.db,collection:e},r);return n}execute(e){super.execute(((t,r)=>{if(typeof e!=="function")return;if(t)return a(e,t,null);a(e,null,r)}))}}o(DropIndexOperation,n.WRITE_OPERATION);e.exports=DropIndexOperation},5328:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(3560);const i=r(1371).handleCallback;class DropIndexesOperation extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute((t=>{if(t)return i(e,t,false);i(e,null,true)}))}}o(DropIndexesOperation,n.WRITE_OPERATION);e.exports=DropIndexesOperation},4451:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1189);const a=r(1178).maxWireVersion;const A=r(5131);class EstimatedDocumentCountOperation extends i{constructor(e,t){super(e,t);this.collection=e;this.collectionName=e.s.namespace.collection}execute(e,t){if(a(e)<12){return this.executeLegacy(e,t)}if(this.options.query){const r=new A(this.collection,this.options.query,this.options);return r.execute(e,t)}const r=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}];const o={aggregate:this.collectionName,pipeline:r,cursor:{}};if(typeof this.options.maxTimeMS==="number"){o.maxTimeMS=this.options.maxTimeMS}super.executeCommand(e,o,((e,r)=>{if(e&&e.code!==n.NamespaceNotFound){t(e);return}t(undefined,r&&r.cursor&&r.cursor.firstBatch&&r.cursor.firstBatch[0].n||0)}))}executeLegacy(e,t){const r={count:this.collectionName};const n=this.options;if(n.query){r.query=n.query}if(n.hint){r.hint=n.hint}if(typeof n.maxTimeMS==="number"){r.maxTimeMS=n.maxTimeMS}if(typeof n.skip==="number"){r.skip=n.skip}if(typeof n.limit==="number"){r.limit=n.limit}super.executeCommand(e,r,((e,r)=>{if(e){t(e);return}t(null,r.n)}))}}s(EstimatedDocumentCountOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=EstimatedDocumentCountOperation},1681:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=r(1371).MongoDBNamespace;class ExecuteDbAdminCommandOperation extends n{constructor(e,t,r){super(r);this.db=e;this.selector=t}execute(e){const t=this.db;const r=this.selector;const n=this.options;const a=new i("admin","$cmd");t.s.topology.command(a,r,n,((r,n)=>{if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new s("topology was destroyed"))}if(r)return o(e,r);o(e,null,n.result)}))}}e.exports=ExecuteDbAdminCommandOperation},2548:(e,t,r)=>{"use strict";const n=r(1371).maybePromise;const o=r(3111).MongoError;const s=r(1018).Aspect;const i=r(1018).OperationBase;const a=r(4485);const A=r(3111).isRetryableError;const c=r(1178).maxWireVersion;const l=r(1178).isUnifiedTopology;function executeOperation(e,t,r){if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!(t instanceof i)){throw new TypeError("This method requires a valid operation instance")}return n(e,r,(r=>{if(l(e)&&e.shouldCheckForSessionSupport()){return selectServerForSessionSupport(e,t,r)}let n,i;if(e.hasSessionSupport()){if(t.session==null){i=Symbol();n=e.startSession({owner:i});t.session=n}else if(t.session.hasEnded){return r(new o("Use of expired sessions is not permitted"))}}else if(t.session){return r(new o("Current topology does not support sessions"))}function executeCallback(e,o){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e,o)}try{if(t.hasAspect(s.EXECUTE_WITH_SELECTION)){executeWithServerSelection(e,t,executeCallback)}else{t.execute(executeCallback)}}catch(e){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e)}}))}function supportsRetryableReads(e){return c(e)>=6}function executeWithServerSelection(e,t,r){const n=t.readPreference||a.primary;const i=t.session&&t.session.inTransaction();if(i&&!n.equals(a.primary)){r(new o(`Read preference in a transaction must be primary, not: ${n.mode}`));return}const c={readPreference:n,session:t.session};function callbackWithRetry(n,o){if(n==null){return r(null,o)}if(!A(n)){return r(n)}e.selectServer(c,((e,n)=>{if(e||!supportsRetryableReads(n)){r(e,null);return}t.execute(n,r)}))}e.selectServer(c,((n,o)=>{if(n){r(n,null);return}const a=e.s.options.retryReads!==false&&t.session&&!i&&supportsRetryableReads(o)&&t.canRetryRead;if(t.hasAspect(s.RETRYABLE)&&a){t.execute(o,callbackWithRetry);return}t.execute(o,r)}))}function selectServerForSessionSupport(e,t,r){e.selectServer(a.primaryPreferred,(n=>{if(n){return r(n)}executeOperation(e,t,r)}))}e.exports=executeOperation},9961:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(3994).ReadPreference;const a=r(1178).maxWireVersion;const A=r(3111).MongoError;class FindOperation extends n{constructor(e,t,r,n){super(n);this.ns=t;this.cmd=r;this.readPreference=i.resolve(e,this.options)}execute(e,t){this.server=e;this.readPreference=i.resolve(this,this.options);if(typeof this.cmd.allowDiskUse!=="undefined"&&a(e)<4){t(new A("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}if(this.explain){this.options.explain=this.explain.verbosity}const r=this.cursorState||{};e.query(this.ns.toString(),this.cmd,r,this.options,t)}}s(FindOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]);e.exports=FindOperation},711:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyRetryableWrites;const s=r(1371).applyWriteConcern;const i=r(1371).decorateWithCollation;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1178).maxWireVersion;const h=r(9386).MongoError;const d=r(1018).Aspect;const g=r(1018).defineAspects;const p=r(1371).decorateWithExplain;class FindAndModifyOperation extends n{constructor(e,t,r,n,o){super(o);this.collection=e;this.query=t;this.sort=r;this.doc=n}execute(e){const t=this.collection;const r=this.query;const n=A(this.sort);const d=this.doc;let g=this.options;let E={findAndModify:t.collectionName,query:r};if(n){E.sort=n}E.new=g.new?true:false;E.remove=g.remove?true:false;E.upsert=g.upsert?true:false;const m=g.projection||g.fields;if(m){E.fields=m}if(g.arrayFilters){E.arrayFilters=g.arrayFilters}if(d&&!g.remove){E.update=d}if(g.maxTimeMS)E.maxTimeMS=g.maxTimeMS;g.serializeFunctions=g.serializeFunctions||t.s.serializeFunctions;g.checkKeys=false;g=o(g,t.s.db);g=s(g,{db:t.s.db,collection:t},g);if(g.writeConcern){E.writeConcern=g.writeConcern}if(g.bypassDocumentValidation===true){E.bypassDocumentValidation=g.bypassDocumentValidation}g.readPreference=l.primary;try{i(E,t,g)}catch(t){return e(t,null)}if(g.hint){const r=g.writeConcern&&g.writeConcern.w===0;if(r||u(t.s.topology)<8){e(new h("The current topology does not support a hint on findAndModify commands"));return}E.hint=g.hint}if(this.explain){if(u(t.s.topology)<4){e(new h(`server does not support explain on findAndModify`));return}E=p(E,this.explain)}a(t.s.db,E,g,((t,r)=>{if(t)return c(e,t,null);return c(e,null,r)}))}}g(FindAndModifyOperation,[d.EXPLAINABLE]);e.exports=FindAndModifyOperation},4497:(e,t,r)=>{"use strict";const n=r(1371).handleCallback;const o=r(1018).OperationBase;const s=r(1371).toError;const i=r(1018).Aspect;const a=r(1018).defineAspects;class FindOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.query=t}execute(e){const t=this.collection;const r=this.query;const o=this.options;try{const i=t.find(r,o).limit(-1).batchSize(1);i.next(((t,r)=>{if(t!=null)return n(e,s(t),null);n(e,null,r)}))}catch(t){e(t)}}}a(FindOneOperation,[i.EXPLAINABLE]);e.exports=FindOneOperation},5841:(e,t,r)=>{"use strict";const n=r(711);class FindOneAndDeleteOperation extends n{constructor(e,t,r){const n=Object.assign({},r);n.fields=r.projection;n.remove=true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}super(e,t,n.sort,null,n)}}e.exports=FindOneAndDeleteOperation},4316:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndReplaceOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Replacement parameter must be an object")}if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndReplaceOperation},1925:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndUpdateOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Update parameter must be an object")}if(!s(r)){throw new TypeError("Update document requires atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndUpdateOperation},8169:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1018).OperationBase;const i=r(1371).decorateCommand;const a=r(1371).decorateWithReadConcern;const A=r(2226).executeCommand;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1371).toError;class GeoHaystackSearchOperation extends s{constructor(e,t,r,n){super(n);this.collection=e;this.x=t;this.y=r}execute(e){const t=this.collection;const r=this.x;const n=this.y;let o=this.options;let s={geoSearch:t.collectionName,near:[r,n]};s=i(s,o,["readPreference","session"]);o=Object.assign({},o);o.readPreference=l.resolve(t,o);a(s,t,o);A(t.s.db,s,o,((t,r)=>{if(t)return c(e,t);if(r.err||r.errmsg)c(e,u(r));c(e,null,r)}))}}o(GeoHaystackSearchOperation,n.READ_OPERATION);e.exports=GeoHaystackSearchOperation},7809:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(2226).indexInformation;class IndexExistsOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.indexes=t}execute(e){const t=this.collection;const r=this.indexes;const n=this.options;s(t.s.db,t.collectionName,n,((t,n)=>{if(t!=null)return o(e,t,null);if(!Array.isArray(r))return o(e,null,n[r]!=null);for(let t=0;t{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexInformationOperation extends n{constructor(e,t,r){super(r);this.db=e;this.name=t}execute(e){const t=this.db;const r=this.name;const n=this.options;o(t,r,n,e)}}e.exports=IndexInformationOperation},4218:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexesOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;let r=this.options;r=Object.assign({},{full:true},r);o(t.s.db,t.collectionName,r,e)}}e.exports=IndexesOperation},3592:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(6976);const s=r(3994).MongoError;const i=r(2296).prepareDocs;class InsertManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.docs=t}execute(e){const t=this.collection;let r=this.docs;const n=this.options;if(!Array.isArray(r)){return e(s.create({message:"docs parameter must be an array of documents",driver:true}))}n["serializeFunctions"]=n["serializeFunctions"]||t.s.serializeFunctions;r=i(t,r,n);const a=r.map((e=>({insertOne:{document:e}})));const A=new o(t,a,n);A.execute(((t,n)=>{if(t)return e(t,null);e(null,mapInsertManyResults(r,n))}))}}function mapInsertManyResults(e,t){const r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};if(t.getLastOp()){r.result.opTime=t.getLastOp()}return r}e.exports=InsertManyOperation},9915:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(1018).OperationBase;const s=r(2296).insertDocuments;class InsertOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.doc=t}execute(e){const t=this.collection;const r=this.doc;const o=this.options;if(Array.isArray(r)){return e(n.create({message:"doc parameter must be an object",driver:true}))}s(t,[r],o,((t,n)=>{if(e==null)return;if(t&&e)return e(t);if(n==null)return e(null,{result:{ok:1}});n.insertedCount=n.result.n;n.insertedId=r._id;if(e)e(null,n)}))}}e.exports=InsertOneOperation},4956:(e,t,r)=>{"use strict";const n=r(43);const o=r(1371).handleCallback;class IsCappedOperation extends n{constructor(e,t){super(e,t)}execute(e){super.execute(((t,r)=>{if(t)return o(e,t);o(e,null,!!(r&&r.capped))}))}}e.exports=IsCappedOperation},840:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=r(147);const A=3;function listCollectionsTransforms(e){const t=`${e}.`;return{doc:e=>{const r=e.name.indexOf(t);if(e.name&&r===0){e.name=e.name.substr(r+t.length)}return e}}}class ListCollectionsOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.db=e;this.filter=t;this.nameOnly=!!this.options.nameOnly;if(typeof this.options.batchSize==="number"){this.batchSize=this.options.batchSize}}execute(e,t){if(i(e){if(r&&r.message&&r.message.documents&&Array.isArray(r.message.documents)){r.message.documents=r.message.documents.map(o.doc)}t(e,r)}));return}const r={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,r,t)}}s(ListCollectionsOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListCollectionsOperation},9929:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1371).MongoDBNamespace;class ListDatabasesOperation extends n{constructor(e,t){super(e,t);this.ns=new i("admin","$cmd")}execute(e,t){const r={listDatabases:1};if(this.options.nameOnly){r.nameOnly=Number(r.nameOnly)}if(this.options.filter){r.filter=this.options.filter}if(typeof this.options.authorizedDatabases==="boolean"){r.authorizedDatabases=this.options.authorizedDatabases}super.executeCommand(e,r,t)}}s(ListDatabasesOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListDatabasesOperation},28:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=3;class ListIndexesOperation extends n{constructor(e,t){super(e,t,{fullResponse:true});this.collectionNamespace=e.s.namespace}execute(e,t){const r=i(e);if(r{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).handleCallback;const c=r(1371).isObject;const l=r(8275).loadDb;const u=r(1018).OperationBase;const h=r(3994).ReadPreference;const d=r(1371).toError;const g=r(1018).Aspect;const p=r(1018).defineAspects;const E=r(1371).decorateWithExplain;const m=r(1178).maxWireVersion;const C=r(9386).MongoError;const I=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class MapReduceOperation extends u{constructor(e,t,r,n){super(n);this.collection=e;this.map=t;this.reduce=r}execute(e){const t=this.collection;const r=this.map;const o=this.reduce;let c=this.options;let u={mapReduce:t.collectionName,map:r,reduce:o};for(let e in c){if("scope"===e){u[e]=processScope(c[e])}else{if(I.indexOf(e)===-1){u[e]=c[e]}}}c=Object.assign({},c);c.readPreference=h.resolve(t,c);if(c.readPreference!==false&&c.readPreference!=="primary"&&c["out"]&&c["out"].inline!==1&&c["out"]!=="inline"){c.readPreference="primary";n(u,{db:t.s.db,collection:t},c)}else{i(u,t,c)}if(c.bypassDocumentValidation===true){u.bypassDocumentValidation=c.bypassDocumentValidation}try{s(u,t,c)}catch(t){return e(t,null)}if(this.explain){if(m(t.s.topology)<9){e(new C(`server does not support explain on mapReduce`));return}u=E(u,this.explain)}a(t.s.db,u,c,((r,n)=>{if(r)return A(e,r);if(1!==n.ok||n.err||n.errmsg){return A(e,d(n))}if(this.explain)return e(undefined,n);const o={};if(n.timeMillis)o["processtime"]=n.timeMillis;if(n.counts)o["counts"]=n.counts;if(n.timing)o["timing"]=n.timing;if(n.results){if(c["verbose"]==null||!c["verbose"]){return A(e,null,n.results)}return A(e,null,{results:n.results,stats:o})}let s=null;if(n.result!=null&&typeof n.result==="object"){const e=n.result;let r=l();s=new r(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else{s=t.s.db.collection(n.result)}if(c["verbose"]==null||!c["verbose"]){return A(e,r,s)}A(e,r,{collection:s,stats:o})}))}}function processScope(e){if(!c(e)||e._bsontype==="ObjectID"){return e}const t=Object.keys(e);let r;const n={};for(let s=t.length-1;s>=0;s--){r=t[s];if("function"===typeof e[r]){n[r]=new o(String(e[r]))}else{n[r]=processScope(e[r])}}return n}p(MapReduceOperation,[g.EXPLAINABLE]);e.exports=MapReduceOperation},1018:(e,t,r)=>{"use strict";const n=r(5293).Explain;const o=r(3111).MongoError;const s={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"),EXPLAINABLE:Symbol("EXPLAINABLE")};class OperationBase{constructor(e){this.options=Object.assign({},e);if(this.hasAspect(s.EXPLAINABLE)){this.explain=n.fromOptions(e)}else if(this.options.explain!==undefined){throw new o(`explain is not supported on this command`)}}hasAspect(e){if(this.constructor.aspects==null){return false}return 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 true}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}function defineAspects(e,t){if(!Array.isArray(t)&&!(t instanceof Set)){t=[t]}t=new Set(t);Object.defineProperty(e,"aspects",{value:t,writable:false});return t}e.exports={Aspect:s,defineAspects:defineAspects,OperationBase:OperationBase}},43:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;class OptionsOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;const r=this.options;t.s.db.listCollections({name:t.collectionName},r).toArray(((r,n)=>{if(r)return o(e,r);if(n.length===0){return o(e,s.create({message:`collection ${t.namespace} not found`,driver:true}))}o(e,r,n[0].options||null)}))}}e.exports=OptionsOperation},3969:(e,t,r)=>{"use strict";const n=r(499);class ProfilingLevelOperation extends n{constructor(e,t,r){super(e,r)}_buildCommand(){const e={profile:-1};return e}execute(e){super.execute(((t,r)=>{if(t==null&&r.ok===1){const t=r.was;if(t===0)return e(null,"off");if(t===1)return e(null,"slow_only");if(t===2)return e(null,"all");return e(new Error("Error: illegal profiling level value "+t),null)}else{t!=null?e(t,null):e(new Error("Error with profile command"),null)}}))}}e.exports=ProfilingLevelOperation},6331:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(2291).serverType;const a=r(2291).ServerType;const A=r(3994).MongoError;class ReIndexOperation extends s{constructor(e,t){super(e,t);this.collectionName=e.collectionName}execute(e,t){if(i(e)!==a.Standalone){t(new A(`reIndex can only be executed on standalone servers.`));return}super.executeCommand(e,{reIndex:this.collectionName},((e,r)=>{if(e){t(e);return}t(null,!!r.ok)}))}}o(ReIndexOperation,[n.EXECUTE_WITH_SELECTION]);e.exports=ReIndexOperation},1969:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;const a=r(2481);class RemoveUserOperation extends o{constructor(e,t,r){const n={};const o=a.fromOptions(r);if(o!=null){n.writeConcern=o}if(r.dbName){n.dbName=r.dbName}if(typeof r.maxTimeMS==="number"){n.maxTimeMS=r.maxTimeMS}super(e,n);this.username=t}_buildCommand(){const e=this.username;const t={dropUser:e};return t}execute(e){super.execute(((t,r)=>{if(t)return i(e,t,null);i(e,t,r.ok?true:false)}))}}s(RemoveUserOperation,n.WRITE_OPERATION);e.exports=RemoveUserOperation},2808:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyWriteConcern;const s=r(1371).checkCollectionName;const i=r(2226).executeDbAdminCommand;const a=r(1371).handleCallback;const A=r(8275).loadCollection;const c=r(1371).toError;class RenameOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.newName=t}execute(e){const t=this.collection;const r=this.newName;const n=this.options;let l=A();s(r);const u=t.namespace;const h=t.s.namespace.withCollection(r).toString();const d=typeof n.dropTarget==="boolean"?n.dropTarget:false;const g={renameCollection:u,to:h,dropTarget:d};o(g,{db:t.s.db,collection:t},n);i(t.s.db.admin().s.db,g,n,((n,o)=>{if(n)return a(e,n,null);if(o.errmsg)return a(e,c(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,r,t.s.pkFactory,t.s.options))}catch(n){return a(e,c(n),null)}}))}}e.exports=RenameOperation},2508:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;class ReplaceOneOperation extends n{constructor(e,t,r,n){super(n);if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}this.collection=e;this.filter=t;this.replacement=r}execute(e){const t=this.collection;const r=this.filter;const n=this.replacement;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>replaceCallback(t,r,n,e)))}}function replaceCallback(e,t,r,n){if(n==null)return;if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?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=[r];if(n)n(null,t)}e.exports=ReplaceOneOperation},1363:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).defineAspects;const s=r(1018).Aspect;class RunCommandOperation extends n{constructor(e,t,r){super(e,r);this.command=t}execute(e,t){const r=this.command;this.executeCommand(e,r,t)}}o(RunCommandOperation,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]);e.exports=RunCommandOperation},6301:(e,t,r)=>{"use strict";const n=r(499);const o=new Set(["off","slow_only","all"]);class SetProfilingLevelOperation extends n{constructor(e,t,r){let n=0;if(t==="off"){n=0}else if(t==="slow_only"){n=1}else if(t==="all"){n=2}super(e,r);this.level=t;this.profile=n}_buildCommand(){const e=this.profile;const t={profile:e};return t}execute(e){const t=this.level;if(!o.has(t)){return e(new Error("Error: illegal profiling level value "+t))}super.execute(((r,n)=>{if(r==null&&n.ok===1)return e(null,t);return r!=null?e(r,null):e(new Error("Error with profile command"),null)}))}}e.exports=SetProfilingLevelOperation},968:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;class StatsOperation extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection;const t=this.options;const r={collStats:e.collectionName};if(t["scale"]!=null){r["scale"]=t["scale"]}return r}}s(StatsOperation,n.READ_OPERATION);e.exports=StatsOperation},9350:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateManyOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=true;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateManyOperation,[i.EXPLAINABLE]);e.exports=UpdateManyOperation},9068:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateOneOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateOneOperation,[i.EXPLAINABLE]);e.exports=UpdateOneOperation},9263:(e,t,r)=>{"use strict";const n=r(499);class ValidateCollectionOperation extends n{constructor(e,t,r){let n={validate:t};const o=Object.keys(r);for(let e=0;e{if(r!=null)return e(r,null);if(n.ok===0)return e(new Error("Error with validate command"),null);if(n.result!=null&&n.result.constructor!==String)return e(new Error("Error with validation data"),null);if(n.result!=null&&n.result.match(/exception|corrupt/)!=null)return e(new Error("Error: invalid collection "+t),null);if(n.valid!=null&&!n.valid)return e(new Error("Error: invalid collection "+t),null);return e(null,n)}))}}e.exports=ValidateCollectionOperation},7289:e=>{"use strict";class ReadConcern{constructor(e){if(e!=null){this.level=e}}static fromOptions(e){if(e==null){return}if(e.readConcern){if(e.readConcern instanceof ReadConcern){return e.readConcern}return new ReadConcern(e.readConcern.level)}if(e.level){return new ReadConcern(e.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=ReadConcern},2048:(e,t,r)=>{"use strict";const n=r(8589).oF;const o=r(3994).MongoError;const s=r(3994).Mongos;const i=r(7159);const a=r(8421);const A=r(8589).yh;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"];class Mongos extends n{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var n=0;n0?t.socketOptions:t;C=l(C,I);this.s={coreTopology:new s(E,C),sCapabilities:null,debug:C.debug,storeOptions:g,clonedOptions:C,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var n=["timeout","error","close"];n.forEach((function(e){r.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.close(true);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect");r.s.store.execute()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){var e=["timeout","error","close","fullsetup"];e.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.on("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r)}));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("joined",relay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.connect(e)}}Object.defineProperty(Mongos.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=Mongos},2632:(e,t,r)=>{"use strict";const n=r(3994).Topology;const o=r(8589).ug;const s=r(7159);const i=r(1371).translateOptions;class NativeTopology extends n{constructor(e,t){t=t||{};let r=Object.assign({},{cursorFactory:s,reconnect:false,emitError:typeof t.emitError==="boolean"?t.emitError:true,maxPoolSize:typeof t.maxPoolSize==="number"?t.maxPoolSize:typeof t.poolSize==="number"?t.poolSize:10,minPoolSize:typeof t.minPoolSize==="number"?t.minPoolSize:typeof t.minSize==="number"?t.minSize:0,monitorCommands:typeof t.monitorCommands==="boolean"?t.monitorCommands:false});r=i(r,t);var n=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;r=i(r,n);r.serverApi=t.serverApi;r.useUnifiedTopology=t.useUnifiedTopology;super(e,r)}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.lastIsMaster()==null)return null;this.s.sCapabilities=new o(this.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){super.command(e.toString(),t,r,n)}insert(e,t,r,n){super.insert(e.toString(),t,r,n)}update(e,t,r,n){super.update(e.toString(),t,r,n)}remove(e,t,r,n){super.remove(e.toString(),t,r,n)}}e.exports=NativeTopology},382:(e,t,r)=>{"use strict";const n=r(8421);const o=r(7159);const s=r(3994).MongoError;const i=r(8589).oF;const a=r(8589).yh;const A=r(3994).ReplSet;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class ReplSet extends i{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var i=0;i0?t.socketOptions:t;m=l(m,C);var I=new A(E,m);I.on("reconnect",(function(){r.emit("reconnect");p.execute()}));this.s={coreTopology:I,sCapabilities:null,tag:t.tag,storeOptions:g,clonedOptions:m,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise};if(m.debug){Object.defineProperty(this,"replset",{enumerable:true,get:function(){return I}})}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));var relay=function(e){return function(t,n){r.emit(e,t,n)}};var replsetRelay=function(e){return function(t,n){r.emit(e,t,n.lastIsMaster(),n)}};var relayHa=function(e,t){r.emit("ha",e,t);if(e==="start"){r.emit("ha_connect",e,t)}else if(e==="end"){r.emit("ha_ismaster",e,t)}};r.s.coreTopology.on("joined",replsetRelay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("ping",relay("ping"));r.s.coreTopology.on("ha",relayHa);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r,r)}));r.s.coreTopology.on("all",(function(){r.emit("all",null,r)}));var connectHandler=function(){r.s.coreTopology.once("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.once("close",errorHandler("close"));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var connectErrorHandler=function(){return function(e){["timeout","error","close"].forEach((function(e){r.s.coreTopology.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.s.coreTopology.destroy();try{t(e)}catch(e){if(!r.s.coreTopology.isConnected())process.nextTick((function(){throw e}))}}};r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach((e=>this.removeAllListeners(e)));super.close(e,t)}}Object.defineProperty(ReplSet.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=ReplSet},8421:(e,t,r)=>{"use strict";const n=r(3994).Server;const o=r(7159);const s=r(8589).oF;const i=r(8589).yh;const a=r(3994).MongoError;const A=r(1371).MAX_JS_INT;const c=r(1371).translateOptions;const l=r(1371).filterOptions;const u=r(1371).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","bsonRegExp","compression","promiseLibrary","monitorCommands"];class Server extends s{constructor(e,t,r){super();var s=this;r=l(r,h);const d=r.promiseLibrary;var g={force:false,bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:A};var p=r.store||new i(s,g);if(e.indexOf("/")!==-1){if(t!=null&&typeof t==="object"){r=t;t=null}}else if(t==null){throw a.create({message:"port must be specified",driver:true})}var E=typeof r.auto_reconnect==="boolean"?r.auto_reconnect:true;E=typeof r.autoReconnect==="boolean"?r.autoReconnect:E;var m=u({},{host:e,port:t,disconnectHandler:p,cursorFactory:o,reconnect:E,emitError:typeof r.emitError==="boolean"?r.emitError:true,size:typeof r.poolSize==="number"?r.poolSize:5,monitorCommands:typeof r.monitorCommands==="boolean"?r.monitorCommands:false});m=c(m,r);var C=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;m=c(m,C);this.s={coreTopology:new n(m),sCapabilities:null,clonedOptions:m,reconnect:m.reconnect,emitError:m.emitError,poolSize:m.size,storeOptions:g,store:p,host:e,port:t,options:r,sessionPool:null,sessions:new Set,promiseLibrary:d||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e=this.s.clonedOptions;if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var o=["timeout","error","close"];o.forEach((function(e){r.s.coreTopology.removeListener(e,n[e])}));r.s.coreTopology.removeListener("connect",connectErrorHandler);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect",r);r.s.store.execute()};var reconnectFailedHandler=function(e){r.emit("reconnectFailed",e);r.s.store.flush(e)};var destroyHandler=function(){r.s.store.flush()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){["timeout","error","close","destroy"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("destroy",destroyHandler);r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n={timeout:connectErrorHandler("timeout"),error:connectErrorHandler("error"),close:connectErrorHandler("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.once("timeout",n.timeout);r.s.coreTopology.once("error",n.error);r.s.coreTopology.once("close",n.close);r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.on("reconnectFailed",reconnectFailedHandler);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("attemptReconnect",relay("attemptReconnect"));r.s.coreTopology.on("monitoring",relay("monitoring"));r.s.coreTopology.connect(e)}}Object.defineProperty(Server.prototype,"poolSize",{enumerable:true,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(Server.prototype,"autoReconnect",{enumerable:true,get:function(){return this.s.reconnect}});Object.defineProperty(Server.prototype,"host",{enumerable:true,get:function(){return this.s.host}});Object.defineProperty(Server.prototype,"port",{enumerable:true,get:function(){return this.s.port}});e.exports=Server},8589:(e,t,r)=>{"use strict";const n=r(2361),o=r(3994).MongoError,s=r(3837).format,i=r(3994).ReadPreference,a=r(3994).Sessions.ClientSession;var Store=function(e,t){var r=this;var n=[];t=t||{force:false,bufferMaxEntries:-1};this.s={storedOps:n,storeOptions:t,topology:e};Object.defineProperty(this,"length",{enumerable:true,get:function(){return r.s.storedOps.length}})};Store.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};Store.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};Store.prototype.flush=function(e){while(this.s.storedOps.length>0){this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:true}))}};var A=["primary","primaryPreferred","nearest","secondaryPreferred"];var c=["secondary","secondaryPreferred"];Store.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];var r=typeof e.executePrimary==="boolean"?e.executePrimary:true;var n=typeof e.executeSecondary==="boolean"?e.executeSecondary:true;while(t.length>0){var o=t.shift();if(o.t==="cursor"){if(r&&n){o.o[o.m].apply(o.o,o.p)}else if(r&&o.o.options&&o.o.options.readPreference&&A.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}else if(!r&&n&&o.o.options&&o.o.options.readPreference&&c.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}}else if(o.t==="auth"){this.s.topology[o.t].apply(this.s.topology,o.o)}else{if(r&&n){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(r&&o.op&&o.op.readPreference&&A.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(!r&&n&&o.op&&o.op.readPreference&&c.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}}}};Store.prototype.all=function(){return this.s.storedOps};var ServerCapabilities=function(e){var setup_get_property=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var t=false;var r=false;var n=false;var o=false;var s=false;var i=false;var a=e.maxWriteBatchSize||1e3;var A=false;var c=false;if(e.minWireVersion>=0){n=true}if(e.maxWireVersion>=1){t=true;o=true}if(e.maxWireVersion>=2){r=true}if(e.maxWireVersion>=3){s=true;i=true}if(e.maxWireVersion>=5){A=true;c=true}if(e.minWireVersion==null){e.minWireVersion=0}if(e.maxWireVersion==null){e.maxWireVersion=0}setup_get_property(this,"hasAggregationCursor",t);setup_get_property(this,"hasWriteCommands",r);setup_get_property(this,"hasTextSearch",n);setup_get_property(this,"hasAuthCommands",o);setup_get_property(this,"hasListCollectionsCommand",s);setup_get_property(this,"hasListIndexesCommand",i);setup_get_property(this,"minWireVersion",e.minWireVersion);setup_get_property(this,"maxWireVersion",e.maxWireVersion);setup_get_property(this,"maxNumberOfDocsInBatch",a);setup_get_property(this,"commandsTakeWriteConcern",A);setup_get_property(this,"commandsTakeCollation",c)};class TopologyBase extends n{constructor(){super();this.setMaxListeners(Infinity)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new a(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.s.coreTopology.lastIsMaster()==null)return null;this.s.sCapabilities=new ServerCapabilities(this.s.coreTopology.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){this.s.coreTopology.command(e.toString(),t,i.translate(r),n)}insert(e,t,r,n){this.s.coreTopology.insert(e.toString(),t,r,n)}update(e,t,r,n){this.s.coreTopology.update(e.toString(),t,r,n)}remove(e,t,r,n){this.s.coreTopology.remove(e.toString(),t,r,n)}isConnected(e){e=e||{};e=i.translate(e);return this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,r){r=r||{};r=i.translate(r);r.disconnectHandler=this.s.store;r.topology=this;return this.s.coreTopology.cursor(e,t,r)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,r){return this.s.coreTopology.selectServer(e,t,r)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach((e=>e.endSession()));if(this.s.sessionPool){this.s.sessionPool.endAllPooledSessions()}if(e===true){this.s.storeOptions.force=e;this.s.store.flush()}this.s.coreTopology.destroy({force:typeof e==="boolean"?e:false},t)}}Object.defineProperty(TopologyBase.prototype,"bson",{enumerable:true,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(TopologyBase.prototype,"parserType",{enumerable:true,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(TopologyBase.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(TopologyBase.prototype,"type",{enumerable:true,get:function(){return this.s.coreTopology.type}});t.yh=Store;t.ug=ServerCapabilities;t.oF=TopologyBase},8729:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(7310);const s=r(3837).format;const i=r(3994).Logger;const a=r(7578);const A=r(7289);const c=r(3477);const l=r(3111).MongoParseError;e.exports=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};let n;try{n=o.parse(e,true)}catch(e){return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:"){return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"))}if(n.protocol==="mongodb:"){return parseHandler(e,t,r)}if(n.hostname.split(".").length<3){return r(new Error("URI does not have hostname, domain name and tld"))}n.domainLength=n.hostname.split(".").length;const s=e.substring("mongodb+srv://".length).split("/")[0];if(s.match(",")){return r(new Error("Invalid URI, cannot contain multiple hostnames"))}if(n.port){return r(new Error("Ports not accepted with `mongodb+srv` URIs"))}let i=`_mongodb._tcp.${n.host}`;a.resolveSrv(i,(function(e,o){if(e)return r(e);if(o.length===0){return r(new Error("No addresses found at host"))}for(let e=0;e1){return r(new l("Multiple text records not allowed"))}n=n[0].join("");const e=c.parse(n);const t=Object.keys(e);if(Object.keys(t).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new l("Load balancer mode requires driver version 4+"))}if(t.some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new l("Text record must only set `authSource` or `replicaSet`"))}if(t.length>0){u.push(n)}}if(u.length){A+=`?${u.join("&")}`}parseHandler(A,t,r)}))}))};function matchesParentDomain(e,t){let r=/^.*?\./;let n=`.${e.replace(r,"")}`;let o=`.${t.replace(r,"")}`;if(n.endsWith(o))return true;else return false}function parseHandler(e,t,r){let n,o;try{n=parseConnectionString(e,t)}catch(e){o=e}return o?r(o,null):r(null,n)}function parseConnectionString(e,t){let r="";let a="";let c="";let u="admin";let h=o.parse(e,true);if((h.hostname==null||h.hostname==="")&&e.indexOf(".sock")===-1){throw new Error("No hostname or hostnames provided in connection string")}if(h.port==="0"){throw new Error("Invalid port (zero) with hostname")}if(!isNaN(parseInt(h.port,10))&&parseInt(h.port,10)>65535){throw new Error("Invalid port (larger than 65535) with hostname")}if(h.path&&h.path.length>0&&h.path[0]!=="/"&&e.indexOf(".sock")===-1){throw new Error("Missing delimiting slash between hosts and options")}if(h.query){for(let e in h.query){if(e.indexOf("::")!==-1){throw new Error("Double colon in host identifier")}if(h.query[e]===""){throw new Error("Query parameter "+e+" is an incomplete value pair")}}}if(h.auth){let t=h.auth.split(":");if(e.indexOf(h.auth)!==-1&&t.length>2){throw new Error("Username with password containing an unescaped colon")}if(e.indexOf(h.auth)!==-1&&h.auth.indexOf("@")!==-1){throw new Error("Username containing an unescaped at-sign")}}let d=e.split("?").shift();let g=d.split(",");let p=[];for(let e=0;e1&&t.path.indexOf("::")===-1){throw new Error("Slash in host identifier")}else{throw new Error("Double colon in host identifier")}}}if(e.indexOf("?")!==-1){c=e.substr(e.indexOf("?")+1);r=e.substring("mongodb://".length,e.indexOf("?"))}else{r=e.substring("mongodb://".length)}if(r.indexOf("@")!==-1){a=r.split("@")[0];r=r.split("@")[1]}if(r.split("/").length>2){throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash")}if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){u=r.split(".sock/")[1];if(u.indexOf("/")!==-1){if(u.split("/").length===2&&u.split("/")[1].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}r=r.split("/",r.indexOf(".sock")+".sock".length)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2){if(r.split("/")[2].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}u=r.split("/")[1];r=r.split("/")[0]}r=decodeURIComponent(r);let E={};let m=a||"";let C=m.split(":",2);let I=decodeURIComponent(C[0]);if(C[0]!==encodeURIComponent(I)){throw new Error("Username contains an illegal unescaped character")}C[0]=I;if(C[1]){let e=decodeURIComponent(C[1]);if(C[1]!==encodeURIComponent(e)){throw new Error("Password contains an illegal unescaped character")}C[1]=e}if(C.length===2)E.auth={user:C[0],password:C[1]};if(t&&t.auth!=null)E.auth=t.auth;let y;let B;let Q;let b;let w={socketOptions:{}};let S={read_preference_tags:[]};let v={socketOptions:{}};let R={socketOptions:{}};E.server_options=w;E.db_options=S;E.rs_options=v;E.mongos_options=R;if(e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);if(t.indexOf("@")!==-1)t=t.split("@")[1];t=decodeURIComponent(t);Q=[{domain_socket:t}]}else{y=r;let e={};Q=y.split(",").map((function(t){let r,n,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t)){r=o[1];n=parseInt(o[2],10)||27017}else{let e=t.split(":",2);r=e[0]||"localhost";n=e[1]!=null?parseInt(e[1],10):27017;if(r.indexOf("?")!==-1)r=r.split(/\?/)[0]}if(e[r+"_"+n])return null;e[r+"_"+n]=1;return{host:r,port:n}})).filter((function(e){return e!=null}))}E.dbName=u||"admin";B=(c||"").split(/[&;]/);if(B.some((e=>e.toLowerCase()==="loadbalanced"))){throw new l("Load balancer mode requires driver version 4+")}B.forEach((function(e){if(!e)return;var t=e.split("="),r=t[0],o=t[1];switch(r){case"slaveOk":case"slave_ok":w.slave_ok=o==="true";S.slaveOk=o==="true";break;case"maxPoolSize":case"poolSize":w.poolSize=parseInt(o,10);v.poolSize=parseInt(o,10);break;case"appname":E.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":w.auto_reconnect=o==="true";break;case"ssl":if(o==="prefer"){w.ssl=o;v.ssl=o;R.ssl=o;break}w.ssl=o==="true";v.ssl=o==="true";R.ssl=o==="true";break;case"sslValidate":w.sslValidate=o==="true";v.sslValidate=o==="true";R.sslValidate=o==="true";break;case"replicaSet":case"rs_name":v.rs_name=o;break;case"reconnectWait":v.reconnectWait=parseInt(o,10);break;case"retries":v.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":v.read_secondary=o==="true";break;case"fsync":S.fsync=o==="true";break;case"journal":S.j=o==="true";break;case"safe":S.safe=o==="true";break;case"nativeParser":case"native_parser":S.native_parser=o==="true";break;case"readConcernLevel":S.readConcern=new A(o);break;case"connectTimeoutMS":w.socketOptions.connectTimeoutMS=parseInt(o,10);v.socketOptions.connectTimeoutMS=parseInt(o,10);R.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":w.socketOptions.socketTimeoutMS=parseInt(o,10);v.socketOptions.socketTimeoutMS=parseInt(o,10);R.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":S.w=parseInt(o,10);if(isNaN(S.w))S.w=o;break;case"authSource":S.authSource=o;break;case"gssapiServiceName":S.gssapiServiceName=o;break;case"authMechanism":if(o==="GSSAPI"){if(E.auth==null){let e=decodeURIComponent(m);if(e.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");E.auth={user:e,password:null}}else{E.auth.user=decodeURIComponent(E.auth.user)}}else if(o==="MONGODB-X509"){E.auth={user:decodeURIComponent(m)}}if(o!=="GSSAPI"&&o!=="MONGODB-X509"&&o!=="MONGODB-CR"&&o!=="DEFAULT"&&o!=="SCRAM-SHA-1"&&o!=="SCRAM-SHA-256"&&o!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");S.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(",");let t={};e.forEach((function(e){let r=e.split(":");t[r[0]]=r[1]}));S.authMechanismProperties=t;if(typeof t.SERVICE_NAME==="string")S.gssapiServiceName=t.SERVICE_NAME;if(typeof t.SERVICE_REALM==="string")S.gssapiServiceRealm=t.SERVICE_REALM;if(typeof t.CANONICALIZE_HOST_NAME==="string")S.gssapiCanonicalizeHostName=t.CANONICALIZE_HOST_NAME==="true"?true:false}break;case"wtimeoutMS":S.wtimeout=parseInt(o,10);break;case"readPreference":if(!n.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");S.readPreference=o;break;case"maxStalenessSeconds":S.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{o=decodeURIComponent(o);let e={};if(o==null||o===""){S.read_preference_tags.push(e);break}let t=o.split(/,/);for(let r=0;r9){throw new Error("zlibCompressionLevel must be an integer between -1 and 9")}b.zlibCompressionLevel=e;w.compression=b}break;case"retryWrites":S.retryWrites=o==="true";break;case"minSize":S.minSize=parseInt(o,10);break;default:{let e=i("URL Parser");e.warn(`${r} is not supported as a connection string option`)}break}}));if(S.read_preference_tags.length===0){S.read_preference_tags=null}if((S.w===-1||S.w===0)&&(S.journal===true||S.fsync===true||S.safe===true))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");if(!S.readPreference){S.readPreference="primary"}S=Object.assign(S,t);E.servers=Q;return E}},1371:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(2481);var shallowClone=function(e){var t={};for(var r in e)t[r]=e[r];return t};var getSingleProperty=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var s=t.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){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)']]")}};var i=t.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0){return null}for(var r=0;r{if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!Array.isArray(r)){throw new TypeError("This method requires an array of arguments to apply")}o=o||{};const s=e.s.promiseLibrary;let i=r[r.length-1];let a,A,c;if(!o.skipSessions&&e.hasSessionSupport()){A=r[r.length-2];if(A==null||A.session==null){c=Symbol();a=e.startSession({owner:c});const t=r.length-2;r[t]=Object.assign({},r[t],{session:a})}else if(A.session&&A.session.hasEnded){throw new n("Use of expired sessions is not permitted")}}const makeExecuteCallback=(e,t)=>function executeCallback(r,n){if(a&&a.owner===c&&!o.returnsCursor){a.endSession((()=>{delete A.session;if(r)return t(r);e(n)}))}else{if(r)return t(r);e(n)}};if(typeof i==="function"){i=r.pop();const e=makeExecuteCallback((e=>i(null,e)),(e=>i(e,null)));r.push(e);try{return t.apply(null,r)}catch(t){e(t);throw t}}if(r[r.length-1]!=null){throw new TypeError("final argument to `executeLegacyOperation` must be a callback")}return new s((function(e,n){const o=makeExecuteCallback(e,n);r[r.length-1]=o;try{return t.apply(null,r)}catch(e){o(e)}}))};function applyRetryableWrites(e,t){if(t&&t.s.options.retryWrites){e.retryWrites=true}return e}function applyWriteConcern(e,t,r){r=r||{};const n=t.db;const s=t.collection;if(r.session&&r.session.inTransaction()){if(e.writeConcern){delete e.writeConcern}return e}const i=o.fromOptions(r);if(i){return Object.assign(e,{writeConcern:i})}if(s&&s.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)})}if(n&&n.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)})}return e}function isPromiseLike(e){return e&&typeof e.then==="function"}function decorateWithCollation(e,t,r){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(r.collation&&typeof r.collation==="object"){if(s&&s.commandsTakeCollation){e.collation=r.collation}else{throw new n(`Current topology does not support collation`)}}}function decorateWithReadConcern(e,t,r){if(r&&r.session&&r.session.inTransaction()){return}let n=Object.assign({},e.readConcern||{});if(t.s.readConcern){Object.assign(n,t.s.readConcern)}if(Object.keys(n).length>0){Object.assign(e,{readConcern:n})}}function decorateWithExplain(e,t){if(e.explain){return e}return{explain:e,verbosity:t.verbosity}}const u=+process.version.split(".")[0].substring(1);const emitProcessWarning=e=>u<=6?process.emitWarning(e,"DeprecationWarning",g):process.emitWarning(e,{type:"DeprecationWarning",code:g});const emitConsoleWarning=e=>console.error(e);const h=process.emitWarning?emitProcessWarning:emitConsoleWarning;function defaultMsgHandler(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}function deprecateOptions(e,t){if(process.noDeprecation===true){return t}const r=e.msgHandler?e.msgHandler:defaultMsgHandler;const n=new Set;function deprecated(){const o=arguments[e.optionsIndex];if(!c(o)||Object.keys(o).length===0){return t.apply(this,arguments)}e.deprecatedOptions.forEach((t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!n.has(t)){n.add(t);const o=r(e.name,t);h(o);if(this&&this.getLogger){const e=this.getLogger();if(e){e.warn(o)}}}}));return t.apply(this,arguments)}Object.setPrototypeOf(deprecated,t);if(t.prototype){deprecated.prototype=t.prototype}return deprecated}const d={};try{r(1749);d.ASYNC_ITERATOR=true}catch(e){d.ASYNC_ITERATOR=false}class MongoDBNamespace{constructor(e,t){this.db=e;this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new MongoDBNamespace(this.db,e)}static fromString(e){if(!e){throw new Error(`Cannot parse namespace from "${e}"`)}const t=e.indexOf(".");return new MongoDBNamespace(e.substring(0,t),e.substring(t+1))}}function*makeCounter(e){let t=e||0;while(true){const e=t;t+=1;yield e}}function maybePromise(e,t,r){const n=e&&e.s&&e.s.promiseLibrary||Promise;let o;if(typeof t!=="function"){o=new n(((e,r)=>{t=(t,n)=>{if(t)return r(t);e(n)}}))}r((function(e,r){if(e!=null){try{t(e)}catch(e){return process.nextTick((()=>{throw e}))}return}t(e,r)}));return o}function now(){const e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}function calculateDurationInMs(e){if(typeof e!=="number"){throw TypeError("numeric value required to calculate duration")}const t=now()-e;return t<0?0:t}function makeInterruptableAsyncInterval(e,t){let r;let n;let o;let s=false;t=t||{};const i=t.interval||1e3;const a=t.minInterval||500;const A=typeof t.immediate==="boolean"?t.immediate:false;const c=typeof t.clock==="function"?t.clock:now;function wake(){const e=c();const t=e-o;const r=e-n;const s=i-r;o=e;if(ta){reschedule(a)}if(s<0){executeAndReschedule()}}function stop(){s=true;if(r){clearTimeout(r);r=null}n=0;o=0}function reschedule(e){if(s)return;clearTimeout(r);r=setTimeout(executeAndReschedule,e||i)}function executeAndReschedule(){o=0;n=c();e((e=>{if(e)throw e;reschedule(i)}))}if(A){executeAndReschedule()}else{n=c();reschedule()}return{wake:wake,stop:stop}}function hasAtomicOperators(e){if(Array.isArray(e)){return e.reduce(((e,t)=>e||hasAtomicOperators(t)),null)}return Object.keys(typeof e.toBSON!=="function"?e:e.toBSON()).map((e=>e[0])).indexOf("$")>=0}const g="MONGODB DRIVER";function emitWarning(e){if(process.emitWarning){return u<=6?process.emitWarning(e,undefined,g):process.emitWarning(e,{code:g})}else{return console.error(`[${g}] Warning:`,e)}}const p=new Set;function emitWarningOnce(e){if(!p.has(e)){p.add(e);return emitWarning(e)}}function isSuperset(e,t){e=Array.isArray(e)?new Set(e):e;t=Array.isArray(t)?new Set(t):t;for(const r of t){if(!e.has(r)){return false}}return true}function isRecord(e,t){const r=Object.prototype.toString;const n=Object.prototype.hasOwnProperty;const isObject=e=>r.call(e)==="[object Object]";if(!isObject(e)){return false}const o=e.constructor;if(o&&o.prototype){if(!isObject(o.prototype)){return false}if(!n.call(o.prototype,"isPrototypeOf")){return false}}if(t){const r=Object.keys(e);return isSuperset(r,t)}return true}function deepCopy(e){if(e==null){return e}else if(Array.isArray(e)){return e.map((e=>deepCopy(e)))}else if(isRecord(e)){const t={};for(const r in e){t[r]=deepCopy(e[r])}return t}const t=e.constructor;if(t){switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}}return e}function parsePackageVersion(e){const t=e.version.split(".").map((e=>Number.parseInt(e,10)));return{major:t[0],minor:t[1],patch:t[2]}}e.exports={filterOptions:filterOptions,mergeOptions:mergeOptions,translateOptions:translateOptions,shallowClone:shallowClone,getSingleProperty:getSingleProperty,checkCollectionName:a,toError:toError,formattedOrderClause:i,parseIndexOptions:parseIndexOptions,normalizeHintField:A,handleCallback:handleCallback,decorateCommand:decorateCommand,isObject:c,debugOptions:debugOptions,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:conditionallyMergeWriteConcern,executeLegacyOperation:executeLegacyOperation,applyRetryableWrites:applyRetryableWrites,applyWriteConcern:applyWriteConcern,isPromiseLike:isPromiseLike,decorateWithCollation:decorateWithCollation,decorateWithReadConcern:decorateWithReadConcern,decorateWithExplain:decorateWithExplain,deprecateOptions:deprecateOptions,SUPPORTS:d,MongoDBNamespace:MongoDBNamespace,emitDeprecationWarning:h,makeCounter:makeCounter,maybePromise:maybePromise,now:now,calculateDurationInMs:calculateDurationInMs,makeInterruptableAsyncInterval:makeInterruptableAsyncInterval,hasAtomicOperators:hasAtomicOperators,MONGODB_WARNING_CODE:g,emitWarning:emitWarning,emitWarningOnce:emitWarningOnce,deepCopy:deepCopy,parsePackageVersion:parsePackageVersion}},2481:(e,t,r)=>{"use strict";const n=new Set(["w","wtimeout","j","journal","fsync"]);let o;class WriteConcern{constructor(e,t,r,n){if(e!=null){this.w=e}if(t!=null){this.wtimeout=t}if(r!=null){this.j=r}if(n!=null){this.fsync=n}}static fromOptions(e){if(e==null||e.writeConcern==null&&e.w==null&&e.wtimeout==null&&e.j==null&&e.journal==null&&e.fsync==null){return}if(e.writeConcern){if(typeof e.writeConcern==="string"){return new WriteConcern(e.writeConcern)}if(!Object.keys(e.writeConcern).some((e=>n.has(e)))){return}return new WriteConcern(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}if(!o)o=r(1371);o.emitWarningOnce(`Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.`);return new WriteConcern(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}e.exports=WriteConcern},900:e=>{var t=1e3;var r=t*60;var n=r*60;var o=n*24;var s=o*7;var i=o*365.25;e.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0){return parse(e)}else if(r==="number"&&isFinite(e)){return t.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a){return}var A=parseFloat(a[1]);var c=(a[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return A*i;case"weeks":case"week":case"w":return A*s;case"days":case"day":case"d":return A*o;case"hours":case"hour":case"hrs":case"hr":case"h":return A*n;case"minutes":case"minute":case"mins":case"min":case"m":return A*r;case"seconds":case"second":case"secs":case"sec":case"s":return A*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return undefined}}function fmtShort(e){var s=Math.abs(e);if(s>=o){return Math.round(e/o)+"d"}if(s>=n){return Math.round(e/n)+"h"}if(s>=r){return Math.round(e/r)+"m"}if(s>=t){return Math.round(e/t)+"s"}return e+"ms"}function fmtLong(e){var s=Math.abs(e);if(s>=o){return plural(e,s,o,"day")}if(s>=n){return plural(e,s,n,"hour")}if(s>=r){return plural(e,s,r,"minute")}if(s>=t){return plural(e,s,t,"second")}return e+" ms"}function plural(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}},1156:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.findSync=t.find=t.findAsync=void 0;const n=r(4351);const o=r(1017);const s=r(7147);const i=r(8237);const a=i("new-find-package-json:main");function findAsync(e,t,r){return n.__asyncGenerator(this,arguments,(function*findAsync_1(){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const s=!!r?r:"package.json";const i=!!t||o.isAbsolute(t)?t:process.cwd();let A=o.resolve(i,e);let c=false;while(A){if(A===o.parse(A).root){c=true}const e=o.resolve(A,s);a(`findSync: testing path "${e}"`);const t=yield n.__await(statPathAsync(e));if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield yield n.__await(e);a(`findSync: after yield`)}if(c){break}A=o.resolve(A,"..")}}))}t.findAsync=findAsync;t.find=findAsync;function*findSync(e,t,r){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const n=!!r?r:"package.json";const s=!!t||o.isAbsolute(t)?t:process.cwd();let i=o.resolve(s,e);let A=false;while(i){if(i===o.parse(i).root){A=true}const e=o.resolve(i,n);a(`findSync: testing path "${e}"`);const t=statPathSync(e);if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield e;a(`findSync: after yield`)}if(A){break}i=o.resolve(i,"..")}}t.findSync=findSync;function statPathSync(e){try{return s.statSync(e)}catch(e){if(e.code==="ENOENT"){return undefined}throw e}}function statPathAsync(e){return n.__awaiter(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(e.code==="ENOENT"){return undefined}throw e}))}))}},1223:(e,t,r)=>{var n=r(2940);e.exports=n(once);e.exports.strict=n(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})}));function once(e){var f=function(){if(f.called)return f.value;f.called=true;return f.value=e.apply(this,arguments)};f.called=false;return f}function onceStrict(e){var f=function(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=e.apply(this,arguments)};var t=e.name||"Function wrapped with `once`";f.onceError=t+" shouldn't be called more than once";f.called=false;return f}},9341:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";const n=r(9341);e.exports=function(){return n.makeOptionalRequire.apply(n,arguments)};e.exports.tryRequire=n.tryRequire;e.exports.tryResolve=n.tryResolve;e.exports["try"]=n.tryRequire;e.exports.resolve=n.tryResolve;e.exports.makeOptionalRequire=n.makeOptionalRequire;e.exports.optionalRequire=n.optionalRequire;e.exports.optionalRequireCwd=n.optionalRequireCwd;e.exports.optionalRequireTop=n.optionalRequireTop;let o;Object.defineProperty(e.exports,"log",{set(e){o=e;n.setDefaultLog(e)},get(){return o}})},6978:(e,t,r)=>{"use strict";const n=r(7147);const{promisify:o}=r(3837);const s=o(n.access);e.exports=async e=>{try{await s(e);return true}catch(e){return false}};e.exports.sync=e=>{try{n.accessSync(e);return true}catch(e){return false}}},8714:e=>{"use strict";function posix(e){return e.charAt(0)==="/"}function win32(e){var t=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var r=t.exec(e);var n=r[1]||"";var o=Boolean(n&&n.charAt(1)!==":");return Boolean(r[2]||o)}e.exports=process.platform==="win32"?win32:posix;e.exports.posix=posix;e.exports.win32=win32},4833:e=>{e.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}Pend.prototype.go=function(e){if(this.pending0&&e.pending{"use strict";const n=r(1017);const o=r(1812);const pkgDir=async e=>{const t=await o("package.json",{cwd:e});return t&&n.dirname(t)};e.exports=pkgDir;e.exports["default"]=pkgDir;e.exports.sync=e=>{const t=o.sync("package.json",{cwd:e});return t&&n.dirname(t)}},1812:(e,t,r)=>{"use strict";const n=r(1017);const o=r(5937);const s=r(6978);const i=Symbol("findUp.stop");e.exports=async(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=async t=>{if(typeof e!=="function"){return o(a,t)}const r=await e(t.cwd);if(typeof r==="string"){return o([r],t)}return r};while(true){const e=await runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.sync=(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=t=>{if(typeof e!=="function"){return o.sync(a,t)}const r=e(t.cwd);if(typeof r==="string"){return o.sync([r],t)}return r};while(true){const e=runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.exists=s;e.exports.sync.exists=s.sync;e.exports.stop=i},5937:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const{promisify:s}=r(3837);const i=r(6249);const a=s(o.stat);const A=s(o.lstat);const c={directory:"isDirectory",file:"isFile"};function checkType({type:e}){if(e in c){return}throw new Error(`Invalid type specified: ${e}`)}const matchType=(e,t)=>e===undefined||t[c[e]]();e.exports=async(e,t)=>{t={cwd:process.cwd(),type:"file",allowSymlinks:true,...t};checkType(t);const r=t.allowSymlinks?a:A;return i(e,(async e=>{try{const o=await r(n.resolve(t.cwd,e));return matchType(t.type,o)}catch(e){return false}}),t)};e.exports.sync=(e,t)=>{t={cwd:process.cwd(),allowSymlinks:true,type:"file",...t};checkType(t);const r=t.allowSymlinks?o.statSync:o.lstatSync;for(const o of e){try{const e=r(n.resolve(t.cwd,o));if(matchType(t.type,e)){return o}}catch(e){}}}},4752:(e,t,r)=>{"use strict";const n=r(7471);const pLimit=e=>{if(!((Number.isInteger(e)||e===Infinity)&&e>0)){return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"))}const t=[];let r=0;const next=()=>{r--;if(t.length>0){t.shift()()}};const run=(e,t,...o)=>{r++;const s=n(e,...o);t(s);s.then(next,next)};const enqueue=(n,o,...s)=>{if(rnew Promise((r=>enqueue(e,r,...t)));Object.defineProperties(generator,{activeCount:{get:()=>r},pendingCount:{get:()=>t.length},clearQueue:{value:()=>{t.length=0}}});return generator};e.exports=pLimit;e.exports["default"]=pLimit},6249:(e,t,r)=>{"use strict";const n=r(4752);class EndError extends Error{constructor(e){super();this.value=e}}const testElement=async(e,t)=>t(await e);const finder=async e=>{const t=await Promise.all(e);if(t[1]===true){throw new EndError(t[0])}return false};const pLocate=async(e,t,r)=>{r={concurrency:Infinity,preserveOrder:true,...r};const o=n(r.concurrency);const s=[...e].map((e=>[e,o(testElement,e,t)]));const i=n(r.preserveOrder?1:Infinity);try{await Promise.all(s.map((e=>i(finder,e))))}catch(e){if(e instanceof EndError){return e.value}throw e}};e.exports=pLocate;e.exports["default"]=pLocate},7471:e=>{"use strict";const pTry=(e,...t)=>new Promise((r=>{r(e(...t))}));e.exports=pTry;e.exports["default"]=pTry},7214:e=>{"use strict";const t={};function createErrorType(e,r,n){if(!n){n=Error}function getMessage(e,t,n){if(typeof r==="string"){return r}else{return r(e,t,n)}}class NodeError extends n{constructor(e,t,r){super(getMessage(e,t,r))}}NodeError.prototype.name=n.name;NodeError.prototype.code=e;t[e]=NodeError}function oneOf(e,t){if(Array.isArray(e)){const r=e.length;e=e.map((e=>String(e)));if(r>2){return`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]}else if(r===2){return`one of ${t} ${e[0]} or ${e[1]}`}else{return`of ${t} ${e[0]}`}}else{return`of ${t} ${String(e)}`}}function startsWith(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function endsWith(e,t,r){if(r===undefined||r>e.length){r=e.length}return e.substring(r-t.length,r)===t}function includes(e,t,r){if(typeof r!=="number"){r=0}if(r+t.length>e.length){return false}else{return e.indexOf(t,r)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(e,t,r){let n;if(typeof t==="string"&&startsWith(t,"not ")){n="must not be";t=t.replace(/^not /,"")}else{n="must be"}let o;if(endsWith(e," argument")){o=`The ${e} ${n} ${oneOf(t,"type")}`}else{const r=includes(e,".")?"property":"argument";o=`The "${e}" ${r} ${n} ${oneOf(t,"type")}`}o+=`. Received type ${typeof r}`;return o}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.q=t},1359:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=r(1433);var s=r(6993);r(4124)(Duplex,o);{var i=n(s.prototype);for(var a=0;a{"use strict";e.exports=PassThrough;var n=r(4415);r(4124)(PassThrough,n);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);n.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},1433:(e,t,r)=>{"use strict";e.exports=Readable;var n;Readable.ReadableState=ReadableState;var o=r(2361).EventEmitter;var s=function EElistenerCount(e,t){return e.listeners(t).length};var i=r(2387);var a=r(4300).Buffer;var A=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return a.from(e)}function _isUint8Array(e){return a.isBuffer(e)||e instanceof A}var c=r(3837);var l;if(c&&c.debuglog){l=c.debuglog("stream")}else{l=function debug(){}}var u=r(2746);var h=r(7049);var d=r(9948),g=d.getHighWaterMark;var p=r(7214).q,E=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,C=p.ERR_METHOD_NOT_IMPLEMENTED,I=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var y;var B;var Q;r(4124)(Readable,i);var b=h.errorOrDestroy;var w=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(Array.isArray(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.readableObjectMode;this.highWaterMark=g(this,e,"readableHighWaterMark",o);this.buffer=new u;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(4841).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){n=n||r(1359);if(!(this instanceof Readable))return new Readable(e);var t=this instanceof n;this._readableState=new ReadableState(e,this,t);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}i.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=h.destroy;Readable.prototype._undestroy=h.undestroy;Readable.prototype._destroy=function(e,t){t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var n;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=a.from(e,t);t=""}n=true}}else{n=true}return readableAddChunk(this,e,t,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,n,o){l("readableAddChunk",t);var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var i;if(!o)i=chunkInvalid(s,t);if(i){b(e,i)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==a.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(s.endEmitted)b(e,new I);else addChunk(e,s,t,true)}else if(s.ended){b(e,new m)}else if(s.destroyed){return false}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!n){s.reading=false;maybeReadMore(e,s)}}return!s.ended&&(s.length=S){e=S}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){l("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=t.length<=t.highWaterMark;e=0}else{t.length-=e;t.awaitDrain=0}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){l("onEofChunk");if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.sync){emitReadable(e)}else{t.needReadable=false;if(!t.emittedReadable){t.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable);t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended);if(!t.destroyed&&(t.length||t.ended)){e.emit("readable");t.emittedReadable=false}t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark;flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;process.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){while(!t.reading&&!t.ended&&(t.length1&&indexOf(n.pipes,e)!==-1)&&!A){l("false write response, pause",n.awaitDrain);n.awaitDrain++}r.pause()}}function onerror(t){l("onerror",t);unpipe();e.removeListener("error",onerror);if(s(e,"error")===0)b(e,t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){l("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){l("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!n.flowing){l("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&s(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var n=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;l("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return r};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);if(e==="readable"){process.nextTick(updateReadableListening,this)}return r};Readable.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return t};function updateReadableListening(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0;if(t.resumeScheduled&&!t.paused){t.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){l("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){l("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,t){if(!t.resumeScheduled){t.resumeScheduled=true;process.nextTick(resume_,e,t)}}function resume_(e,t){l("resume",t.reading);if(!t.reading){e.read(0)}t.resumeScheduled=false;e.emit("resume");flow(e);if(t.flowing&&!t.reading)e.read(0)}Readable.prototype.pause=function(){l("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){l("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var t=e._readableState;l("flow",t.flowing);while(t.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var t=this;var r=this._readableState;var n=false;e.on("end",(function(){l("wrapped end");if(r.decoder&&!r.ended){var e=r.decoder.end();if(e&&e.length)t.push(e)}t.push(null)}));e.on("data",(function(o){l("wrapped data");if(r.decoder)o=r.decoder.write(o);if(r.objectMode&&(o===null||o===undefined))return;else if(!r.objectMode&&(!o||!o.length))return;var s=t.push(o);if(!s){n=true;e.pause()}}));for(var o in e){if(this[o]===undefined&&typeof e[o]==="function"){this[o]=function methodWrap(t){return function methodWrapReturnFunction(){return e[t].apply(e,arguments)}}(o)}}for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.first();else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=t.buffer.consume(e,t.decoder)}return r}function endReadable(e){var t=e._readableState;l("endReadable",t.endEmitted);if(!t.endEmitted){t.ended=true;process.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){l("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end");if(e.autoDestroy){var r=t._writableState;if(!r||r.autoDestroy&&r.finished){t.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(e,t){if(Q===undefined){Q=r(9082)}return Q(Readable,e,t)}}function indexOf(e,t){for(var r=0,n=e.length;r{"use strict";e.exports=Transform;var n=r(7214).q,o=n.ERR_METHOD_NOT_IMPLEMENTED,s=n.ERR_MULTIPLE_CALLBACK,i=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=n.ERR_TRANSFORM_WITH_LENGTH_0;var A=r(1359);r(4124)(Transform,A);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null){return this.emit("error",new s)}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);n(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var n;Writable.WritableState=WritableState;var o={deprecate:r(5278)};var s=r(2387);var i=r(4300).Buffer;var a=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return i.from(e)}function _isUint8Array(e){return i.isBuffer(e)||e instanceof a}var A=r(7049);var c=r(9948),l=c.getHighWaterMark;var u=r(7214).q,h=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,g=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,E=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,C=u.ERR_STREAM_WRITE_AFTER_END,I=u.ERR_UNKNOWN_ENCODING;var y=A.errorOrDestroy;r(4124)(Writable,s);function nop(){}function WritableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.writableObjectMode;this.highWaterMark=l(this,e,"writableHighWaterMark",o);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var s=e.decodeStrings===false;this.decodeStrings=!s;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:o.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var B;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){B=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(e){if(B.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{B=function realHasInstance(e){return e instanceof this}}function Writable(e){n=n||r(1359);var t=this instanceof n;if(!t&&!B.call(Writable,this))return new Writable(e);this._writableState=new WritableState(e,this,t);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}s.call(this)}Writable.prototype.pipe=function(){y(this,new p)};function writeAfterEnd(e,t){var r=new C;y(e,r);process.nextTick(t,r)}function validChunk(e,t,r,n){var o;if(r===null){o=new m}else if(typeof r!=="string"&&!t.objectMode){o=new h("chunk",["string","Buffer"],r)}if(o){y(e,o);process.nextTick(n,o);return false}return true}Writable.prototype.write=function(e,t,r){var n=this._writableState;var o=false;var s=!n.objectMode&&_isUint8Array(e);if(s&&!i.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=n.defaultEncoding;if(typeof r!=="function")r=nop;if(n.ending)writeAfterEnd(this,r);else if(s||validChunk(this,n,e,r)){n.pendingcb++;o=writeOrBuffer(this,n,s,e,t,r)}return o};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new I(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=i.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,n,o,s){if(!r){var i=decodeChunk(t,n,o);if(n!==i){r=true;o="buffer";n=i}}var a=t.objectMode?1:n.length;t.length+=a;var A=t.length{"use strict";var n;function _defineProperty(e,t,r){if(t in e){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true})}else{e[t]=r}return e}var o=r(6080);var s=Symbol("lastResolve");var i=Symbol("lastReject");var a=Symbol("error");var A=Symbol("ended");var c=Symbol("lastPromise");var l=Symbol("handlePromise");var u=Symbol("stream");function createIterResult(e,t){return{value:e,done:t}}function readAndResolve(e){var t=e[s];if(t!==null){var r=e[u].read();if(r!==null){e[c]=null;e[s]=null;e[i]=null;t(createIterResult(r,false))}}}function onReadable(e){process.nextTick(readAndResolve,e)}function wrapForNext(e,t){return function(r,n){e.then((function(){if(t[A]){r(createIterResult(undefined,true));return}t[l](r,n)}),n)}}var h=Object.getPrototypeOf((function(){}));var d=Object.setPrototypeOf((n={get stream(){return this[u]},next:function next(){var e=this;var t=this[a];if(t!==null){return Promise.reject(t)}if(this[A]){return Promise.resolve(createIterResult(undefined,true))}if(this[u].destroyed){return new Promise((function(t,r){process.nextTick((function(){if(e[a]){r(e[a])}else{t(createIterResult(undefined,true))}}))}))}var r=this[c];var n;if(r){n=new Promise(wrapForNext(r,this))}else{var o=this[u].read();if(o!==null){return Promise.resolve(createIterResult(o,false))}n=new Promise(this[l])}this[c]=n;return n}},_defineProperty(n,Symbol.asyncIterator,(function(){return this})),_defineProperty(n,"return",(function _return(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){if(e){r(e);return}t(createIterResult(undefined,true))}))}))})),n),h);var g=function createReadableStreamAsyncIterator(e){var t;var r=Object.create(d,(t={},_defineProperty(t,u,{value:e,writable:true}),_defineProperty(t,s,{value:null,writable:true}),_defineProperty(t,i,{value:null,writable:true}),_defineProperty(t,a,{value:null,writable:true}),_defineProperty(t,A,{value:e._readableState.endEmitted,writable:true}),_defineProperty(t,l,{value:function value(e,t){var n=r[u].read();if(n){r[c]=null;r[s]=null;r[i]=null;e(createIterResult(n,false))}else{r[s]=e;r[i]=t}},writable:true}),t));r[c]=null;o(e,(function(e){if(e&&e.code!=="ERR_STREAM_PREMATURE_CLOSE"){var t=r[i];if(t!==null){r[c]=null;r[s]=null;r[i]=null;t(e)}r[a]=e;return}var n=r[s];if(n!==null){r[c]=null;r[s]=null;r[i]=null;n(createIterResult(undefined,true))}r[A]=true}));e.on("readable",onReadable.bind(null,r));return r};e.exports=g},2746:(e,t,r)=>{"use strict";function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t0)this.tail.next=t;else this.head=t;this.tail=t;++this.length}},{key:"unshift",value:function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r}},{key:"concat",value:function concat(e){if(this.length===0)return o.alloc(0);var t=o.allocUnsafe(e>>>0);var r=this.head;var n=0;while(r){copyBuffer(r.data,t,n);n+=r.data.length;r=r.next}return t}},{key:"consume",value:function consume(e,t){var r;if(eo.length?o.length:e;if(s===o.length)n+=o;else n+=o.slice(0,e);e-=s;if(e===0){if(s===o.length){++r;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=o.slice(s)}break}++r}this.length-=r;return n}},{key:"_getBuffer",value:function _getBuffer(e){var t=o.allocUnsafe(e);var r=this.head;var n=1;r.data.copy(t);e-=r.data.length;while(r=r.next){var s=r.data;var i=e>s.length?s.length:e;s.copy(t,t.length-e,0,i);e-=i;if(e===0){if(i===s.length){++n;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=s.slice(i)}break}++n}this.length-=n;return t}},{key:a,value:function value(e,t){return i(this,_objectSpread({},t,{depth:0,customInspect:false}))}}]);return BufferList}()},7049:e=>{"use strict";function destroy(e,t){var r=this;var n=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(n||o){if(t){t(e)}else if(e){if(!this._writableState){process.nextTick(emitErrorNT,this,e)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,e)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){if(!r._writableState){process.nextTick(emitErrorAndCloseNT,r,e)}else if(!r._writableState.errorEmitted){r._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,r,e)}else{process.nextTick(emitCloseNT,r)}}else if(t){process.nextTick(emitCloseNT,r);t(e)}else{process.nextTick(emitCloseNT,r)}}));return this}function emitErrorAndCloseNT(e,t){emitErrorNT(e,t);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}function errorOrDestroy(e,t){var r=e._readableState;var n=e._writableState;if(r&&r.autoDestroy||n&&n.autoDestroy)e.destroy(t);else e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},6080:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_STREAM_PREMATURE_CLOSE;function once(e){var t=false;return function(){if(t)return;t=true;for(var r=arguments.length,n=new Array(r),o=0;o{"use strict";function asyncGeneratorStep(e,t,r,n,o,s,i){try{var a=e[s](i);var A=a.value}catch(e){r(e);return}if(a.done){t(A)}else{Promise.resolve(A).then(n,o)}}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var s=e.apply(t,r);function _next(e){asyncGeneratorStep(s,n,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(s,n,o,_next,_throw,"throw",e)}_next(undefined)}))}}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t{"use strict";var n;function once(e){var t=false;return function(){if(t)return;t=true;e.apply(void 0,arguments)}}var o=r(7214).q,s=o.ERR_MISSING_ARGS,i=o.ERR_STREAM_DESTROYED;function noop(e){if(e)throw e}function isRequest(e){return e.setHeader&&typeof e.abort==="function"}function destroyer(e,t,o,s){s=once(s);var a=false;e.on("close",(function(){a=true}));if(n===undefined)n=r(6080);n(e,{readable:t,writable:o},(function(e){if(e)return s(e);a=true;s()}));var A=false;return function(t){if(a)return;if(A)return;A=true;if(isRequest(e))return e.abort();if(typeof e.destroy==="function")return e.destroy();s(t||new i("pipe"))}}function call(e){e()}function pipe(e,t){return e.pipe(t)}function popCallback(e){if(!e.length)return noop;if(typeof e[e.length-1]!=="function")return noop;return e.pop()}function pipeline(){for(var e=arguments.length,t=new Array(e),r=0;r0;return destroyer(e,s,a,(function(e){if(!o)o=e;if(e)i.forEach(call);if(s)return;i.forEach(call);n(o)}))}));return t.reduce(pipe)}e.exports=pipeline},9948:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function getHighWaterMark(e,t,r,o){var s=highWaterMarkFrom(t,o,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var i=o?r:"highWaterMark";throw new n(i,s)}return Math.floor(s)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},2387:(e,t,r)=>{e.exports=r(2781)},1642:(e,t,r)=>{var n=r(2781);if(process.env.READABLE_STREAM==="disable"&&n){e.exports=n.Readable;Object.assign(e.exports,n);e.exports.Stream=n}else{t=e.exports=r(1433);t.Stream=n||t;t.Readable=t;t.Writable=r(6993);t.Duplex=r(1359);t.Transform=r(4415);t.PassThrough=r(1542);t.finished=r(6080);t.pipeline=r(6989)}},545:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";const Module=__nccwpck_require__(8188);const xrequire=eval("require");const createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{const r=new Module(e);r.filename=e;r.paths=Module._nodeModulePaths(t);function _require(e){return xrequire(resolve(e))}function resolve(e,t){return Module._resolveFilename(e,r,false,t)}_require.resolve=resolve;function paths(e){return Module._resolveLookupPaths(e,r,true)}resolve.paths=paths;_require.main=process.mainModule;_require.extensions=Module._extensions;_require.cache=Module._cache;return _require});module.exports=createRequireFromPath},2058:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(545);const i=new Map;function requireAt(e,t){const makeIt=(r,i)=>{let a=requireAt.cache&&requireAt.cache.get(r);if(!a){let t;try{t=o.statSync(r)}catch(e){throw new Error(`require-at: stat '${r}' failed: ${e.message}`)}if(!t||!t.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return makeIt(n.dirname(r),true)}a=s(n.join(r,"._require-at_"),r);requireAt.cache&&requireAt.cache.set(r,a)}return t?a(t):a};return makeIt(n.resolve(e),false)}requireAt.cache=i;e.exports=requireAt},4959:(e,t,r)=>{const n=r(9491);const o=r(1017);const s=r(7147);let i=undefined;try{i=r(1957)}catch(e){}const a={nosort:true,silent:true};let A=0;const c=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&i===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||a};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof r,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let a=0;const next=e=>{s=s||e;if(--a===0)r(s)};const afterGlob=(e,n)=>{if(e)return r(e);a=n.length;if(a===0)return r();n.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&Arimraf_(e,t,CB)),A++)}if(r.code==="ENOENT")r=null}A=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!i.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,n)=>{if(!r)return afterGlob(null,[e]);i(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.lstat(e,((n,o)=>{if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&c)fixWinEPERM(e,t,n,r);if(o&&o.isDirectory())return rmdir(e,t,n,r);t.unlink(e,(n=>{if(n){if(n.code==="ENOENT")return r(null);if(n.code==="EPERM")return c?fixWinEPERM(e,t,n,r):rmdir(e,t,n,r);if(n.code==="EISDIR")return rmdir(e,t,n,r)}return r(n)}))}))};const fixWinEPERM=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.chmod(e,438,(n=>{if(n)o(n.code==="ENOENT"?null:r);else t.stat(e,((n,s)=>{if(n)o(n.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{n(e);n(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.rmdir(e,(n=>{if(n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM"))rmkids(e,t,o);else if(n&&n.code==="ENOTDIR")o(r);else o(n)}))};const rmkids=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.readdir(e,((n,s)=>{if(n)return r(n);let i=s.length;if(i===0)return t.rmdir(e,r);let a;s.forEach((n=>{rimraf(o.join(e,n),t,(n=>{if(a)return;if(n)return r(a=n);if(--i===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n(t,"rimraf: missing options");n.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!i.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(n){r=i.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{n(e);n(t);try{t.rmdirSync(e)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;if(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{n(e);n(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=c?100:1;let s=0;do{let n=true;try{const r=t.rmdirSync(e,t);n=false;return r}finally{if(++s{var n=r(4300);var o=n.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=o(e);if(t!==undefined){if(typeof r==="string"){n.fill(t,r)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},9178:(e,t,r)=>{"use strict";const{unassigned_code_points:n,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:A}=r(8916);e.exports=saslprep;const c=s;const l=o;const getCodePoint=e=>e.codePointAt(0);const first=e=>e[0];const last=e=>e[e.length-1];function toCodePoints(e){const t=[];const r=e.length;for(let n=0;n=55296&&o<=56319&&r>n+1){const r=e.charCodeAt(n+1);if(r>=56320&&r<=57343){t.push((o-55296)*1024+r-56320+65536);n+=1;continue}}t.push(o)}return t}function saslprep(e,t={}){if(typeof e!=="string"){throw new TypeError("Expected string.")}if(e.length===0){return""}const r=toCodePoints(e).map((e=>c.get(e)?32:e)).filter((e=>!l.get(e)));const o=String.fromCodePoint.apply(null,r).normalize("NFKC");const s=toCodePoints(o);const u=s.some((e=>i.get(e)));if(u){throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3")}if(t.allowUnassigned!==true){const e=s.some((e=>n.get(e)));if(e){throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}}const h=s.some((e=>a.get(e)));const d=s.some((e=>A.get(e)));if(h&&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 g=a.get(getCodePoint(first(o)));const p=a.get(getCodePoint(last(o)));if(h&&!(g&&p)){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}},8916:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const s=r(1453);const i=n.readFileSync(r.ab+"code-points.mem");let a=0;function read(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);a+=e;return s({buffer:t})}const A=read();const c=read();const l=read();const u=read();const h=read();const d=read();e.exports={unassigned_code_points:A,commonly_mapped_to_nothing:c,non_ASCII_space_characters:l,prohibited_characters:u,bidirectional_r_al:h,bidirectional_l:d}},1532:(e,t,r)=>{const n=Symbol("SemVer ANY");class Comparator{static get ANY(){return n}constructor(e,t){t=o(t);if(e instanceof Comparator){if(e.loose===!!t.loose){return e}else{e=e.value}}e=e.trim().split(/\s+/).join(" ");A("comparator",e,t);this.options=t;this.loose=!!t.loose;this.parse(e);if(this.semver===n){this.value=""}else{this.value=this.operator+this.semver.version}A("comp",this)}parse(e){const t=this.options.loose?s[i.COMPARATORLOOSE]:s[i.COMPARATOR];const r=e.match(t);if(!r){throw new TypeError(`Invalid comparator: ${e}`)}this.operator=r[1]!==undefined?r[1]:"";if(this.operator==="="){this.operator=""}if(!r[2]){this.semver=n}else{this.semver=new c(r[2],this.options.loose)}}toString(){return this.value}test(e){A("Comparator.test",e,this.options.loose);if(this.semver===n||e===n){return true}if(typeof e==="string"){try{e=new c(e,this.options)}catch(e){return false}}return a(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator)){throw new TypeError("a Comparator is required")}if(this.operator===""){if(this.value===""){return true}return new l(e.value,t).test(this.value)}else if(e.operator===""){if(e.value===""){return true}return new l(this.value,t).test(e.semver)}t=o(t);if(t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")){return false}if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))){return false}if(this.operator.startsWith(">")&&e.operator.startsWith(">")){return true}if(this.operator.startsWith("<")&&e.operator.startsWith("<")){return true}if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")){return true}if(a(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")){return true}if(a(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")){return true}return false}}e.exports=Comparator;const o=r(785);const{safeRe:s,t:i}=r(9523);const a=r(5098);const A=r(427);const c=r(8088);const l=r(9828)},9828:(e,t,r)=>{class Range{constructor(e,t){t=s(t);if(e instanceof Range){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{return new Range(e.raw,t)}}if(e instanceof i){this.raw=e.value;this.set=[[e]];this.format();return this}this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;this.raw=e.trim().split(/\s+/).join(" ");this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length));if(!this.set.length){throw new TypeError(`Invalid SemVer Range: ${this.raw}`)}if(this.set.length>1){const e=this.set[0];this.set=this.set.filter((e=>!isNullSet(e[0])));if(this.set.length===0){this.set=[e]}else if(this.set.length>1){for(const e of this.set){if(e.length===1&&isAny(e[0])){this.set=[e];break}}}}this.format()}format(){this.range=this.set.map((e=>e.join(" ").trim())).join("||").trim();return this.range}toString(){return this.range}parseRange(e){const t=(this.options.includePrerelease&&g)|(this.options.loose&&p);const r=t+":"+e;const n=o.get(r);if(n){return n}const s=this.options.loose;const A=s?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(A,hyphenReplace(this.options.includePrerelease));a("hyphen replace",e);e=e.replace(c[l.COMPARATORTRIM],u);a("comparator trim",e);e=e.replace(c[l.TILDETRIM],h);a("tilde trim",e);e=e.replace(c[l.CARETTRIM],d);a("caret trim",e);let E=e.split(" ").map((e=>parseComparator(e,this.options))).join(" ").split(/\s+/).map((e=>replaceGTE0(e,this.options)));if(s){E=E.filter((e=>{a("loose invalid filter",e,this.options);return!!e.match(c[l.COMPARATORLOOSE])}))}a("range list",E);const m=new Map;const C=E.map((e=>new i(e,this.options)));for(const e of C){if(isNullSet(e)){return[e]}m.set(e.value,e)}if(m.size>1&&m.has("")){m.delete("")}const I=[...m.values()];o.set(r,I);return I}intersects(e,t){if(!(e instanceof Range)){throw new TypeError("a Range is required")}return this.set.some((r=>isSatisfiable(r,t)&&e.set.some((e=>isSatisfiable(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e){return false}if(typeof e==="string"){try{e=new A(e,this.options)}catch(e){return false}}for(let t=0;te.value==="<0.0.0-0";const isAny=e=>e.value==="";const isSatisfiable=(e,t)=>{let r=true;const n=e.slice();let o=n.pop();while(r&&n.length){r=n.every((e=>o.intersects(e,t)));o=n.pop()}return r};const parseComparator=(e,t)=>{a("comp",e,t);e=replaceCarets(e,t);a("caret",e);e=replaceTildes(e,t);a("tildes",e);e=replaceXRanges(e,t);a("xrange",e);e=replaceStars(e,t);a("stars",e);return e};const isX=e=>!e||e.toLowerCase()==="x"||e==="*";const replaceTildes=(e,t)=>e.trim().split(/\s+/).map((e=>replaceTilde(e,t))).join(" ");const replaceTilde=(e,t)=>{const r=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(r,((t,r,n,o,s)=>{a("tilde",e,t,r,n,o,s);let i;if(isX(r)){i=""}else if(isX(n)){i=`>=${r}.0.0 <${+r+1}.0.0-0`}else if(isX(o)){i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`}else if(s){a("replaceTilde pr",s);i=`>=${r}.${n}.${o}-${s} <${r}.${+n+1}.0-0`}else{i=`>=${r}.${n}.${o} <${r}.${+n+1}.0-0`}a("tilde return",i);return i}))};const replaceCarets=(e,t)=>e.trim().split(/\s+/).map((e=>replaceCaret(e,t))).join(" ");const replaceCaret=(e,t)=>{a("caret",e,t);const r=t.loose?c[l.CARETLOOSE]:c[l.CARET];const n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,o,s,i)=>{a("caret",e,t,r,o,s,i);let A;if(isX(r)){A=""}else if(isX(o)){A=`>=${r}.0.0${n} <${+r+1}.0.0-0`}else if(isX(s)){if(r==="0"){A=`>=${r}.${o}.0${n} <${r}.${+o+1}.0-0`}else{A=`>=${r}.${o}.0${n} <${+r+1}.0.0-0`}}else if(i){a("replaceCaret pr",i);if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}-${i} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}-${i} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s}-${i} <${+r+1}.0.0-0`}}else{a("no pr");if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}${n} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}${n} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s} <${+r+1}.0.0-0`}}a("caret return",A);return A}))};const replaceXRanges=(e,t)=>{a("replaceXRanges",e,t);return e.split(/\s+/).map((e=>replaceXRange(e,t))).join(" ")};const replaceXRange=(e,t)=>{e=e.trim();const r=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(r,((r,n,o,s,i,A)=>{a("xRange",e,r,n,o,s,i,A);const c=isX(o);const l=c||isX(s);const u=l||isX(i);const h=u;if(n==="="&&h){n=""}A=t.includePrerelease?"-0":"";if(c){if(n===">"||n==="<"){r="<0.0.0-0"}else{r="*"}}else if(n&&h){if(l){s=0}i=0;if(n===">"){n=">=";if(l){o=+o+1;s=0;i=0}else{s=+s+1;i=0}}else if(n==="<="){n="<";if(l){o=+o+1}else{s=+s+1}}if(n==="<"){A="-0"}r=`${n+o}.${s}.${i}${A}`}else if(l){r=`>=${o}.0.0${A} <${+o+1}.0.0-0`}else if(u){r=`>=${o}.${s}.0${A} <${o}.${+s+1}.0-0`}a("xRange return",r);return r}))};const replaceStars=(e,t)=>{a("replaceStars",e,t);return e.trim().replace(c[l.STAR],"")};const replaceGTE0=(e,t)=>{a("replaceGTE0",e,t);return e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],"")};const hyphenReplace=e=>(t,r,n,o,s,i,a,A,c,l,u,h)=>{if(isX(n)){r=""}else if(isX(o)){r=`>=${n}.0.0${e?"-0":""}`}else if(isX(s)){r=`>=${n}.${o}.0${e?"-0":""}`}else if(i){r=`>=${r}`}else{r=`>=${r}${e?"-0":""}`}if(isX(c)){A=""}else if(isX(l)){A=`<${+c+1}.0.0-0`}else if(isX(u)){A=`<${c}.${+l+1}.0-0`}else if(h){A=`<=${c}.${l}.${u}-${h}`}else if(e){A=`<${c}.${l}.${+u+1}-0`}else{A=`<=${A}`}return`${r} ${A}`.trim()};const testSet=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch){return true}}}return false}return true}},8088:(e,t,r)=>{const n=r(427);const{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=r(2293);const{safeRe:i,t:a}=r(9523);const A=r(785);const{compareIdentifiers:c}=r(2463);class SemVer{constructor(e,t){t=A(t);if(e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{e=e.version}}else if(typeof e!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`)}if(e.length>o){throw new TypeError(`version is longer than ${o} characters`)}n("SemVer",e,t);this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[a.LOOSE]:i[a.FULL]);if(!r){throw new TypeError(`Invalid Version: ${e}`)}this.raw=e;this.major=+r[1];this.minor=+r[2];this.patch=+r[3];if(this.major>s||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>s||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>s||this.patch<0){throw new TypeError("Invalid patch version")}if(!r[4]){this.prerelease=[]}else{this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0){if(typeof this.prerelease[n]==="number"){this.prerelease[n]++;n=-2}}if(n===-1){if(t===this.prerelease.join(".")&&r===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(e)}}if(t){let n=[t,e];if(r===false){n=[t]}if(c(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1])){this.prerelease=n}}else{this.prerelease=n}}break}default:throw new Error(`invalid increment argument: ${e}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}e.exports=SemVer},8848:(e,t,r)=>{const n=r(5925);const clean=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};e.exports=clean},5098:(e,t,r)=>{const n=r(1898);const o=r(6017);const s=r(4123);const i=r(5522);const a=r(194);const A=r(7520);const cmp=(e,t,r,c)=>{switch(t){case"===":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e===r;case"!==":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e!==r;case"":case"=":case"==":return n(e,r,c);case"!=":return o(e,r,c);case">":return s(e,r,c);case">=":return i(e,r,c);case"<":return a(e,r,c);case"<=":return A(e,r,c);default:throw new TypeError(`Invalid operator: ${t}`)}};e.exports=cmp},3466:(e,t,r)=>{const n=r(8088);const o=r(5925);const{safeRe:s,t:i}=r(9523);const coerce=(e,t)=>{if(e instanceof n){return e}if(typeof e==="number"){e=String(e)}if(typeof e!=="string"){return null}t=t||{};let r=null;if(!t.rtl){r=e.match(t.includePrerelease?s[i.COERCEFULL]:s[i.COERCE])}else{const n=t.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL];let o;while((o=n.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||o.index+o[0].length!==r.index+r[0].length){r=o}n.lastIndex=o.index+o[1].length+o[2].length}n.lastIndex=-1}if(r===null){return null}const a=r[2];const A=r[3]||"0";const c=r[4]||"0";const l=t.includePrerelease&&r[5]?`-${r[5]}`:"";const u=t.includePrerelease&&r[6]?`+${r[6]}`:"";return o(`${a}.${A}.${c}${l}${u}`,t)};e.exports=coerce},2156:(e,t,r)=>{const n=r(8088);const compareBuild=(e,t,r)=>{const o=new n(e,r);const s=new n(t,r);return o.compare(s)||o.compareBuild(s)};e.exports=compareBuild},2804:(e,t,r)=>{const n=r(4309);const compareLoose=(e,t)=>n(e,t,true);e.exports=compareLoose},4309:(e,t,r)=>{const n=r(8088);const compare=(e,t,r)=>new n(e,r).compare(new n(t,r));e.exports=compare},4297:(e,t,r)=>{const n=r(5925);const diff=(e,t)=>{const r=n(e,null,true);const o=n(t,null,true);const s=r.compare(o);if(s===0){return null}const i=s>0;const a=i?r:o;const A=i?o:r;const c=!!a.prerelease.length;const l=!!A.prerelease.length;if(l&&!c){if(!A.patch&&!A.minor){return"major"}if(a.patch){return"patch"}if(a.minor){return"minor"}return"major"}const u=c?"pre":"";if(r.major!==o.major){return u+"major"}if(r.minor!==o.minor){return u+"minor"}if(r.patch!==o.patch){return u+"patch"}return"prerelease"};e.exports=diff},1898:(e,t,r)=>{const n=r(4309);const eq=(e,t,r)=>n(e,t,r)===0;e.exports=eq},4123:(e,t,r)=>{const n=r(4309);const gt=(e,t,r)=>n(e,t,r)>0;e.exports=gt},5522:(e,t,r)=>{const n=r(4309);const gte=(e,t,r)=>n(e,t,r)>=0;e.exports=gte},929:(e,t,r)=>{const n=r(8088);const inc=(e,t,r,o,s)=>{if(typeof r==="string"){s=o;o=r;r=undefined}try{return new n(e instanceof n?e.version:e,r).inc(t,o,s).version}catch(e){return null}};e.exports=inc},194:(e,t,r)=>{const n=r(4309);const lt=(e,t,r)=>n(e,t,r)<0;e.exports=lt},7520:(e,t,r)=>{const n=r(4309);const lte=(e,t,r)=>n(e,t,r)<=0;e.exports=lte},6688:(e,t,r)=>{const n=r(8088);const major=(e,t)=>new n(e,t).major;e.exports=major},8447:(e,t,r)=>{const n=r(8088);const minor=(e,t)=>new n(e,t).minor;e.exports=minor},6017:(e,t,r)=>{const n=r(4309);const neq=(e,t,r)=>n(e,t,r)!==0;e.exports=neq},5925:(e,t,r)=>{const n=r(8088);const parse=(e,t,r=false)=>{if(e instanceof n){return e}try{return new n(e,t)}catch(e){if(!r){return null}throw e}};e.exports=parse},2866:(e,t,r)=>{const n=r(8088);const patch=(e,t)=>new n(e,t).patch;e.exports=patch},4016:(e,t,r)=>{const n=r(5925);const prerelease=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};e.exports=prerelease},6417:(e,t,r)=>{const n=r(4309);const rcompare=(e,t,r)=>n(t,e,r);e.exports=rcompare},8701:(e,t,r)=>{const n=r(2156);const rsort=(e,t)=>e.sort(((e,r)=>n(r,e,t)));e.exports=rsort},6055:(e,t,r)=>{const n=r(9828);const satisfies=(e,t,r)=>{try{t=new n(t,r)}catch(e){return false}return t.test(e)};e.exports=satisfies},1426:(e,t,r)=>{const n=r(2156);const sort=(e,t)=>e.sort(((e,r)=>n(e,r,t)));e.exports=sort},9601:(e,t,r)=>{const n=r(5925);const valid=(e,t)=>{const r=n(e,t);return r?r.version:null};e.exports=valid},1383:(e,t,r)=>{const n=r(9523);const o=r(2293);const s=r(8088);const i=r(2463);const a=r(5925);const A=r(9601);const c=r(8848);const l=r(929);const u=r(4297);const h=r(6688);const d=r(8447);const g=r(2866);const p=r(4016);const E=r(4309);const m=r(6417);const C=r(2804);const I=r(2156);const y=r(1426);const B=r(8701);const Q=r(4123);const b=r(194);const w=r(1898);const S=r(6017);const v=r(5522);const R=r(7520);const k=r(5098);const D=r(3466);const N=r(1532);const T=r(9828);const O=r(6055);const _=r(2706);const M=r(579);const L=r(832);const F=r(4179);const U=r(2098);const P=r(420);const G=r(9380);const Y=r(3323);const V=r(7008);const W=r(5297);const J=r(7863);e.exports={parse:a,valid:A,clean:c,inc:l,diff:u,major:h,minor:d,patch:g,prerelease:p,compare:E,rcompare:m,compareLoose:C,compareBuild:I,sort:y,rsort:B,gt:Q,lt:b,eq:w,neq:S,gte:v,lte:R,cmp:k,coerce:D,Comparator:N,Range:T,satisfies:O,toComparators:_,maxSatisfying:M,minSatisfying:L,minVersion:F,validRange:U,outside:P,gtr:G,ltr:Y,intersects:V,simplifyRange:W,subset:J,SemVer:s,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},2293:e=>{const t="2.0.0";const r=256;const n=Number.MAX_SAFE_INTEGER||9007199254740991;const o=16;const s=r-6;const i=["major","premajor","minor","preminor","patch","prepatch","prerelease"];e.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:i,SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},427:e=>{const t=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},2463:e=>{const t=/^[0-9]+$/;const compareIdentifiers=(e,r)=>{const n=t.test(e);const o=t.test(r);if(n&&o){e=+e;r=+r}return e===r?0:n&&!o?-1:o&&!n?1:ecompareIdentifiers(t,e);e.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},5339:e=>{class LRUCache{constructor(){this.max=1e3;this.map=new Map}get(e){const t=this.map.get(e);if(t===undefined){return undefined}else{this.map.delete(e);this.map.set(e,t);return t}}delete(e){return this.map.delete(e)}set(e,t){const r=this.delete(e);if(!r&&t!==undefined){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}e.exports=LRUCache},785:e=>{const t=Object.freeze({loose:true});const r=Object.freeze({});const parseOptions=e=>{if(!e){return r}if(typeof e!=="object"){return t}return e};e.exports=parseOptions},9523:(e,t,r)=>{const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=r(2293);const i=r(427);t=e.exports={};const a=t.re=[];const A=t.safeRe=[];const c=t.src=[];const l=t.t={};let u=0;const h="[a-zA-Z0-9-]";const d=[["\\s",1],["\\d",s],[h,o]];const makeSafeRegex=e=>{for(const[t,r]of d){e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`)}return e};const createToken=(e,t,r)=>{const n=makeSafeRegex(t);const o=u++;i(e,o,t);l[e]=o;c[o]=t;a[o]=new RegExp(t,r?"g":undefined);A[o]=new RegExp(n,r?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`);createToken("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${h}+`);createToken("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`);createToken("FULL",`^${c[l.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`);createToken("LOOSE",`^${c[l.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${n}})`+`(?:\\.(\\d{1,${n}}))?`+`(?:\\.(\\d{1,${n}}))?`);createToken("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",c[l.COERCE],true);createToken("COERCERTLFULL",c[l.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,true);t.tildeTrimReplace="$1~";createToken("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,true);t.caretTrimReplace="$1^";createToken("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,true);t.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9380:(e,t,r)=>{const n=r(420);const gtr=(e,t,r)=>n(e,t,">",r);e.exports=gtr},7008:(e,t,r)=>{const n=r(9828);const intersects=(e,t,r)=>{e=new n(e,r);t=new n(t,r);return e.intersects(t,r)};e.exports=intersects},3323:(e,t,r)=>{const n=r(420);const ltr=(e,t,r)=>n(e,t,"<",r);e.exports=ltr},579:(e,t,r)=>{const n=r(8088);const o=r(9828);const maxSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===-1){s=e;i=new n(s,r)}}}));return s};e.exports=maxSatisfying},832:(e,t,r)=>{const n=r(8088);const o=r(9828);const minSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===1){s=e;i=new n(s,r)}}}));return s};e.exports=minSatisfying},4179:(e,t,r)=>{const n=r(8088);const o=r(9828);const s=r(4123);const minVersion=(e,t)=>{e=new o(e,t);let r=new n("0.0.0");if(e.test(r)){return r}r=new n("0.0.0-0");if(e.test(r)){return r}r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":if(t.prerelease.length===0){t.patch++}else{t.prerelease.push(0)}t.raw=t.format();case"":case">=":if(!i||s(t,i)){i=t}break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}));if(i&&(!r||s(r,i))){r=i}}if(r&&e.test(r)){return r}return null};e.exports=minVersion},420:(e,t,r)=>{const n=r(8088);const o=r(1532);const{ANY:s}=o;const i=r(9828);const a=r(6055);const A=r(4123);const c=r(194);const l=r(7520);const u=r(5522);const outside=(e,t,r,h)=>{e=new n(e,h);t=new i(t,h);let d,g,p,E,m;switch(r){case">":d=A;g=l;p=c;E=">";m=">=";break;case"<":d=c;g=u;p=A;E="<";m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(e,t,h)){return false}for(let r=0;r{if(e.semver===s){e=new o(">=0.0.0")}i=i||e;a=a||e;if(d(e.semver,i.semver,h)){i=e}else if(p(e.semver,a.semver,h)){a=e}}));if(i.operator===E||i.operator===m){return false}if((!a.operator||a.operator===E)&&g(e,a.semver)){return false}else if(a.operator===m&&p(e,a.semver)){return false}}return true};e.exports=outside},5297:(e,t,r)=>{const n=r(6055);const o=r(4309);e.exports=(e,t,r)=>{const s=[];let i=null;let a=null;const A=e.sort(((e,t)=>o(e,t,r)));for(const e of A){const o=n(e,t,r);if(o){a=e;if(!i){i=e}}else{if(a){s.push([i,a])}a=null;i=null}}if(i){s.push([i,null])}const c=[];for(const[e,t]of s){if(e===t){c.push(e)}else if(!t&&e===A[0]){c.push("*")}else if(!t){c.push(`>=${e}`)}else if(e===A[0]){c.push(`<=${t}`)}else{c.push(`${e} - ${t}`)}}const l=c.join(" || ");const u=typeof t.raw==="string"?t.raw:String(t);return l.length{const n=r(9828);const o=r(1532);const{ANY:s}=o;const i=r(6055);const a=r(4309);const subset=(e,t,r={})=>{if(e===t){return true}e=new n(e,r);t=new n(t,r);let o=false;e:for(const n of e.set){for(const e of t.set){const t=simpleSubset(n,e,r);o=o||t!==null;if(t){continue e}}if(o){return false}}return true};const A=[new o(">=0.0.0-0")];const c=[new o(">=0.0.0")];const simpleSubset=(e,t,r)=>{if(e===t){return true}if(e.length===1&&e[0].semver===s){if(t.length===1&&t[0].semver===s){return true}else if(r.includePrerelease){e=A}else{e=c}}if(t.length===1&&t[0].semver===s){if(r.includePrerelease){return true}else{t=c}}const n=new Set;let o,l;for(const t of e){if(t.operator===">"||t.operator===">="){o=higherGT(o,t,r)}else if(t.operator==="<"||t.operator==="<="){l=lowerLT(l,t,r)}else{n.add(t.semver)}}if(n.size>1){return null}let u;if(o&&l){u=a(o.semver,l.semver,r);if(u>0){return null}else if(u===0&&(o.operator!==">="||l.operator!=="<=")){return null}}for(const e of n){if(o&&!i(e,String(o),r)){return null}if(l&&!i(e,String(l),r)){return null}for(const n of t){if(!i(e,String(n),r)){return false}}return true}let h,d;let g,p;let E=l&&!r.includePrerelease&&l.semver.prerelease.length?l.semver:false;let m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:false;if(E&&E.prerelease.length===1&&l.operator==="<"&&E.prerelease[0]===0){E=false}for(const e of t){p=p||e.operator===">"||e.operator===">=";g=g||e.operator==="<"||e.operator==="<=";if(o){if(m){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===m.major&&e.semver.minor===m.minor&&e.semver.patch===m.patch){m=false}}if(e.operator===">"||e.operator===">="){h=higherGT(o,e,r);if(h===e&&h!==o){return false}}else if(o.operator===">="&&!i(o.semver,String(e),r)){return false}}if(l){if(E){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===E.major&&e.semver.minor===E.minor&&e.semver.patch===E.patch){E=false}}if(e.operator==="<"||e.operator==="<="){d=lowerLT(l,e,r);if(d===e&&d!==l){return false}}else if(l.operator==="<="&&!i(l.semver,String(e),r)){return false}}if(!e.operator&&(l||o)&&u!==0){return false}}if(o&&g&&!l&&u!==0){return false}if(l&&p&&!o&&u!==0){return false}if(m||E){return false}return true};const higherGT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e};const lowerLT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};e.exports=subset},2706:(e,t,r)=>{const n=r(9828);const toComparators=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")));e.exports=toComparators},2098:(e,t,r)=>{const n=r(9828);const validRange=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}};e.exports=validRange},1453:(e,t,r)=>{var n=r(1529);e.exports=Bitfield;function Bitfield(e){if(!(this instanceof Bitfield))return new Bitfield(e);if(!e)e={};if(Buffer.isBuffer(e))e={buffer:e};this.pageOffset=e.pageOffset||0;this.pageSize=e.pageSize||1024;this.pages=e.pages||n(this.pageSize);this.byteLength=this.pages.length*this.pageSize;this.length=8*this.byteLength;if(!powerOfTwo(this.pageSize))throw new Error("The page size should be a power of two");this._trackUpdates=!!e.trackUpdates;this._pageMask=this.pageSize-1;if(e.buffer){for(var t=0;t>t)};Bitfield.prototype.getByte=function(e){var t=e&this._pageMask;var r=(e-t)/this.pageSize;var n=this.pages.get(r,true);return n?n.buffer[t+this.pageOffset]:0};Bitfield.prototype.set=function(e,t){var r=e&7;var n=(e-r)/8;var o=this.getByte(n);return this.setByte(n,t?o|128>>r:o&(255^128>>r))};Bitfield.prototype.toBuffer=function(){var e=alloc(this.pages.length*this.pageSize);for(var t=0;t=this.byteLength){this.byteLength=e+1;this.length=this.byteLength*8}if(this._trackUpdates)this.pages.updated(o);return true};function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function powerOfTwo(e){return!(e&e-1)}},4841:(e,t,r)=>{"use strict";var n=r(1867).Buffer;var o=n.isEncoding||function(e){e=""+e;switch(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 true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){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=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var n=t.length-1;if(n=0){if(o>0)e.lastNeed=o-1;return o}if(--n=0){if(o>0)e.lastNeed=o-2;return o}if(--n=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},9318:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6224);const s=r(1621);const{env:i}=process;let a;if(s("no-color")||s("no-colors")||s("color=false")||s("color=never")){a=0}else if(s("color")||s("colors")||s("color=true")||s("color=always")){a=1}if("FORCE_COLOR"in i){if(i.FORCE_COLOR==="true"){a=1}else if(i.FORCE_COLOR==="false"){a=0}else{a=i.FORCE_COLOR.length===0?1:Math.min(parseInt(i.FORCE_COLOR,10),3)}}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e,t){if(a===0){return 0}if(s("color=16m")||s("color=full")||s("color=truecolor")){return 3}if(s("color=256")){return 2}if(e&&!t&&a===undefined){return 0}const r=a||0;if(i.TERM==="dumb"){return r}if(process.platform==="win32"){const e=n.release().split(".");if(Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in i){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||i.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in i){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0}if(i.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(i.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)){return 1}if("COLORTERM"in i){return 1}return r}function getSupportLevel(e){const t=supportsColor(e,e&&e.isTTY);return translateLevel(t)}e.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(true,o.isatty(1))),stderr:translateLevel(supportsColor(true,o.isatty(2)))}},7882:(e,t,r)=>{var n=r(3837);var o=r(336);var s=r(8860);var i=r(1642).Writable;var a=r(1642).PassThrough;var noop=function(){};var overflow=function(e){e&=511;return e&&512-e};var emptyStream=function(e,t){var r=new Source(e,t);r.end();return r};var mixinPax=function(e,t){if(t.path)e.name=t.path;if(t.linkpath)e.linkname=t.linkpath;if(t.size)e.size=parseInt(t.size,10);e.pax=t;return e};var Source=function(e,t){this._parent=e;this.offset=t;a.call(this,{autoDestroy:false})};n.inherits(Source,a);Source.prototype.destroy=function(e){this._parent.destroy(e)};var Extract=function(e){if(!(this instanceof Extract))return new Extract(e);i.call(this,e);e=e||{};this._offset=0;this._buffer=o();this._missing=0;this._partial=false;this._onparse=noop;this._header=null;this._stream=null;this._overflow=null;this._cb=null;this._locked=false;this._destroyed=false;this._pax=null;this._paxGlobal=null;this._gnuLongPath=null;this._gnuLongLinkPath=null;var t=this;var r=t._buffer;var oncontinue=function(){t._continue()};var onunlock=function(e){t._locked=false;if(e)return t.destroy(e);if(!t._stream)oncontinue()};var onstreamend=function(){t._stream=null;var e=overflow(t._header.size);if(e)t._parse(e,ondrain);else t._parse(512,onheader);if(!t._locked)oncontinue()};var ondrain=function(){t._buffer.consume(overflow(t._header.size));t._parse(512,onheader);oncontinue()};var onpaxglobalheader=function(){var e=t._header.size;t._paxGlobal=s.decodePax(r.slice(0,e));r.consume(e);onstreamend()};var onpaxheader=function(){var e=t._header.size;t._pax=s.decodePax(r.slice(0,e));if(t._paxGlobal)t._pax=Object.assign({},t._paxGlobal,t._pax);r.consume(e);onstreamend()};var ongnulongpath=function(){var n=t._header.size;this._gnuLongPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var ongnulonglinkpath=function(){var n=t._header.size;this._gnuLongLinkPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var onheader=function(){var n=t._offset;var o;try{o=t._header=s.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(e){t.emit("error",e)}r.consume(512);if(!o){t._parse(512,onheader);oncontinue();return}if(o.type==="gnu-long-path"){t._parse(o.size,ongnulongpath);oncontinue();return}if(o.type==="gnu-long-link-path"){t._parse(o.size,ongnulonglinkpath);oncontinue();return}if(o.type==="pax-global-header"){t._parse(o.size,onpaxglobalheader);oncontinue();return}if(o.type==="pax-header"){t._parse(o.size,onpaxheader);oncontinue();return}if(t._gnuLongPath){o.name=t._gnuLongPath;t._gnuLongPath=null}if(t._gnuLongLinkPath){o.linkname=t._gnuLongLinkPath;t._gnuLongLinkPath=null}if(t._pax){t._header=o=mixinPax(o,t._pax);t._pax=null}t._locked=true;if(!o.size||o.type==="directory"){t._parse(512,onheader);t.emit("entry",o,emptyStream(t,n),onunlock);return}t._stream=new Source(t,n);t.emit("entry",o,t._stream,onunlock);t._parse(o.size,onstreamend);oncontinue()};this._onheader=onheader;this._parse(512,onheader)};n.inherits(Extract,i);Extract.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream)this._stream.emit("close")};Extract.prototype._parse=function(e,t){if(this._destroyed)return;this._offset+=e;this._missing=e;if(t===this._onheader)this._partial=false;this._onparse=t};Extract.prototype._continue=function(){if(this._destroyed)return;var e=this._cb;this._cb=noop;if(this._overflow)this._write(this._overflow,undefined,e);else e()};Extract.prototype._write=function(e,t,r){if(this._destroyed)return;var n=this._stream;var o=this._buffer;var s=this._missing;if(e.length)this._partial=true;if(e.lengths){i=e.slice(s);e=e.slice(0,s)}if(n)n.end(e);else o.append(e);this._overflow=i;this._onparse()};Extract.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};e.exports=Extract},8860:(e,t)=>{var r=Buffer.alloc;var n="0000000000000000000";var o="7777777777777777777";var s="0".charCodeAt(0);var i=Buffer.from("ustar\0","binary");var a=Buffer.from("00","binary");var A=Buffer.from("ustar ","binary");var c=Buffer.from(" \0","binary");var l=parseInt("7777",8);var u=257;var h=263;var clamp=function(e,t,r){if(typeof e!=="number")return r;e=~~e;if(e>=t)return t;if(e>=0)return e;e+=t;if(e>=0)return e;return 0};var toType=function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null};var toTypeflag=function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0};var indexOf=function(e,t,r,n){for(;rt)return o.slice(0,t)+" ";else return n.slice(0,t-e.length)+e+" "};function parse256(e){var t;if(e[0]===128)t=true;else if(e[0]===255)t=false;else return null;var r=[];for(var n=e.length-1;n>0;n--){var o=e[n];if(t)r.push(o);else r.push(255-o)}var s=0;var i=r.length;for(n=0;n=Math.pow(10,r))r++;return t+r+e};t.decodeLongPath=function(e,t){return decodeStr(e,0,e.length,t)};t.encodePax=function(e){var t="";if(e.name)t+=addLength(" path="+e.name+"\n");if(e.linkname)t+=addLength(" linkpath="+e.linkname+"\n");var r=e.pax;if(r){for(var n in r){t+=addLength(" "+n+"="+r[n]+"\n")}}return Buffer.from(t)};t.decodePax=function(e){var t={};while(e.length){var r=0;while(r100){var A=n.indexOf("/");if(A===-1)return null;o+=o?"/"+n.slice(0,A):n.slice(0,A);n=n.slice(A+1)}if(Buffer.byteLength(n)>100||Buffer.byteLength(o)>155)return null;if(e.linkname&&Buffer.byteLength(e.linkname)>100)return null;t.write(n);t.write(encodeOct(e.mode&l,6),100);t.write(encodeOct(e.uid,6),108);t.write(encodeOct(e.gid,6),116);t.write(encodeOct(e.size,11),124);t.write(encodeOct(e.mtime.getTime()/1e3|0,11),136);t[156]=s+toTypeflag(e.type);if(e.linkname)t.write(e.linkname,157);i.copy(t,u);a.copy(t,h);if(e.uname)t.write(e.uname,265);if(e.gname)t.write(e.gname,297);t.write(encodeOct(e.devmajor||0,6),329);t.write(encodeOct(e.devminor||0,6),337);if(o)t.write(o,345);t.write(encodeOct(cksum(t),6),148);return t};t.decode=function(e,t,r){var n=e[156]===0?0:e[156]-s;var o=decodeStr(e,0,100,t);var a=decodeOct(e,100,8);var l=decodeOct(e,108,8);var d=decodeOct(e,116,8);var g=decodeOct(e,124,12);var p=decodeOct(e,136,12);var E=toType(n);var m=e[157]===0?null:decodeStr(e,157,100,t);var C=decodeStr(e,265,32);var I=decodeStr(e,297,32);var y=decodeOct(e,329,8);var B=decodeOct(e,337,8);var Q=cksum(e);if(Q===8*32)return null;if(Q!==decodeOct(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(i.compare(e,u,u+6)===0){if(e[345])o=decodeStr(e,345,155,t)+"/"+o}else if(A.compare(e,u,u+6)===0&&c.compare(e,h,h+2)===0){}else{if(!r){throw new Error("Invalid tar header: unknown format.")}}if(n===0&&o&&o[o.length-1]==="/")n=5;return{name:o,mode:a,uid:l,gid:d,size:g,mtime:new Date(1e3*p),type:E,linkname:m,uname:C,gname:I,devmajor:y,devminor:B}}},2283:(e,t,r)=>{t.extract=r(7882);t.pack=r(4930)},4930:(e,t,r)=>{var n=r(3186);var o=r(1205);var s=r(4124);var i=Buffer.alloc;var a=r(1642).Readable;var A=r(1642).Writable;var c=r(1576).StringDecoder;var l=r(8860);var u=parseInt("755",8);var h=parseInt("644",8);var d=i(1024);var noop=function(){};var overflow=function(e,t){t&=511;if(t)e.push(d.slice(0,512-t))};function modeToType(e){switch(e&n.S_IFMT){case n.S_IFBLK:return"block-device";case n.S_IFCHR:return"character-device";case n.S_IFDIR:return"directory";case n.S_IFIFO:return"fifo";case n.S_IFLNK:return"symlink"}return"file"}var Sink=function(e){A.call(this);this.written=0;this._to=e;this._destroyed=false};s(Sink,A);Sink.prototype._write=function(e,t,r){this.written+=e.length;if(this._to.push(e))return r();this._to._drain=r};Sink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var LinkSink=function(){A.call(this);this.linkname="";this._decoder=new c("utf-8");this._destroyed=false};s(LinkSink,A);LinkSink.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e);r()};LinkSink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Void=function(){A.call(this);this._destroyed=false};s(Void,A);Void.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Void.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Pack=function(e){if(!(this instanceof Pack))return new Pack(e);a.call(this,e);this._drain=noop;this._finalized=false;this._finalizing=false;this._destroyed=false;this._stream=null};s(Pack,a);Pack.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(this._finalized||this._destroyed)return;if(typeof t==="function"){r=t;t=null}if(!r)r=noop;var n=this;if(!e.size||e.type==="symlink")e.size=0;if(!e.type)e.type=modeToType(e.mode);if(!e.mode)e.mode=e.type==="directory"?u:h;if(!e.uid)e.uid=0;if(!e.gid)e.gid=0;if(!e.mtime)e.mtime=new Date;if(typeof t==="string")t=Buffer.from(t);if(Buffer.isBuffer(t)){e.size=t.length;this._encode(e);var s=this.push(t);overflow(n,e.size);if(s)process.nextTick(r);else this._drain=r;return new Void}if(e.type==="symlink"&&!e.linkname){var i=new LinkSink;o(i,(function(t){if(t){n.destroy();return r(t)}e.linkname=i.linkname;n._encode(e);r()}));return i}this._encode(e);if(e.type!=="file"&&e.type!=="contiguous-file"){process.nextTick(r);return new Void}var a=new Sink(this);this._stream=a;o(a,(function(t){n._stream=null;if(t){n.destroy();return r(t)}if(a.written!==e.size){n.destroy();return r(new Error("size mismatch"))}overflow(n,e.size);if(n._finalizing)n.finalize();r()}));return a};Pack.prototype.finalize=function(){if(this._stream){this._finalizing=true;return}if(this._finalized)return;this._finalized=true;this.push(d);this.push(null)};Pack.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream&&this._stream.destroy)this._stream.destroy()};Pack.prototype._encode=function(e){if(!e.pax){var t=l.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Pack.prototype._encodePax=function(e){var t=l.encodePax({name:e.name,linkname:e.linkname,pax:e.pax});var r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(l.encode(r));this.push(t);overflow(this,t.length);r.size=e.size;r.type=e.type;this.push(l.encode(r))};Pack.prototype._read=function(e){var t=this._drain;this._drain=noop;t()};e.exports=Pack},8517:(e,t,r)=>{ /*! * Tmp * diff --git a/src/index.ts b/src/index.ts index 849855a..8d62824 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,8 @@ async function runCommand(command: string, connectionString: string): Promise Date: Wed, 1 Oct 2025 13:27:16 -0600 Subject: [PATCH 2/5] Testing token permission. --- .github/workflows/publish.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index b17e665..24f1583 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -1,7 +1,9 @@ name: publish on: push: - branches: [master, main] + branches: [master, main, enginfs-545300/move-actions] +permissions: + contents: write jobs: publish: runs-on: ubuntu-22.04 From 0ad7b2f670531ba25a86da4fcb0a30f5425327c8 Mon Sep 17 00:00:00 2001 From: Lucas Parreira Date: Wed, 1 Oct 2025 13:31:02 -0600 Subject: [PATCH 3/5] Removing test log. --- src/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 8d62824..849855a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,8 +18,6 @@ async function runCommand(command: string, connectionString: string): Promise Date: Wed, 1 Oct 2025 19:31:48 +0000 Subject: [PATCH 4/5] Commit from GitHub Actions (publish) Signed-off-by: NeoBot --- build/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/index.js b/build/index.js index 3efe906..10c21a4 100644 --- a/build/index.js +++ b/build/index.js @@ -1,4 +1,4 @@ -(()=>{var __webpack_modules__={924:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var o=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function verb(e){return function(t){return step([e,t])}}function step(i){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,o&&(s=i[0]&2?o["return"]:i[0]?o["throw"]||((s=o["return"])&&s.call(o),0):o.next)&&!(s=s.call(o,i[1])).done)return s;if(o=0,s)i=[i[0]&2,s.value];switch(i[0]){case 0:case 1:s=i;break;case 4:r.label++;return{value:i[1],done:false};case 5:r.label++;o=i[1];i=[0];continue;case 7:i=r.ops.pop();r.trys.pop();continue;default:if(!(s=r.trys,s=s.length>0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0){e+=" ";let t=true;for(const r in this.properties){if(this.properties.hasOwnProperty(r)){const n=this.properties[r];if(n){if(t){t=false}else{e+=","}e+=`${r}=${escapeProperty(n)}`}}}}e+=`${A}${escapeData(this.message)}`;return e}}function escapeData(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},2186:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.getIDToken=t.getState=t.saveState=t.group=t.endGroup=t.startGroup=t.info=t.notice=t.warning=t.error=t.debug=t.isDebug=t.setFailed=t.setCommandEcho=t.setOutput=t.getBooleanInput=t.getMultilineInput=t.getInput=t.addPath=t.setSecret=t.exportVariable=t.ExitCode=void 0;const a=r(7351);const A=r(717);const c=r(6321);const l=s(r(2037));const u=s(r(1017));const h=r(8041);var d;(function(e){e[e["Success"]=0]="Success";e[e["Failure"]=1]="Failure"})(d=t.ExitCode||(t.ExitCode={}));function exportVariable(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env["GITHUB_ENV"]||"";if(n){return A.issueFileCommand("ENV",A.prepareKeyValueMessage(e,t))}a.issueCommand("set-env",{name:e},r)}t.exportVariable=exportVariable;function setSecret(e){a.issueCommand("add-mask",{},e)}t.setSecret=setSecret;function addPath(e){const t=process.env["GITHUB_PATH"]||"";if(t){A.issueFileCommand("PATH",e)}else{a.issueCommand("add-path",{},e)}process.env["PATH"]=`${e}${u.delimiter}${process.env["PATH"]}`}t.addPath=addPath;function getInput(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r){throw new Error(`Input required and not supplied: ${e}`)}if(t&&t.trimWhitespace===false){return r}return r.trim()}t.getInput=getInput;function getMultilineInput(e,t){const r=getInput(e,t).split("\n").filter((e=>e!==""));if(t&&t.trimWhitespace===false){return r}return r.map((e=>e.trim()))}t.getMultilineInput=getMultilineInput;function getBooleanInput(e,t){const r=["true","True","TRUE"];const n=["false","False","FALSE"];const o=getInput(e,t);if(r.includes(o))return true;if(n.includes(o))return false;throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${e}\n`+`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}t.getBooleanInput=getBooleanInput;function setOutput(e,t){const r=process.env["GITHUB_OUTPUT"]||"";if(r){return A.issueFileCommand("OUTPUT",A.prepareKeyValueMessage(e,t))}process.stdout.write(l.EOL);a.issueCommand("set-output",{name:e},c.toCommandValue(t))}t.setOutput=setOutput;function setCommandEcho(e){a.issue("echo",e?"on":"off")}t.setCommandEcho=setCommandEcho;function setFailed(e){process.exitCode=d.Failure;error(e)}t.setFailed=setFailed;function isDebug(){return process.env["RUNNER_DEBUG"]==="1"}t.isDebug=isDebug;function debug(e){a.issueCommand("debug",{},e)}t.debug=debug;function error(e,t={}){a.issueCommand("error",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.error=error;function warning(e,t={}){a.issueCommand("warning",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.warning=warning;function notice(e,t={}){a.issueCommand("notice",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.notice=notice;function info(e){process.stdout.write(e+l.EOL)}t.info=info;function startGroup(e){a.issue("group",e)}t.startGroup=startGroup;function endGroup(){a.issue("endgroup")}t.endGroup=endGroup;function group(e,t){return i(this,void 0,void 0,(function*(){startGroup(e);let r;try{r=yield t()}finally{endGroup()}return r}))}t.group=group;function saveState(e,t){const r=process.env["GITHUB_STATE"]||"";if(r){return A.issueFileCommand("STATE",A.prepareKeyValueMessage(e,t))}a.issueCommand("save-state",{name:e},c.toCommandValue(t))}t.saveState=saveState;function getState(e){return process.env[`STATE_${e}`]||""}t.getState=getState;function getIDToken(e){return i(this,void 0,void 0,(function*(){return yield h.OidcClient.getIDToken(e)}))}t.getIDToken=getIDToken;var g=r(1327);Object.defineProperty(t,"summary",{enumerable:true,get:function(){return g.summary}});var p=r(1327);Object.defineProperty(t,"markdownSummary",{enumerable:true,get:function(){return p.markdownSummary}});var E=r(2981);Object.defineProperty(t,"toPosixPath",{enumerable:true,get:function(){return E.toPosixPath}});Object.defineProperty(t,"toWin32Path",{enumerable:true,get:function(){return E.toWin32Path}});Object.defineProperty(t,"toPlatformPath",{enumerable:true,get:function(){return E.toPlatformPath}})},717:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.prepareKeyValueMessage=t.issueFileCommand=void 0;const i=s(r(7147));const a=s(r(2037));const A=r(5840);const c=r(6321);function issueFileCommand(e,t){const r=process.env[`GITHUB_${e}`];if(!r){throw new Error(`Unable to find environment variable for file command ${e}`)}if(!i.existsSync(r)){throw new Error(`Missing file at path: ${r}`)}i.appendFileSync(r,`${c.toCommandValue(t)}${a.EOL}`,{encoding:"utf8"})}t.issueFileCommand=issueFileCommand;function prepareKeyValueMessage(e,t){const r=`ghadelimiter_${A.v4()}`;const n=c.toCommandValue(t);if(e.includes(r)){throw new Error(`Unexpected input: name should not contain the delimiter "${r}"`)}if(n.includes(r)){throw new Error(`Unexpected input: value should not contain the delimiter "${r}"`)}return`${e}<<${r}${a.EOL}${n}${a.EOL}${r}`}t.prepareKeyValueMessage=prepareKeyValueMessage},8041:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.OidcClient=void 0;const o=r(6255);const s=r(5526);const i=r(2186);class OidcClient{static createHttpClient(e=true,t=10){const r={allowRetries:e,maxRetries:t};return new o.HttpClient("actions/oidc-client",[new s.BearerCredentialHandler(OidcClient.getRequestToken())],r)}static getRequestToken(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable")}return e}static getIDTokenUrl(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable")}return e}static getCall(e){var t;return n(this,void 0,void 0,(function*(){const r=OidcClient.createHttpClient();const n=yield r.getJson(e).catch((e=>{throw new Error(`Failed to get ID Token. \n \n Error Code : ${e.statusCode}\n \n Error Message: ${e.message}`)}));const o=(t=n.result)===null||t===void 0?void 0:t.value;if(!o){throw new Error("Response json body do not have ID Token field")}return o}))}static getIDToken(e){return n(this,void 0,void 0,(function*(){try{let t=OidcClient.getIDTokenUrl();if(e){const r=encodeURIComponent(e);t=`${t}&audience=${r}`}i.debug(`ID token url is ${t}`);const r=yield OidcClient.getCall(t);i.setSecret(r);return r}catch(e){throw new Error(`Error message: ${e.message}`)}}))}}t.OidcClient=OidcClient},2981:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const i=s(r(1017));function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,i.sep)}t.toPlatformPath=toPlatformPath},1327:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.summary=t.markdownSummary=t.SUMMARY_DOCS_URL=t.SUMMARY_ENV_VAR=void 0;const o=r(2037);const s=r(7147);const{access:i,appendFile:a,writeFile:A}=s.promises;t.SUMMARY_ENV_VAR="GITHUB_STEP_SUMMARY";t.SUMMARY_DOCS_URL="https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";class Summary{constructor(){this._buffer=""}filePath(){return n(this,void 0,void 0,(function*(){if(this._filePath){return this._filePath}const e=process.env[t.SUMMARY_ENV_VAR];if(!e){throw new Error(`Unable to find environment variable for $${t.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`)}try{yield i(e,s.constants.R_OK|s.constants.W_OK)}catch(t){throw new Error(`Unable to access summary file: '${e}'. Check if the file has correct read/write permissions.`)}this._filePath=e;return this._filePath}))}wrap(e,t,r={}){const n=Object.entries(r).map((([e,t])=>` ${e}="${t}"`)).join("");if(!t){return`<${e}${n}>`}return`<${e}${n}>${t}`}write(e){return n(this,void 0,void 0,(function*(){const t=!!(e===null||e===void 0?void 0:e.overwrite);const r=yield this.filePath();const n=t?A:a;yield n(r,this._buffer,{encoding:"utf8"});return this.emptyBuffer()}))}clear(){return n(this,void 0,void 0,(function*(){return this.emptyBuffer().write({overwrite:true})}))}stringify(){return this._buffer}isEmptyBuffer(){return this._buffer.length===0}emptyBuffer(){this._buffer="";return this}addRaw(e,t=false){this._buffer+=e;return t?this.addEOL():this}addEOL(){return this.addRaw(o.EOL)}addCodeBlock(e,t){const r=Object.assign({},t&&{lang:t});const n=this.wrap("pre",this.wrap("code",e),r);return this.addRaw(n).addEOL()}addList(e,t=false){const r=t?"ol":"ul";const n=e.map((e=>this.wrap("li",e))).join("");const o=this.wrap(r,n);return this.addRaw(o).addEOL()}addTable(e){const t=e.map((e=>{const t=e.map((e=>{if(typeof e==="string"){return this.wrap("td",e)}const{header:t,data:r,colspan:n,rowspan:o}=e;const s=t?"th":"td";const i=Object.assign(Object.assign({},n&&{colspan:n}),o&&{rowspan:o});return this.wrap(s,r,i)})).join("");return this.wrap("tr",t)})).join("");const r=this.wrap("table",t);return this.addRaw(r).addEOL()}addDetails(e,t){const r=this.wrap("details",this.wrap("summary",e)+t);return this.addRaw(r).addEOL()}addImage(e,t,r){const{width:n,height:o}=r||{};const s=Object.assign(Object.assign({},n&&{width:n}),o&&{height:o});const i=this.wrap("img",null,Object.assign({src:e,alt:t},s));return this.addRaw(i).addEOL()}addHeading(e,t){const r=`h${t}`;const n=["h1","h2","h3","h4","h5","h6"].includes(r)?r:"h1";const o=this.wrap(n,e);return this.addRaw(o).addEOL()}addSeparator(){const e=this.wrap("hr",null);return this.addRaw(e).addEOL()}addBreak(){const e=this.wrap("br",null);return this.addRaw(e).addEOL()}addQuote(e,t){const r=Object.assign({},t&&{cite:t});const n=this.wrap("blockquote",e,r);return this.addRaw(n).addEOL()}addLink(e,t){const r=this.wrap("a",e,{href:t});return this.addRaw(r).addEOL()}}const c=new Summary;t.markdownSummary=c;t.summary=c},6321:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.toCommandProperties=t.toCommandValue=void 0;function toCommandValue(e){if(e===null||e===undefined){return""}else if(typeof e==="string"||e instanceof String){return e}return JSON.stringify(e)}t.toCommandValue=toCommandValue;function toCommandProperties(e){if(!Object.keys(e).length){return{}}return{title:e.title,file:e.file,line:e.startLine,endLine:e.endLine,col:e.startColumn,endColumn:e.endColumn}}t.toCommandProperties=toCommandProperties},5526:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.PersonalAccessTokenCredentialHandler=t.BearerCredentialHandler=t.BasicCredentialHandler=void 0;class BasicCredentialHandler{constructor(e,t){this.username=e;this.password=t}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BasicCredentialHandler=BasicCredentialHandler;class BearerCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Bearer ${this.token}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BearerCredentialHandler=BearerCredentialHandler;class PersonalAccessTokenCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.PersonalAccessTokenCredentialHandler=PersonalAccessTokenCredentialHandler},6255:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable)){o={enumerable:true,get:function(){return t[r]}}}Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.HttpClient=t.isHttps=t.HttpClientResponse=t.HttpClientError=t.getProxyUrl=t.MediaTypes=t.Headers=t.HttpCodes=void 0;const a=s(r(3685));const A=s(r(5687));const c=s(r(9835));const l=s(r(4294));const u=r(1773);var h;(function(e){e[e["OK"]=200]="OK";e[e["MultipleChoices"]=300]="MultipleChoices";e[e["MovedPermanently"]=301]="MovedPermanently";e[e["ResourceMoved"]=302]="ResourceMoved";e[e["SeeOther"]=303]="SeeOther";e[e["NotModified"]=304]="NotModified";e[e["UseProxy"]=305]="UseProxy";e[e["SwitchProxy"]=306]="SwitchProxy";e[e["TemporaryRedirect"]=307]="TemporaryRedirect";e[e["PermanentRedirect"]=308]="PermanentRedirect";e[e["BadRequest"]=400]="BadRequest";e[e["Unauthorized"]=401]="Unauthorized";e[e["PaymentRequired"]=402]="PaymentRequired";e[e["Forbidden"]=403]="Forbidden";e[e["NotFound"]=404]="NotFound";e[e["MethodNotAllowed"]=405]="MethodNotAllowed";e[e["NotAcceptable"]=406]="NotAcceptable";e[e["ProxyAuthenticationRequired"]=407]="ProxyAuthenticationRequired";e[e["RequestTimeout"]=408]="RequestTimeout";e[e["Conflict"]=409]="Conflict";e[e["Gone"]=410]="Gone";e[e["TooManyRequests"]=429]="TooManyRequests";e[e["InternalServerError"]=500]="InternalServerError";e[e["NotImplemented"]=501]="NotImplemented";e[e["BadGateway"]=502]="BadGateway";e[e["ServiceUnavailable"]=503]="ServiceUnavailable";e[e["GatewayTimeout"]=504]="GatewayTimeout"})(h||(t.HttpCodes=h={}));var d;(function(e){e["Accept"]="accept";e["ContentType"]="content-type"})(d||(t.Headers=d={}));var g;(function(e){e["ApplicationJson"]="application/json"})(g||(t.MediaTypes=g={}));function getProxyUrl(e){const t=c.getProxyUrl(new URL(e));return t?t.href:""}t.getProxyUrl=getProxyUrl;const p=[h.MovedPermanently,h.ResourceMoved,h.SeeOther,h.TemporaryRedirect,h.PermanentRedirect];const E=[h.BadGateway,h.ServiceUnavailable,h.GatewayTimeout];const m=["OPTIONS","GET","DELETE","HEAD"];const C=10;const I=5;class HttpClientError extends Error{constructor(e,t){super(e);this.name="HttpClientError";this.statusCode=t;Object.setPrototypeOf(this,HttpClientError.prototype)}}t.HttpClientError=HttpClientError;class HttpClientResponse{constructor(e){this.message=e}readBody(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){let t=Buffer.alloc(0);this.message.on("data",(e=>{t=Buffer.concat([t,e])}));this.message.on("end",(()=>{e(t.toString())}))}))))}))}readBodyBuffer(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){const t=[];this.message.on("data",(e=>{t.push(e)}));this.message.on("end",(()=>{e(Buffer.concat(t))}))}))))}))}}t.HttpClientResponse=HttpClientResponse;function isHttps(e){const t=new URL(e);return t.protocol==="https:"}t.isHttps=isHttps;class HttpClient{constructor(e,t,r){this._ignoreSslError=false;this._allowRedirects=true;this._allowRedirectDowngrade=false;this._maxRedirects=50;this._allowRetries=false;this._maxRetries=1;this._keepAlive=false;this._disposed=false;this.userAgent=e;this.handlers=t||[];this.requestOptions=r;if(r){if(r.ignoreSslError!=null){this._ignoreSslError=r.ignoreSslError}this._socketTimeout=r.socketTimeout;if(r.allowRedirects!=null){this._allowRedirects=r.allowRedirects}if(r.allowRedirectDowngrade!=null){this._allowRedirectDowngrade=r.allowRedirectDowngrade}if(r.maxRedirects!=null){this._maxRedirects=Math.max(r.maxRedirects,0)}if(r.keepAlive!=null){this._keepAlive=r.keepAlive}if(r.allowRetries!=null){this._allowRetries=r.allowRetries}if(r.maxRetries!=null){this._maxRetries=r.maxRetries}}}options(e,t){return i(this,void 0,void 0,(function*(){return this.request("OPTIONS",e,null,t||{})}))}get(e,t){return i(this,void 0,void 0,(function*(){return this.request("GET",e,null,t||{})}))}del(e,t){return i(this,void 0,void 0,(function*(){return this.request("DELETE",e,null,t||{})}))}post(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("POST",e,t,r||{})}))}patch(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PATCH",e,t,r||{})}))}put(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PUT",e,t,r||{})}))}head(e,t){return i(this,void 0,void 0,(function*(){return this.request("HEAD",e,null,t||{})}))}sendStream(e,t,r,n){return i(this,void 0,void 0,(function*(){return this.request(e,t,r,n)}))}getJson(e,t={}){return i(this,void 0,void 0,(function*(){t[d.Accept]=this._getExistingOrDefaultHeader(t,d.Accept,g.ApplicationJson);const r=yield this.get(e,t);return this._processResponse(r,this.requestOptions)}))}postJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.post(e,n,r);return this._processResponse(o,this.requestOptions)}))}putJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.put(e,n,r);return this._processResponse(o,this.requestOptions)}))}patchJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.patch(e,n,r);return this._processResponse(o,this.requestOptions)}))}request(e,t,r,n){return i(this,void 0,void 0,(function*(){if(this._disposed){throw new Error("Client has already been disposed.")}const o=new URL(t);let s=this._prepareRequest(e,o,n);const i=this._allowRetries&&m.includes(e)?this._maxRetries+1:1;let a=0;let A;do{A=yield this.requestRaw(s,r);if(A&&A.message&&A.message.statusCode===h.Unauthorized){let e;for(const t of this.handlers){if(t.canHandleAuthentication(A)){e=t;break}}if(e){return e.handleAuthentication(this,s,r)}else{return A}}let t=this._maxRedirects;while(A.message.statusCode&&p.includes(A.message.statusCode)&&this._allowRedirects&&t>0){const i=A.message.headers["location"];if(!i){break}const a=new URL(i);if(o.protocol==="https:"&&o.protocol!==a.protocol&&!this._allowRedirectDowngrade){throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.")}yield A.readBody();if(a.hostname!==o.hostname){for(const e in n){if(e.toLowerCase()==="authorization"){delete n[e]}}}s=this._prepareRequest(e,a,n);A=yield this.requestRaw(s,r);t--}if(!A.message.statusCode||!E.includes(A.message.statusCode)){return A}a+=1;if(a{function callbackForResult(e,t){if(e){n(e)}else if(!t){n(new Error("Unknown error"))}else{r(t)}}this.requestRawWithCallback(e,t,callbackForResult)}))}))}requestRawWithCallback(e,t,r){if(typeof t==="string"){if(!e.options.headers){e.options.headers={}}e.options.headers["Content-Length"]=Buffer.byteLength(t,"utf8")}let n=false;function handleResult(e,t){if(!n){n=true;r(e,t)}}const o=e.httpModule.request(e.options,(e=>{const t=new HttpClientResponse(e);handleResult(undefined,t)}));let s;o.on("socket",(e=>{s=e}));o.setTimeout(this._socketTimeout||3*6e4,(()=>{if(s){s.end()}handleResult(new Error(`Request timeout: ${e.options.path}`))}));o.on("error",(function(e){handleResult(e)}));if(t&&typeof t==="string"){o.write(t,"utf8")}if(t&&typeof t!=="string"){t.on("close",(function(){o.end()}));t.pipe(o)}else{o.end()}}getAgent(e){const t=new URL(e);return this._getAgent(t)}getAgentDispatcher(e){const t=new URL(e);const r=c.getProxyUrl(t);const n=r&&r.hostname;if(!n){return}return this._getProxyAgentDispatcher(t,r)}_prepareRequest(e,t,r){const n={};n.parsedUrl=t;const o=n.parsedUrl.protocol==="https:";n.httpModule=o?A:a;const s=o?443:80;n.options={};n.options.host=n.parsedUrl.hostname;n.options.port=n.parsedUrl.port?parseInt(n.parsedUrl.port):s;n.options.path=(n.parsedUrl.pathname||"")+(n.parsedUrl.search||"");n.options.method=e;n.options.headers=this._mergeHeaders(r);if(this.userAgent!=null){n.options.headers["user-agent"]=this.userAgent}n.options.agent=this._getAgent(n.parsedUrl);if(this.handlers){for(const e of this.handlers){e.prepareRequest(n.options)}}return n}_mergeHeaders(e){if(this.requestOptions&&this.requestOptions.headers){return Object.assign({},lowercaseKeys(this.requestOptions.headers),lowercaseKeys(e||{}))}return lowercaseKeys(e||{})}_getExistingOrDefaultHeader(e,t,r){let n;if(this.requestOptions&&this.requestOptions.headers){n=lowercaseKeys(this.requestOptions.headers)[t]}return e[t]||n||r}_getAgent(e){let t;const r=c.getProxyUrl(e);const n=r&&r.hostname;if(this._keepAlive&&n){t=this._proxyAgent}if(!n){t=this._agent}if(t){return t}const o=e.protocol==="https:";let s=100;if(this.requestOptions){s=this.requestOptions.maxSockets||a.globalAgent.maxSockets}if(r&&r.hostname){const e={maxSockets:s,keepAlive:this._keepAlive,proxy:Object.assign(Object.assign({},(r.username||r.password)&&{proxyAuth:`${r.username}:${r.password}`}),{host:r.hostname,port:r.port})};let n;const i=r.protocol==="https:";if(o){n=i?l.httpsOverHttps:l.httpsOverHttp}else{n=i?l.httpOverHttps:l.httpOverHttp}t=n(e);this._proxyAgent=t}if(!t){const e={keepAlive:this._keepAlive,maxSockets:s};t=o?new A.Agent(e):new a.Agent(e);this._agent=t}if(o&&this._ignoreSslError){t.options=Object.assign(t.options||{},{rejectUnauthorized:false})}return t}_getProxyAgentDispatcher(e,t){let r;if(this._keepAlive){r=this._proxyAgentDispatcher}if(r){return r}const n=e.protocol==="https:";r=new u.ProxyAgent(Object.assign({uri:t.href,pipelining:!this._keepAlive?0:1},(t.username||t.password)&&{token:`${t.username}:${t.password}`}));this._proxyAgentDispatcher=r;if(n&&this._ignoreSslError){r.options=Object.assign(r.options.requestTls||{},{rejectUnauthorized:false})}return r}_performExponentialBackoff(e){return i(this,void 0,void 0,(function*(){e=Math.min(C,e);const t=I*Math.pow(2,e);return new Promise((e=>setTimeout((()=>e()),t)))}))}_processResponse(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((r,n)=>i(this,void 0,void 0,(function*(){const o=e.message.statusCode||0;const s={statusCode:o,result:null,headers:{}};if(o===h.NotFound){r(s)}function dateTimeDeserializer(e,t){if(typeof t==="string"){const e=new Date(t);if(!isNaN(e.valueOf())){return e}}return t}let i;let a;try{a=yield e.readBody();if(a&&a.length>0){if(t&&t.deserializeDates){i=JSON.parse(a,dateTimeDeserializer)}else{i=JSON.parse(a)}s.result=i}s.headers=e.message.headers}catch(e){}if(o>299){let e;if(i&&i.message){e=i.message}else if(a&&a.length>0){e=a}else{e=`Failed request: (${o})`}const t=new HttpClientError(e,o);t.result=s.result;n(t)}else{r(s)}}))))}))}}t.HttpClient=HttpClient;const lowercaseKeys=e=>Object.keys(e).reduce(((t,r)=>(t[r.toLowerCase()]=e[r],t)),{})},9835:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.checkBypass=t.getProxyUrl=void 0;function getProxyUrl(e){const t=e.protocol==="https:";if(checkBypass(e)){return undefined}const r=(()=>{if(t){return process.env["https_proxy"]||process.env["HTTPS_PROXY"]}else{return process.env["http_proxy"]||process.env["HTTP_PROXY"]}})();if(r){try{return new URL(r)}catch(e){if(!r.startsWith("http://")&&!r.startsWith("https://"))return new URL(`http://${r}`)}}else{return undefined}}t.getProxyUrl=getProxyUrl;function checkBypass(e){if(!e.hostname){return false}const t=e.hostname;if(isLoopbackAddress(t)){return true}const r=process.env["no_proxy"]||process.env["NO_PROXY"]||"";if(!r){return false}let n;if(e.port){n=Number(e.port)}else if(e.protocol==="http:"){n=80}else if(e.protocol==="https:"){n=443}const o=[e.hostname.toUpperCase()];if(typeof n==="number"){o.push(`${o[0]}:${n}`)}for(const e of r.split(",").map((e=>e.trim().toUpperCase())).filter((e=>e))){if(e==="*"||o.some((t=>t===e||t.endsWith(`.${e}`)||e.startsWith(".")&&t.endsWith(`${e}`)))){return true}}return false}t.checkBypass=checkBypass;function isLoopbackAddress(e){const t=e.toLowerCase();return t==="localhost"||t.startsWith("127.")||t.startsWith("[::1]")||t.startsWith("[0:0:0:0:0:0:0:1]")}},9690:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2361);const s=n(r(8237));const i=n(r(6570));const a=s.default("agent-base");function isAgent(e){return Boolean(e)&&typeof e.addRequest==="function"}function isSecureEndpoint(){const{stack:e}=new Error;if(typeof e!=="string")return false;return e.split("\n").some((e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1))}function createAgent(e,t){return new createAgent.Agent(e,t)}(function(e){class Agent extends o.EventEmitter{constructor(e,t){super();let r=t;if(typeof e==="function"){this.callback=e}else if(e){r=e}this.timeout=null;if(r&&typeof r.timeout==="number"){this.timeout=r.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,r){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const r=Object.assign({},t);if(typeof r.secureEndpoint!=="boolean"){r.secureEndpoint=isSecureEndpoint()}if(r.host==null){r.host="localhost"}if(r.port==null){r.port=r.secureEndpoint?443:80}if(r.protocol==null){r.protocol=r.secureEndpoint?"https:":"http:"}if(r.host&&r.path){delete r.path}delete r.agent;delete r.hostname;delete r._defaultAgent;delete r.defaultPort;delete r.createConnection;e._last=true;e.shouldKeepAlive=false;let n=false;let o=null;const s=r.timeout||this.timeout;const onerror=t=>{if(e._hadError)return;e.emit("error",t);e._hadError=true};const ontimeout=()=>{o=null;n=true;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT";onerror(e)};const callbackError=e=>{if(n)return;if(o!==null){clearTimeout(o);o=null}onerror(e)};const onsocket=t=>{if(n)return;if(o!=null){clearTimeout(o);o=null}if(isAgent(t)){a("Callback returned another Agent instance %o",t.constructor.name);t.addRequest(e,r);return}if(t){t.once("free",(()=>{this.freeSocket(t,r)}));e.onSocket(t);return}const s=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);onerror(s)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){a("Converting legacy callback function to promise");this.promisifiedCallback=i.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof s==="number"&&s>0){o=setTimeout(ontimeout,s)}if("port"in r&&typeof r.port!=="number"){r.port=Number(r.port)}try{a("Resolving socket for %o request: %o",r.protocol,`${e.method} ${e.path}`);Promise.resolve(this.promisifiedCallback(e,r)).then(onsocket,callbackError)}catch(e){Promise.reject(e).catch(callbackError)}}freeSocket(e,t){a("Freeing socket %o %o",e.constructor.name,t);e.destroy()}destroy(){a("Destroying agent %o",this.constructor.name)}}e.Agent=Agent;e.prototype=e.Agent.prototype})(createAgent||(createAgent={}));e.exports=createAgent},6570:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function promisify(e){return function(t,r){return new Promise(((n,o)=>{e.call(this,t,r,((e,t)=>{if(e){o(e)}else{n(t)}}))}))}}t["default"]=promisify},4855:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6006);var s=function(){function Mutex(e){this._semaphore=new o.default(1,e)}Mutex.prototype.acquire=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,n.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._semaphore.acquire()];case 1:e=r.sent(),t=e[1];return[2,t]}}))}))};Mutex.prototype.runExclusive=function(e){return this._semaphore.runExclusive((function(){return e()}))};Mutex.prototype.isLocked=function(){return this._semaphore.isLocked()};Mutex.prototype.waitForUnlock=function(){return this._semaphore.waitForUnlock()};Mutex.prototype.release=function(){this._semaphore.release()};Mutex.prototype.cancel=function(){return this._semaphore.cancel()};return Mutex}();t["default"]=s},6006:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6984);var s=function(){function Semaphore(e,t){if(t===void 0){t=o.E_CANCELED}this._maxConcurrency=e;this._cancelError=t;this._queue=[];this._waiters=[];if(e<=0){throw new Error("semaphore must be initialized to a positive value")}this._value=e}Semaphore.prototype.acquire=function(){var e=this;var t=this.isLocked();var r=new Promise((function(t,r){return e._queue.push({resolve:t,reject:r})}));if(!t)this._dispatch();return r};Semaphore.prototype.runExclusive=function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r,o;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.acquire()];case 1:t=n.sent(),r=t[0],o=t[1];n.label=2;case 2:n.trys.push([2,,4,5]);return[4,e(r)];case 3:return[2,n.sent()];case 4:o();return[7];case 5:return[2]}}))}))};Semaphore.prototype.waitForUnlock=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e;var t=this;return(0,n.__generator)(this,(function(r){if(!this.isLocked()){return[2,Promise.resolve()]}e=new Promise((function(e){return t._waiters.push({resolve:e})}));return[2,e]}))}))};Semaphore.prototype.isLocked=function(){return this._value<=0};Semaphore.prototype.release=function(){if(this._maxConcurrency>1){throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead")}if(this._currentReleaser){var e=this._currentReleaser;this._currentReleaser=undefined;e()}};Semaphore.prototype.cancel=function(){var e=this;this._queue.forEach((function(t){return t.reject(e._cancelError)}));this._queue=[]};Semaphore.prototype._dispatch=function(){var e=this;var t=this._queue.shift();if(!t)return;var r=false;this._currentReleaser=function(){if(r)return;r=true;e._value++;e._resolveWaiters();e._dispatch()};t.resolve([this._value--,this._currentReleaser])};Semaphore.prototype._resolveWaiters=function(){this._waiters.forEach((function(e){return e.resolve()}));this._waiters=[]};return Semaphore}();t["default"]=s},6984:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.E_CANCELED=t.E_ALREADY_LOCKED=t.E_TIMEOUT=void 0;t.E_TIMEOUT=new Error("timeout while waiting for mutex to become available");t.E_ALREADY_LOCKED=new Error("mutex already locked");t.E_CANCELED=new Error("request for lock canceled")},4038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=t.withTimeout=t.Semaphore=t.Mutex=void 0;var n=r(4351);var o=r(4855);Object.defineProperty(t,"Mutex",{enumerable:true,get:function(){return o.default}});var s=r(6006);Object.defineProperty(t,"Semaphore",{enumerable:true,get:function(){return s.default}});var i=r(5124);Object.defineProperty(t,"withTimeout",{enumerable:true,get:function(){return i.withTimeout}});var a=r(2621);Object.defineProperty(t,"tryAcquire",{enumerable:true,get:function(){return a.tryAcquire}});(0,n.__exportStar)(r(6984),t)},2621:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=void 0;var n=r(6984);var o=r(5124);function tryAcquire(e,t){if(t===void 0){t=n.E_ALREADY_LOCKED}return(0,o.withTimeout)(e,0,t)}t.tryAcquire=tryAcquire},5124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.withTimeout=void 0;var n=r(4351);var o=r(6984);function withTimeout(e,t,r){var s=this;if(r===void 0){r=o.E_TIMEOUT}return{acquire:function(){return new Promise((function(o,i){return(0,n.__awaiter)(s,void 0,void 0,(function(){var s,a,A,c,l;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:s=false;a=setTimeout((function(){s=true;i(r)}),t);n.label=1;case 1:n.trys.push([1,3,,4]);return[4,e.acquire()];case 2:A=n.sent();if(s){c=Array.isArray(A)?A[1]:A;c()}else{clearTimeout(a);o(A)}return[3,4];case 3:l=n.sent();if(!s){clearTimeout(a);i(l)}return[3,4];case 4:return[2]}}))}))}))},runExclusive:function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:t=function(){return undefined};n.label=1;case 1:n.trys.push([1,,7,8]);return[4,this.acquire()];case 2:r=n.sent();if(!Array.isArray(r))return[3,4];t=r[1];return[4,e(r[0])];case 3:return[2,n.sent()];case 4:t=r;return[4,e()];case 5:return[2,n.sent()];case 6:return[3,8];case 7:t();return[7];case 8:return[2]}}))}))},release:function(){e.release()},cancel:function(){return e.cancel()},waitForUnlock:function(){return e.waitForUnlock()},isLocked:function(){return e.isLocked()}}}t.withTimeout=withTimeout},9417:e=>{"use strict";e.exports=balanced;function balanced(e,t,r){if(e instanceof RegExp)e=maybeMatch(e,r);if(t instanceof RegExp)t=maybeMatch(t,r);var n=range(e,t,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+e.length,n[1]),post:r.slice(n[1]+t.length)}}function maybeMatch(e,t){var r=t.match(e);return r?r[0]:null}balanced.range=range;function range(e,t,r){var n,o,s,i,a;var A=r.indexOf(e);var c=r.indexOf(t,A+1);var l=A;if(A>=0&&c>0){if(e===t){return[A,c]}n=[];s=r.length;while(l>=0&&!a){if(l==A){n.push(l);A=r.indexOf(e,l+1)}else if(n.length==1){a=[n.pop(),c]}else{o=n.pop();if(o=0?A:c}if(n.length){a=[s,i]}}return a}},336:(e,t,r)=>{"use strict";var n=r(1642).Duplex,o=r(3837),s=r(1867).Buffer;function BufferList(e){if(!(this instanceof BufferList))return new BufferList(e);this._bufs=[];this.length=0;if(typeof e=="function"){this._callback=e;var t=function piper(e){if(this._callback){this._callback(e);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(e){e.on("error",t)}));this.on("unpipe",(function onUnpipe(e){e.removeListener("error",t)}))}else{this.append(e)}n.call(this)}o.inherits(BufferList,n);BufferList.prototype._offset=function _offset(e){var t=0,r=0,n;if(e===0)return[0,0];for(;rthis.length||e<0){return undefined}var t=this._offset(e);return this._bufs[t[0]][t[1]]};BufferList.prototype.slice=function slice(e,t){if(typeof e=="number"&&e<0)e+=this.length;if(typeof t=="number"&&t<0)t+=this.length;return this.copy(null,0,e,t)};BufferList.prototype.copy=function copy(e,t,r,n){if(typeof r!="number"||r<0)r=0;if(typeof n!="number"||n>this.length)n=this.length;if(r>=this.length)return e||s.alloc(0);if(n<=0)return e||s.alloc(0);var copy=!!e,o=this._offset(r),i=n-r,a=i,A=copy&&t||0,c=o[1],l,u;if(r===0&&n==this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length)}for(u=0;ul){this._bufs[u].copy(e,A,c);A+=l}else{this._bufs[u].copy(e,A,c,c+a);A+=l;break}a-=l;if(c)c=0}if(e.length>A)return e.slice(0,A);return e};BufferList.prototype.shallowSlice=function shallowSlice(e,t){e=e||0;t=typeof t!=="number"?this.length:t;if(e<0)e+=this.length;if(t<0)t+=this.length;if(e===t){return new BufferList}var r=this._offset(e),n=this._offset(t),o=this._bufs.slice(r[0],n[0]+1);if(n[1]==0)o.pop();else o[o.length-1]=o[o.length-1].slice(0,n[1]);if(r[1]!=0)o[0]=o[0].slice(r[1]);return new BufferList(o)};BufferList.prototype.toString=function toString(e,t,r){return this.slice(t,r).toString(e)};BufferList.prototype.consume=function consume(e){e=Math.trunc(e);if(Number.isNaN(e)||e<=0)return this;while(this._bufs.length){if(e>=this._bufs[0].length){e-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(e);this.length-=e;break}}return this};BufferList.prototype.duplicate=function duplicate(){var e=0,t=new BufferList;for(;ethis.length?this.length:t}var n=this._offset(t);var o=n[0];var i=n[1];for(o;o=e.length){var c=a.indexOf(e,i);if(c!==-1){return this._reverseOffset([o,c])}i=a.length-e.length+1}else{var l=this._reverseOffset([o,i]);if(this._match(l,e)){return l}i++}}i=0}return-1};BufferList.prototype._match=function(e,t){if(this.length-e{var n=r(6891);var o=r(9417);e.exports=expandTop;var s="\0SLASH"+Math.random()+"\0";var i="\0OPEN"+Math.random()+"\0";var a="\0CLOSE"+Math.random()+"\0";var A="\0COMMA"+Math.random()+"\0";var c="\0PERIOD"+Math.random()+"\0";function numeric(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function escapeBraces(e){return e.split("\\\\").join(s).split("\\{").join(i).split("\\}").join(a).split("\\,").join(A).split("\\.").join(c)}function unescapeBraces(e){return e.split(s).join("\\").split(i).join("{").split(a).join("}").split(A).join(",").split(c).join(".")}function parseCommaParts(e){if(!e)return[""];var t=[];var r=o("{","}",e);if(!r)return e.split(",");var n=r.pre;var s=r.body;var i=r.post;var a=n.split(",");a[a.length-1]+="{"+s+"}";var A=parseCommaParts(i);if(i.length){a[a.length-1]+=A.shift();a.push.apply(a,A)}t.push.apply(t,a);return t}function expandTop(e){if(!e)return[];if(e.substr(0,2)==="{}"){e="\\{\\}"+e.substr(2)}return expand(escapeBraces(e),true).map(unescapeBraces)}function identity(e){return e}function embrace(e){return"{"+e+"}"}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand(e,t){var r=[];var s=o("{","}",e);if(!s||/\$$/.test(s.pre))return[e];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);var A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);var c=i||A;var l=s.body.indexOf(",")>=0;if(!c&&!l){if(s.post.match(/,.*\}/)){e=s.pre+"{"+s.body+a+s.post;return expand(e)}return[e]}var u;if(c){u=s.body.split(/\.\./)}else{u=parseCommaParts(s.body);if(u.length===1){u=expand(u[0],false).map(embrace);if(u.length===1){var h=s.post.length?expand(s.post,false):[""];return h.map((function(e){return s.pre+u[0]+e}))}}}var d=s.pre;var h=s.post.length?expand(s.post,false):[""];var g;if(c){var p=numeric(u[0]);var E=numeric(u[1]);var m=Math.max(u[0].length,u[1].length);var C=u.length==3?Math.abs(numeric(u[2])):1;var I=lte;var y=E0){var S=new Array(w+1).join("0");if(Q<0)b="-"+S+b.slice(1);else b=S+b}}}g.push(b)}}else{g=n(u,(function(e){return expand(e,false)}))}for(var v=0;v{var n=r(6800),o=r(5497),s=r(7113),i=r(3797),a=r(414),A=r(972),c=r(6142),l=r(8522),u=r(3639),h=r(5846),d=r(5325),g=r(9502),p=r(4636),E=r(2259),m=r(1031);n.BSON_INT32_MAX=2147483647;n.BSON_INT32_MIN=-2147483648;n.BSON_INT64_MAX=Math.pow(2,63)-1;n.BSON_INT64_MIN=-Math.pow(2,63);n.JS_INT_MAX=9007199254740992;n.JS_INT_MIN=-9007199254740992;n.Binary=o;n.Code=s;n.DBRef=i;n.Decimal128=a;n.Double=A;n.Int32=c;n.Long=l;n.Map=u;n.MaxKey=h;n.MinKey=d;n.ObjectId=g;n.ObjectID=g;n.BSONRegExp=p;n.Symbol=E;n.Timestamp=m;e.exports=n},5497:(e,t,r)=>{if(typeof global!=="undefined"){var n=r(4300).Buffer}var o=r(2863);function Binary(e,t){if(!(this instanceof Binary))return new Binary(e,t);if(e!=null&&!(typeof e==="string")&&!n.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e)){throw new Error("only String, Buffer, Uint8Array or Array accepted")}this._bsontype="Binary";if(e instanceof Number){this.sub_type=e;this.position=0}else{this.sub_type=t==null?s:t;this.position=0}if(e!=null&&!(e instanceof Number)){if(typeof e==="string"){if(typeof n!=="undefined"){this.buffer=o.toBuffer(e)}else if(typeof Uint8Array!=="undefined"||Object.prototype.toString.call(e)==="[object Array]"){this.buffer=writeStringToArray(e)}else{throw new Error("only String, Buffer, Uint8Array or Array accepted")}}else{this.buffer=e}this.position=e.length}else{if(typeof n!=="undefined"){this.buffer=o.allocBuffer(Binary.BUFFER_SIZE)}else if(typeof Uint8Array!=="undefined"){this.buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE))}else{this.buffer=new Array(Binary.BUFFER_SIZE)}this.position=0}}Binary.prototype.put=function put(e){if(e["length"]!=null&&typeof e!=="number"&&e.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof e!=="number"&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(typeof e==="string"){t=e.charCodeAt(0)}else if(e["length"]!=null){t=e[0]}else{t=e}if(this.buffer.length>this.position){this.buffer[this.position++]=t}else{if(typeof n!=="undefined"&&n.isBuffer(this.buffer)){var r=o.allocBuffer(Binary.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length);this.buffer=r;this.buffer[this.position++]=t}else{r=null;if(Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"){r=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE+this.buffer.length))}else{r=new Array(Binary.BUFFER_SIZE+this.buffer.length)}for(var s=0;sthis.position?t+e.length:this.position}else if(typeof n!=="undefined"&&typeof e==="string"&&n.isBuffer(this.buffer)){this.buffer.write(e,t,"binary");this.position=t+e.length>this.position?t+e.length:this.position}else if(Object.prototype.toString.call(e)==="[object Uint8Array]"||Object.prototype.toString.call(e)==="[object Array]"&&typeof e!=="string"){for(s=0;sthis.position?t:this.position}else if(typeof e==="string"){for(s=0;sthis.position?t:this.position}};Binary.prototype.read=function read(e,t){t=t&&t>0?t:this.position;if(this.buffer["slice"]){return this.buffer.slice(e,e+t)}else{var r=typeof Uint8Array!=="undefined"?new Uint8Array(new ArrayBuffer(t)):new Array(t);for(var n=0;n{"use strict";var n=r(3639),o=r(8522),s=r(972),i=r(1031),a=r(9502),A=r(4636),c=r(2259),l=r(6142),u=r(7113),h=r(414),d=r(5325),g=r(5846),p=r(3797),E=r(5497);var m=r(2139),C=r(9290),I=r(1273),y=r(2863);var B=1024*1024*17;var Q=y.allocBuffer(B);var BSON=function(){};BSON.prototype.serialize=function serialize(e,t){t=t||{};var r=typeof t.checkKeys==="boolean"?t.checkKeys:false;var n=typeof t.serializeFunctions==="boolean"?t.serializeFunctions:false;var o=typeof t.ignoreUndefined==="boolean"?t.ignoreUndefined:true;var s=typeof t.minInternalBufferSize==="number"?t.minInternalBufferSize:B;if(Q.length{var t=function Code(e,t){if(!(this instanceof Code))return new Code(e,t);this._bsontype="Code";this.code=e;this.scope=t};t.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};e.exports=t;e.exports.Code=t},3797:e=>{function DBRef(e,t,r){if(!(this instanceof DBRef))return new DBRef(e,t,r);this._bsontype="DBRef";this.namespace=e;this.oid=t;this.db=r}DBRef.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};e.exports=DBRef;e.exports.DBRef=DBRef},414:(e,t,r)=>{"use strict";var n=r(8522);var o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var s=/^(\+|-)?(Infinity|inf)$/i;var i=/^(\+|-)?NaN$/i;var a=6111;var A=-6176;var c=6176;var l=34;var u=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var h=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var d=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var g=/^([-+])?(\d+)?$/;var p=r(2863);var isDigit=function(e){return!isNaN(parseInt(e,10))};var divideu128=function(e){var t=n.fromNumber(1e3*1e3*1e3);var r=n.fromNumber(0);var o=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3]){return{quotient:e,rem:r}}for(o=0;o<=3;o++){r=r.shiftLeft(32);r=r.add(new n(e.parts[o],0));e.parts[o]=r.div(t).low_;r=r.modulo(t)}return{quotient:e,rem:r}};var multiply64x2=function(e,t){if(!e&&!t){return{high:n.fromNumber(0),low:n.fromNumber(0)}}var r=e.shiftRightUnsigned(32);var o=new n(e.getLowBits(),0);var s=t.shiftRightUnsigned(32);var i=new n(t.getLowBits(),0);var a=r.multiply(s);var A=r.multiply(i);var c=o.multiply(s);var l=o.multiply(i);a=a.add(A.shiftRightUnsigned(32));A=new n(A.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32));a=a.add(A.shiftRightUnsigned(32));l=A.shiftLeft(32).add(new n(l.getLowBits(),0));return{high:a,low:l}};var lessThan=function(e,t){var r=e.high_>>>0;var n=t.high_>>>0;if(r>>0;var s=t.low_>>>0;if(o=7e3){throw new Error(""+e+" not a valid Decimal128 string")}var _=e.match(o);var M=e.match(s);var L=e.match(i);if(!_&&!M&&!L||e.length===0){throw new Error(""+e+" not a valid Decimal128 string")}if(_&&_[4]&&_[2]===undefined){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="+"||e[O]==="-"){t=e[O++]==="-"}if(!isDigit(e[O])&&e[O]!=="."){if(e[O]==="i"||e[O]==="I"){return new Decimal128(p.toBuffer(t?h:d))}else if(e[O]==="N"){return new Decimal128(p.toBuffer(u))}}while(isDigit(e[O])||e[O]==="."){if(e[O]==="."){if(r){return new Decimal128(p.toBuffer(u))}r=true;O=O+1;continue}if(b<34){if(e[O]!=="0"||E){if(!E){B=C}E=true;Q[w++]=parseInt(e[O],10);b=b+1}}if(E){I=I+1}if(r){y=y+1}C=C+1;O=O+1}if(r&&!C){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="e"||e[O]==="E"){var F=e.substr(++O).match(g);if(!F||!F[2]){return new Decimal128(p.toBuffer(u))}R=parseInt(F[0],10);O=O+F[0].length}if(e[O]){return new Decimal128(p.toBuffer(u))}S=0;if(!b){S=0;v=0;Q[0]=0;I=1;b=1;m=0}else{v=b-1;m=I;if(R!==0&&m!==1){while(e[B+m-1]==="0"){m=m-1}}}if(R<=y&&y-R>1<<14){R=A}else{R=R-y}while(R>a){v=v+1;if(v-S>l){var U=Q.join("");if(U.match(/^0+$/)){R=a;break}else{return new Decimal128(p.toBuffer(t?h:d))}}R=R-1}while(R=5){Y=1;if(G===5){Y=Q[v]%2===1;for(k=B+v+2;k=0;V--){if(++Q[V]>9){Q[V]=0;if(V===0){if(R>8&255;q[O++]=J.low.low_>>16&255;q[O++]=J.low.low_>>24&255;q[O++]=J.low.high_&255;q[O++]=J.low.high_>>8&255;q[O++]=J.low.high_>>16&255;q[O++]=J.low.high_>>24&255;q[O++]=J.high.low_&255;q[O++]=J.high.low_>>8&255;q[O++]=J.high.low_>>16&255;q[O++]=J.high.low_>>24&255;q[O++]=J.high.high_&255;q[O++]=J.high.high_>>8&255;q[O++]=J.high.high_>>16&255;q[O++]=J.high.high_>>24&255;return new Decimal128(q)};var E=31;var m=16383;var C=30;var I=31;c=6176;Decimal128.prototype.toString=function(){var e;var t;var r;var o;var s;var i;var a=0;var A=new Array(36);for(var l=0;l>26&E;if(s>>3===3){if(s===C){return b.join("")+"Infinity"}else if(s===I){return"NaN"}else{i=e>>15&m;p=8+(e>>14&1)}}else{p=e>>14&7;i=e>>17&m}h=i-c;y.parts[0]=(e&16383)+((p&15)<<14);y.parts[1]=t;y.parts[2]=r;y.parts[3]=o;if(y.parts[0]===0&&y.parts[1]===0&&y.parts[2]===0&&y.parts[3]===0){g=true}else{for(Q=3;Q>=0;Q--){var v=0;var R=divideu128(y);y=R.quotient;v=R.rem.low_;if(!v)continue;for(B=8;B>=0;B--){A[Q*9+B]=v%10;v=Math.floor(v/10)}}}if(g){a=1;A[u]=0}else{a=36;l=0;while(!A[u]){l++;a=a-1;u=u+1}}d=a-1+h;if(d>=34||d<=-7||h>0){b.push(A[u++]);a=a-1;if(a){b.push(".")}for(l=0;l0){b.push("+"+d)}else{b.push(d)}}else{if(h>=0){for(l=0;l0){for(l=0;l{function Double(e){if(!(this instanceof Double))return new Double(e);this._bsontype="Double";this.value=e}Double.prototype.valueOf=function(){return this.value};Double.prototype.toJSON=function(){return this.value};e.exports=Double;e.exports.Double=Double},7998:(e,t)=>{var r;var readIEEE754=function(e,t,r,n,o){var s,i,a=r==="big",A=o*8-n-1,c=(1<>1,u=-7,h=a?0:o-1,d=a?1:-1,g=e[t+h];h+=d;s=g&(1<<-u)-1;g>>=-u;u+=A;for(;u>0;s=s*256+e[t+h],h+=d,u-=8);i=s&(1<<-u)-1;s>>=-u;u+=n;for(;u>0;i=i*256+e[t+h],h+=d,u-=8);if(s===0){s=1-l}else if(s===c){return i?NaN:(g?-1:1)*Infinity}else{i=i+Math.pow(2,n);s=s-l}return(g?-1:1)*i*Math.pow(2,s-n)};var writeIEEE754=function(e,t,r,n,o,s){var i,a,A,c=n==="big",l=s*8-o-1,u=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=c?s-1:0,p=c?-1:1,E=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;i=u}else{i=Math.floor(Math.log(t)/Math.LN2);if(t*(A=Math.pow(2,-i))<1){i--;A*=2}if(i+h>=1){t+=d/A}else{t+=d*Math.pow(2,1-h)}if(t*A>=2){i++;A/=2}if(i+h>=u){a=0;i=u}else if(i+h>=1){a=(t*A-1)*Math.pow(2,o);i=i+h}else{a=t*Math.pow(2,h-1)*Math.pow(2,o);i=0}}for(;o>=8;e[r+g]=a&255,g+=p,a/=256,o-=8);i=i<0;e[r+g]=i&255,g+=p,i/=256,l-=8);e[r+g-p]|=E*128};r=readIEEE754;t.P=writeIEEE754},6142:e=>{var Int32=function(e){if(!(this instanceof Int32))return new Int32(e);this._bsontype="Int32";this.value=e};Int32.prototype.valueOf=function(){return this.value};Int32.prototype.toJSON=function(){return this.value};e.exports=Int32;e.exports.Int32=Int32},8522:e=>{function Long(e,t){if(!(this instanceof Long))return new Long(e,t);this._bsontype="Long";this.low_=e|0;this.high_=t|0}Long.prototype.toInt=function(){return this.low_};Long.prototype.toNumber=function(){return this.high_*Long.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Long.prototype.toBigInt=function(){return BigInt(this.toString())};Long.prototype.toJSON=function(){return this.toString()};Long.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Long.TWO_PWR_32_DBL_+this.low_};Long.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Long.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Long.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Long.prototype.negate=function(){if(this.equals(Long.MIN_VALUE)){return Long.MIN_VALUE}else{return this.not().add(Long.ONE)}};Long.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.subtract=function(e){return this.add(e.negate())};Long.prototype.multiply=function(e){if(this.isZero()){return Long.ZERO}else if(e.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){return e.isOdd()?Long.MIN_VALUE:Long.ZERO}else if(e.equals(Long.MIN_VALUE)){return this.isOdd()?Long.MIN_VALUE:Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Long.TWO_PWR_24_)&&e.lessThan(Long.TWO_PWR_24_)){return Long.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){if(e.equals(Long.ONE)||e.equals(Long.NEG_ONE)){return Long.MIN_VALUE}else if(e.equals(Long.MIN_VALUE)){return Long.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Long.ZERO)){return e.isNegative()?Long.ONE:Long.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Long.MIN_VALUE)){return Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Long.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Long.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Long.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Long.ONE}s=s.add(A);n=n.subtract(c)}return s};Long.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Long.prototype.not=function(){return Long.fromBits(~this.low_,~this.high_)};Long.prototype.and=function(e){return Long.fromBits(this.low_&e.low_,this.high_&e.high_)};Long.prototype.or=function(e){return Long.fromBits(this.low_|e.low_,this.high_|e.high_)};Long.prototype.xor=function(e){return Long.fromBits(this.low_^e.low_,this.high_^e.high_)};Long.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Long.fromBits(t<>>32-e)}else{return Long.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Long.fromBits(t>>e-32,t>=0?0:-1)}}};Long.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Long.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Long.fromBits(t,0)}else{return Long.fromBits(t>>>e-32,0)}}};Long.fromInt=function(e){if(-128<=e&&e<128){var t=Long.INT_CACHE_[e];if(t){return t}}var r=new Long(e|0,e<0?-1:0);if(-128<=e&&e<128){Long.INT_CACHE_[e]=r}return r};Long.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Long.ZERO}else if(e<=-Long.TWO_PWR_63_DBL_){return Long.MIN_VALUE}else if(e+1>=Long.TWO_PWR_63_DBL_){return Long.MAX_VALUE}else if(e<0){return Long.fromNumber(-e).negate()}else{return new Long(e%Long.TWO_PWR_32_DBL_|0,e/Long.TWO_PWR_32_DBL_|0)}};Long.fromBigInt=function(e){return Long.fromString(e.toString(10),10)};Long.fromBits=function(e,t){return new Long(e,t)};Long.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Long.fromNumber(Math.pow(r,8));var o=Long.ZERO;for(var s=0;s{"use strict";if(typeof global.Map!=="undefined"){e.exports=global.Map;e.exports.Map=global.Map}else{var Map=function(e){this._keys=[];this._values={};for(var t=0;t{function MaxKey(){if(!(this instanceof MaxKey))return new MaxKey;this._bsontype="MaxKey"}e.exports=MaxKey;e.exports.MaxKey=MaxKey},5325:e=>{function MinKey(){if(!(this instanceof MinKey))return new MinKey;this._bsontype="MinKey"}e.exports=MinKey;e.exports.MinKey=MinKey},9502:(e,t,r)=>{var n="inspect";var o=r(2863);var s=parseInt(Math.random()*16777215,10);var i=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=true;n=r(3837).inspect.custom||"inspect"}}catch(e){a=false}var A=function ObjectID(e){if(e instanceof ObjectID)return e;if(!(this instanceof ObjectID))return new ObjectID(e);this._bsontype="ObjectID";if(e==null||typeof e==="number"){this.id=this.generate(e);if(ObjectID.cacheHexString)this.__id=this.toString("hex");return}var t=ObjectID.isValid(e);if(!t&&e!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(t&&typeof e==="string"&&e.length===24&&a){return new ObjectID(o.toBuffer(e,"hex"))}else if(t&&typeof e==="string"&&e.length===24){return ObjectID.createFromHexString(e)}else if(e!=null&&e.length===12){this.id=e}else if(e!=null&&typeof e.toHexString==="function"){return e}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}if(ObjectID.cacheHexString)this.__id=this.toString("hex")};var c=[];for(var l=0;l<256;l++){c[l]=(l<=15?"0":"")+l.toString(16)}A.prototype.toHexString=function(){if(A.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id instanceof h){e=convertToHex(this.id);if(A.cacheHexString)this.__id=e;return e}for(var t=0;t>8&255;n[1]=e>>16&255;n[0]=e>>24&255;n[6]=s&255;n[5]=s>>8&255;n[4]=s>>16&255;n[8]=t&255;n[7]=t>>8&255;n[11]=r&255;n[10]=r>>8&255;n[9]=r>>16&255;return n};A.prototype.toString=function(e){if(this.id&&this.id.copy){return this.id.toString(typeof e==="string"?e:"hex")}return this.toHexString()};A.prototype[n]=A.prototype.toString;A.prototype.toJSON=function(){return this.toHexString()};A.prototype.equals=function equals(e){if(e instanceof A){return this.toString()===e.toString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12&&this.id instanceof h){return e===this.id.toString("binary")}else if(typeof e==="string"&&A.isValid(e)&&e.length===24){return e.toLowerCase()===this.toHexString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12){return e===this.id}else if(e!=null&&(e instanceof A||e.toHexString)){return e.toHexString()===this.toHexString()}else{return false}};A.prototype.getTimestamp=function(){var e=new Date;var t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;e.setTime(Math.floor(t)*1e3);return e};A.index=~~(Math.random()*16777215);A.createPk=function createPk(){return new A};A.createFromTime=function createFromTime(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);t[3]=e&255;t[2]=e>>8&255;t[1]=e>>16&255;t[0]=e>>24&255;return new A(t)};var u=[];l=0;while(l<10)u[48+l]=l++;while(l<16)u[65-10+l]=u[97-10+l]=l++;var h=Buffer;var convertToHex=function(e){return e.toString("hex")};A.createFromHexString=function createFromHexString(e){if(typeof e==="undefined"||e!=null&&e.length!==24){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 A(o.toBuffer(e,"hex"));var t=new h(12);var r=0;var n=0;while(n<24){t[r++]=u[e.charCodeAt(n++)]<<4|u[e.charCodeAt(n++)]}return new A(t)};A.isValid=function isValid(e){if(e==null)return false;if(typeof e==="number"){return true}if(typeof e==="string"){return e.length===12||e.length===24&&i.test(e)}if(e instanceof A){return true}if(e instanceof h){return true}if(typeof e.toHexString==="function"&&(e.id instanceof h||typeof e.id==="string")){return e.id.length===12||e.id.length===24&&i.test(e.id)}return false};Object.defineProperty(A.prototype,"generationTime",{enumerable:true,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255;this.id[2]=e>>8&255;this.id[1]=e>>16&255;this.id[0]=e>>24&255}});e.exports=A;e.exports.ObjectID=A;e.exports.ObjectId=A},1273:(e,t,r)=>{"use strict";var n=r(8522).Long,o=r(972).Double,s=r(1031).Timestamp,i=r(9502).ObjectID,a=r(2259).Symbol,A=r(4636).BSONRegExp,c=r(7113).Code,l=r(414),u=r(5325).MinKey,h=r(5846).MaxKey,d=r(3797).DBRef,g=r(5497).Binary;var p=r(2863).normalizedFunctionString;var E=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var m=function calculateObjectSize(e,t,r){var n=4+1;if(Array.isArray(e)){for(var o=0;o=C.JS_INT_MIN&&t<=C.JS_INT_MAX){if(t>=C.BSON_INT32_MIN&&t<=C.BSON_INT32_MAX){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}case"undefined":if(I||!y)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;return 0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof u||t instanceof h||t["_bsontype"]==="MinKey"||t["_bsontype"]==="MaxKey"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1}else if(t instanceof i||t["_bsontype"]==="ObjectID"||t["_bsontype"]==="ObjectId"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1)}else if(t instanceof Date||E(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(typeof Buffer!=="undefined"&&Buffer.isBuffer(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length}else if(t instanceof n||t instanceof o||t instanceof s||t["_bsontype"]==="Long"||t["_bsontype"]==="Double"||t["_bsontype"]==="Timestamp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(t instanceof l||t["_bsontype"]==="Decimal128"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1)}else if(t instanceof c||t["_bsontype"]==="Code"){if(t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+m(t.scope,r,y)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1}}else if(t instanceof g||t["_bsontype"]==="Binary"){if(t.sub_type===g.SUBTYPE_BYTE_ARRAY){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1)}}else if(t instanceof a||t["_bsontype"]==="Symbol"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1}else if(t instanceof d||t["_bsontype"]==="DBRef"){var B={$ref:t.namespace,$id:t.oid};if(null!=t.db){B["$db"]=t.db}return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+m(B,r,y)}else if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"){return(e!=null?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}else if(t instanceof A||t["_bsontype"]==="BSONRegExp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+m(t,r,y)+1}case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]"){return(e!=null?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}else{if(r&&t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(p(t),"utf8")+1+m(t.scope,r,y)}else if(r){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(p(t),"utf8")+1}}}return 0}var C={};C.BSON_INT32_MAX=2147483647;C.BSON_INT32_MIN=-2147483648;C.JS_INT_MAX=9007199254740992;C.JS_INT_MIN=-9007199254740992;e.exports=m},2139:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";var Long=__nccwpck_require__(8522).Long,Double=__nccwpck_require__(972).Double,Timestamp=__nccwpck_require__(1031).Timestamp,ObjectID=__nccwpck_require__(9502).ObjectID,Symbol=__nccwpck_require__(2259).Symbol,Code=__nccwpck_require__(7113).Code,MinKey=__nccwpck_require__(5325).MinKey,MaxKey=__nccwpck_require__(5846).MaxKey,Decimal128=__nccwpck_require__(414),Int32=__nccwpck_require__(6142),DBRef=__nccwpck_require__(3797).DBRef,BSONRegExp=__nccwpck_require__(4636).BSONRegExp,Binary=__nccwpck_require__(5497).Binary;var utils=__nccwpck_require__(2863);var deserialize=function(e,t,r){t=t==null?{}:t;var n=t&&t.index?t.index:0;var o=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(o<5||e.lengthe.length){throw new Error("corrupt bson message")}if(e[n+o-1]!==0){throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(e,n,t,r)};var deserializeObject=function(e,t,r,n){var o=r["evalFunctions"]==null?false:r["evalFunctions"];var s=r["cacheFunctions"]==null?false:r["cacheFunctions"];var i=r["cacheFunctionsCrc32"]==null?false:r["cacheFunctionsCrc32"];if(!i)var a=null;var A=r["fieldsAsRaw"]==null?null:r["fieldsAsRaw"];var c=r["raw"]==null?false:r["raw"];var l=typeof r["bsonRegExp"]==="boolean"?r["bsonRegExp"]:false;var u=r["promoteBuffers"]==null?false:r["promoteBuffers"];var h=r["promoteLongs"]==null?true:r["promoteLongs"];var d=r["promoteValues"]==null?true:r["promoteValues"];var g=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var p=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(p<5||p>e.length)throw new Error("corrupt bson message");var E=n?[]:{};var m=0;var C=false;while(!C){var I=e[t++];if(I===0)break;var y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var B=n?m++:e.toString("utf8",t,y);t=y+1;if(I===BSON.BSON_DATA_STRING){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=e.toString("utf8",t,t+Q-1);t=t+Q}else if(I===BSON.BSON_DATA_OID){var b=utils.allocBuffer(12);e.copy(b,0,t,t+12);E[B]=new ObjectID(b);t=t+12}else if(I===BSON.BSON_DATA_INT&&d===false){E[B]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)}else if(I===BSON.BSON_DATA_INT){E[B]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}else if(I===BSON.BSON_DATA_NUMBER&&d===false){E[B]=new Double(e.readDoubleLE(t));t=t+8}else if(I===BSON.BSON_DATA_NUMBER){E[B]=e.readDoubleLE(t);t=t+8}else if(I===BSON.BSON_DATA_DATE){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Date(new Long(w,S).toNumber())}else if(I===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");E[B]=e[t++]===1}else if(I===BSON.BSON_DATA_OBJECT){var v=t;var R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(R<=0||R>e.length-t)throw new Error("bad embedded document length in bson");if(c){E[B]=e.slice(t,t+R)}else{E[B]=deserializeObject(e,v,r,false)}t=t+R}else if(I===BSON.BSON_DATA_ARRAY){v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var k=r;var D=t+R;if(A&&A[B]){k={};for(var N in r)k[N]=r[N];k["raw"]=true}E[B]=deserializeObject(e,v,k,true);t=t+R;if(e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==D)throw new Error("corrupted array bson")}else if(I===BSON.BSON_DATA_UNDEFINED){E[B]=undefined}else if(I===BSON.BSON_DATA_NULL){E[B]=null}else if(I===BSON.BSON_DATA_LONG){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var T=new Long(w,S);if(h&&d===true){E[B]=T.lessThanOrEqual(JS_INT_MAX_LONG)&&T.greaterThanOrEqual(JS_INT_MIN_LONG)?T.toNumber():T}else{E[B]=T}}else if(I===BSON.BSON_DATA_DECIMAL128){var O=utils.allocBuffer(16);e.copy(O,0,t,t+16);t=t+16;var _=new Decimal128(O);E[B]=_.toObject?_.toObject():_}else if(I===BSON.BSON_DATA_BINARY){var M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var L=M;var F=e[t++];if(M<0)throw new Error("Negative binary type element size found");if(M>e.length)throw new Error("Binary type size larger than document size");if(e["slice"]!=null){if(F===Binary.SUBTYPE_BYTE_ARRAY){M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(M<0)throw new Error("Negative binary type element size found for subtype 0x02");if(M>L-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(ML-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(M=e.length)throw new Error("Bad BSON Document: illegal CString");var P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var G=e.toString("utf8",t,y);t=y+1;var Y=new Array(G.length);for(y=0;y=e.length)throw new Error("Bad BSON Document: illegal CString");P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");G=e.toString("utf8",t,y);t=y+1;E[B]=new BSONRegExp(P,G)}else if(I===BSON.BSON_DATA_SYMBOL){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=new Symbol(e.toString("utf8",t,t+Q-1));t=t+Q}else if(I===BSON.BSON_DATA_TIMESTAMP){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Timestamp(w,S)}else if(I===BSON.BSON_DATA_MIN_KEY){E[B]=new MinKey}else if(I===BSON.BSON_DATA_MAX_KEY){E[B]=new MaxKey}else if(I===BSON.BSON_DATA_CODE){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var V=e.toString("utf8",t,t+Q-1);if(o){if(s){var W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}}else{E[B]=new Code(V)}t=t+Q}else if(I===BSON.BSON_DATA_CODE_W_SCOPE){var J=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(J<4+4+4+1){throw new Error("code_w_scope total size shorter minimum expected length")}Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");V=e.toString("utf8",t,t+Q-1);t=t+Q;v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,v,r,false);t=t+R;if(J<4+4+R+Q){throw new Error("code_w_scope total size is to short, truncating scope")}if(J>4+4+R+Q){throw new Error("code_w_scope total size is to long, clips outer document")}if(o){if(s){W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}E[B].scope=q}else{E[B]=new Code(V,q)}}else if(I===BSON.BSON_DATA_DBPOINTER){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var j=e.toString("utf8",t,t+Q-1);t=t+Q;var z=utils.allocBuffer(12);e.copy(z,0,t,t+12);b=new ObjectID(z);t=t+12;var $=j.split(".");var K=$.shift();var X=$.join(".");E[B]=new DBRef(X,b,K)}else{throw new Error("Detected unknown BSON type "+I.toString(16)+' for fieldname "'+B+'", are you using the latest BSON parser')}}if(p!==t-g){if(n)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}if(E["$id"]!=null)E=new DBRef(E["$ref"],E["$id"],E["$db"]);return E};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;if(functionCache[hash]==null){eval("value = "+functionString);functionCache[hash]=value}return functionCache[hash].bind(object)};var isolateEval=function(functionString){var value=null;eval("value = "+functionString);return value};var BSON={};var 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);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},9290:(e,t,r)=>{"use strict";var n=r(7998).P,o=r(8522).Long,s=r(3639),i=r(5497).Binary;var a=r(2863).normalizedFunctionString;var A=/\x00/;var c=["$db","$ref","$id","$clusterTime"];var l=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var u=function isRegExp(e){return Object.prototype.toString.call(e)==="[object RegExp]"};var serializeString=function(e,t,r,n,o){e[n++]=d.BSON_DATA_STRING;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s+1;e[n-1]=0;var i=e.write(r,n+4,"utf8");e[n+3]=i+1>>24&255;e[n+2]=i+1>>16&255;e[n+1]=i+1>>8&255;e[n]=i+1&255;n=n+4+i;e[n++]=0;return n};var serializeNumber=function(e,t,r,s,i){if(Math.floor(r)===r&&r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){if(r>=d.BSON_INT32_MIN&&r<=d.BSON_INT32_MAX){e[s++]=d.BSON_DATA_INT;var a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;e[s++]=r&255;e[s++]=r>>8&255;e[s++]=r>>16&255;e[s++]=r>>24&255}else if(r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}else{e[s++]=d.BSON_DATA_LONG;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;var A=o.fromNumber(r);var c=A.getLowBits();var l=A.getHighBits();e[s++]=c&255;e[s++]=c>>8&255;e[s++]=c>>16&255;e[s++]=c>>24&255;e[s++]=l&255;e[s++]=l>>8&255;e[s++]=l>>16&255;e[s++]=l>>24&255}}else{e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}return s};var serializeNull=function(e,t,r,n,o){e[n++]=d.BSON_DATA_NULL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeBoolean=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BOOLEAN;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r?1:0;return n};var serializeDate=function(e,t,r,n,s){e[n++]=d.BSON_DATA_DATE;var i=!s?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+i;e[n++]=0;var a=o.fromNumber(r.getTime());var A=a.getLowBits();var c=a.getHighBits();e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=c&255;e[n++]=c>>8&255;e[n++]=c>>16&255;e[n++]=c>>24&255;return n};var serializeRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.source&&r.source.match(A)!=null){throw Error("value "+r.source+" must not contain null bytes")}n=n+e.write(r.source,n,"utf8");e[n++]=0;if(r.global)e[n++]=115;if(r.ignoreCase)e[n++]=105;if(r.multiline)e[n++]=109;e[n++]=0;return n};var serializeBSONRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.pattern.match(A)!=null){throw Error("pattern "+r.pattern+" must not contain null bytes")}n=n+e.write(r.pattern,n,"utf8");e[n++]=0;n=n+e.write(r.options.split("").sort().join(""),n,"utf8");e[n++]=0;return n};var serializeMinMax=function(e,t,r,n,o){if(r===null){e[n++]=d.BSON_DATA_NULL}else if(r._bsontype==="MinKey"){e[n++]=d.BSON_DATA_MIN_KEY}else{e[n++]=d.BSON_DATA_MAX_KEY}var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeObjectId=function(e,t,r,n,o){e[n++]=d.BSON_DATA_OID;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(typeof r.id==="string"){e.write(r.id,n,"binary")}else if(r.id&&r.id.copy){r.id.copy(e,n,0,12)}else{throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId")}return n+12};var serializeBuffer=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=r.length;e[n++]=i&255;e[n++]=i>>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=d.BSON_BINARY_SUBTYPE_DEFAULT;r.copy(e,n,0,i);n=n+i;return n};var serializeObject=function(e,t,r,n,o,s,i,a,A,c){for(var l=0;l>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=a&255;e[n++]=a>>8&255;e[n++]=a>>16&255;e[n++]=a>>24&255;return n};var serializeInt32=function(e,t,r,n,o){e[n++]=d.BSON_DATA_INT;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r&255;e[n++]=r>>8&255;e[n++]=r>>16&255;e[n++]=r>>24&255;return n};var serializeDouble=function(e,t,r,o,s){e[o++]=d.BSON_DATA_NUMBER;var i=!s?e.write(t,o,"utf8"):e.write(t,o,"ascii");o=o+i;e[o++]=0;n(e,r,o,"little",52,8);o=o+8;return o};var serializeFunction=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_CODE;var A=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+A;e[n++]=0;var c=a(r);var l=e.write(c,n+4,"utf8")+1;e[n]=l&255;e[n+1]=l>>8&255;e[n+2]=l>>16&255;e[n+3]=l>>24&255;n=n+4+l-1;e[n++]=0;return n};var serializeCode=function(e,t,r,n,o,s,i,a,A){if(r.scope&&typeof r.scope==="object"){e[n++]=d.BSON_DATA_CODE_W_SCOPE;var c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;var l=n;var u=typeof r.code==="string"?r.code:r.code.toString();n=n+4;var g=e.write(u,n+4,"utf8")+1;e[n]=g&255;e[n+1]=g>>8&255;e[n+2]=g>>16&255;e[n+3]=g>>24&255;e[n+4+g-1]=0;n=n+g+4;var p=h(e,r.scope,o,n,s+1,i,a);n=p-1;var E=p-l;e[l++]=E&255;e[l++]=E>>8&255;e[l++]=E>>16&255;e[l++]=E>>24&255;e[n++]=0}else{e[n++]=d.BSON_DATA_CODE;c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;u=r.code.toString();var m=e.write(u,n+4,"utf8")+1;e[n]=m&255;e[n+1]=m>>8&255;e[n+2]=m>>16&255;e[n+3]=m>>24&255;n=n+4+m-1;e[n++]=0}return n};var serializeBinary=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var a=r.value(true);var A=r.position;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY)A=A+4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=r.sub_type;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY){A=A-4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255}a.copy(e,n,0,r.position);n=n+r.position;return n};var serializeSymbol=function(e,t,r,n,o){e[n++]=d.BSON_DATA_SYMBOL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=e.write(r.value,n+4,"utf8")+1;e[n]=i&255;e[n+1]=i>>8&255;e[n+2]=i>>16&255;e[n+3]=i>>24&255;n=n+4+i-1;e[n++]=0;return n};var serializeDBRef=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_OBJECT;var a=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+a;e[n++]=0;var A=n;var c;if(null!=r.db){c=h(e,{$ref:r.namespace,$id:r.oid,$db:r.db},false,n,o+1,s)}else{c=h(e,{$ref:r.namespace,$id:r.oid},false,n,o+1,s)}var l=c-A;e[A++]=l&255;e[A++]=l>>8&255;e[A++]=l>>16&255;e[A++]=l>>24&255;return c};var h=function serializeInto(e,t,r,n,o,i,a,h){n=n||0;h=h||[];h.push(t);var d=n+4;if(Array.isArray(t)){for(var g=0;g>8&255;e[n++]=B>>16&255;e[n++]=B>>24&255;return d};var d={};d.BSON_DATA_NUMBER=1;d.BSON_DATA_STRING=2;d.BSON_DATA_OBJECT=3;d.BSON_DATA_ARRAY=4;d.BSON_DATA_BINARY=5;d.BSON_DATA_UNDEFINED=6;d.BSON_DATA_OID=7;d.BSON_DATA_BOOLEAN=8;d.BSON_DATA_DATE=9;d.BSON_DATA_NULL=10;d.BSON_DATA_REGEXP=11;d.BSON_DATA_CODE=13;d.BSON_DATA_SYMBOL=14;d.BSON_DATA_CODE_W_SCOPE=15;d.BSON_DATA_INT=16;d.BSON_DATA_TIMESTAMP=17;d.BSON_DATA_LONG=18;d.BSON_DATA_DECIMAL128=19;d.BSON_DATA_MIN_KEY=255;d.BSON_DATA_MAX_KEY=127;d.BSON_BINARY_SUBTYPE_DEFAULT=0;d.BSON_BINARY_SUBTYPE_FUNCTION=1;d.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;d.BSON_BINARY_SUBTYPE_UUID=3;d.BSON_BINARY_SUBTYPE_MD5=4;d.BSON_BINARY_SUBTYPE_USER_DEFINED=128;d.BSON_INT32_MAX=2147483647;d.BSON_INT32_MIN=-2147483648;d.BSON_INT64_MAX=Math.pow(2,63)-1;d.BSON_INT64_MIN=-Math.pow(2,63);d.JS_INT_MAX=9007199254740992;d.JS_INT_MIN=-9007199254740992;e.exports=h},2863:e=>{"use strict";function normalizedFunctionString(e){return e.toString().replace(/function *\(/,"function (")}function newBuffer(e,t){return new Buffer(e,t)}function allocBuffer(){return Buffer.alloc.apply(Buffer,arguments)}function toBuffer(){return Buffer.from.apply(Buffer,arguments)}e.exports={normalizedFunctionString:normalizedFunctionString,allocBuffer:typeof Buffer.alloc==="function"?allocBuffer:newBuffer,toBuffer:typeof Buffer.from==="function"?toBuffer:newBuffer}},4636:e=>{function BSONRegExp(e,t){if(!(this instanceof BSONRegExp))return new BSONRegExp;this._bsontype="BSONRegExp";this.pattern=e||"";this.options=t||"";for(var r=0;r{var n=Buffer?r(3837).inspect.custom||"inspect":"inspect";function Symbol(e){if(!(this instanceof Symbol))return new Symbol(e);this._bsontype="Symbol";this.value=e}Symbol.prototype.valueOf=function(){return this.value};Symbol.prototype.toString=function(){return this.value};Symbol.prototype[n]=function(){return this.value};Symbol.prototype.toJSON=function(){return this.value};e.exports=Symbol;e.exports.Symbol=Symbol},1031:e=>{function Timestamp(e,t){if(!(this instanceof Timestamp))return new Timestamp(e,t);this._bsontype="Timestamp";this.low_=e|0;this.high_=t|0}Timestamp.prototype.toInt=function(){return this.low_};Timestamp.prototype.toNumber=function(){return this.high_*Timestamp.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Timestamp.prototype.toJSON=function(){return this.toString()};Timestamp.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Timestamp.TWO_PWR_32_DBL_+this.low_};Timestamp.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Timestamp.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Timestamp.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Timestamp.prototype.negate=function(){if(this.equals(Timestamp.MIN_VALUE)){return Timestamp.MIN_VALUE}else{return this.not().add(Timestamp.ONE)}};Timestamp.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.subtract=function(e){return this.add(e.negate())};Timestamp.prototype.multiply=function(e){if(this.isZero()){return Timestamp.ZERO}else if(e.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){return e.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}else if(e.equals(Timestamp.MIN_VALUE)){return this.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Timestamp.TWO_PWR_24_)&&e.lessThan(Timestamp.TWO_PWR_24_)){return Timestamp.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){if(e.equals(Timestamp.ONE)||e.equals(Timestamp.NEG_ONE)){return Timestamp.MIN_VALUE}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Timestamp.ZERO)){return e.isNegative()?Timestamp.ONE:Timestamp.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Timestamp.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Timestamp.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Timestamp.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Timestamp.ONE}s=s.add(A);n=n.subtract(c)}return s};Timestamp.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Timestamp.prototype.not=function(){return Timestamp.fromBits(~this.low_,~this.high_)};Timestamp.prototype.and=function(e){return Timestamp.fromBits(this.low_&e.low_,this.high_&e.high_)};Timestamp.prototype.or=function(e){return Timestamp.fromBits(this.low_|e.low_,this.high_|e.high_)};Timestamp.prototype.xor=function(e){return Timestamp.fromBits(this.low_^e.low_,this.high_^e.high_)};Timestamp.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Timestamp.fromBits(t<>>32-e)}else{return Timestamp.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Timestamp.fromBits(t>>e-32,t>=0?0:-1)}}};Timestamp.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Timestamp.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Timestamp.fromBits(t,0)}else{return Timestamp.fromBits(t>>>e-32,0)}}};Timestamp.fromInt=function(e){if(-128<=e&&e<128){var t=Timestamp.INT_CACHE_[e];if(t){return t}}var r=new Timestamp(e|0,e<0?-1:0);if(-128<=e&&e<128){Timestamp.INT_CACHE_[e]=r}return r};Timestamp.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Timestamp.ZERO}else if(e<=-Timestamp.TWO_PWR_63_DBL_){return Timestamp.MIN_VALUE}else if(e+1>=Timestamp.TWO_PWR_63_DBL_){return Timestamp.MAX_VALUE}else if(e<0){return Timestamp.fromNumber(-e).negate()}else{return new Timestamp(e%Timestamp.TWO_PWR_32_DBL_|0,e/Timestamp.TWO_PWR_32_DBL_|0)}};Timestamp.fromBits=function(e,t){return new Timestamp(e,t)};Timestamp.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Timestamp.fromNumber(Math.pow(r,8));var o=Timestamp.ZERO;for(var s=0;s{var n=r(4300).Buffer;var o=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){o=new Int32Array(o)}function ensureBuffer(e){if(n.isBuffer(e)){return e}var t=typeof n.alloc==="function"&&typeof n.from==="function";if(typeof e==="number"){return t?n.alloc(e):new n(e)}else if(typeof e==="string"){return t?n.from(e):new n(e)}else{throw new Error("input must be buffer, number, or string, received "+typeof e)}}function bufferizeInt(e){var t=ensureBuffer(4);t.writeInt32BE(e,0);return t}function _crc32(e,t){e=ensureBuffer(e);if(n.isBuffer(t)){t=t.readUInt32BE(0)}var r=~~t^-1;for(var s=0;s>>8}return r^-1}function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};e.exports=crc32},1362:e=>{"use strict";const t=/[\p{Lu}]/u;const r=/[\p{Ll}]/u;const n=/^[\p{Lu}](?![\p{Lu}])/gu;const o=/([\p{Alpha}\p{N}_]|$)/u;const s=/[_.\- ]+/;const i=new RegExp("^"+s.source);const a=new RegExp(s.source+o.source,"gu");const A=new RegExp("\\d+"+o.source,"gu");const preserveCamelCase=(e,n,o)=>{let s=false;let i=false;let a=false;for(let A=0;A{n.lastIndex=0;return e.replace(n,(e=>t(e)))};const postProcess=(e,t)=>{a.lastIndex=0;A.lastIndex=0;return e.replace(a,((e,r)=>t(r))).replace(A,(e=>t(e)))};const camelCase=(e,t)=>{if(!(typeof e==="string"||Array.isArray(e))){throw new TypeError("Expected the input to be `string | string[]`")}t={pascalCase:false,preserveConsecutiveUppercase:false,...t};if(Array.isArray(e)){e=e.map((e=>e.trim())).filter((e=>e.length)).join("-")}else{e=e.trim()}if(e.length===0){return""}const r=t.locale===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale);const n=t.locale===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);if(e.length===1){return t.pascalCase?n(e):r(e)}const o=e!==r(e);if(o){e=preserveCamelCase(e,r,n)}e=e.replace(i,"");if(t.preserveConsecutiveUppercase){e=preserveConsecutiveUppercase(e,r)}else{e=r(e)}if(t.pascalCase){e=n(e.charAt(0))+e.slice(1)}return postProcess(e,n)};e.exports=camelCase;e.exports["default"]=camelCase},9930:(e,t,r)=>{var n=r(1017);e.exports=function(e,t){if(t){var r=t.map((function(t){return n.resolve(e,t)}))}else{var r=e}var o=r.slice(1).reduce((function(e,t){if(!t.match(/^([A-Za-z]:)?\/|\\/)){throw new Error("relative path without a basedir")}var r=t.split(/\/+|\\+/);for(var n=0;e[n]===r[n]&&n1?o.join("/"):"/"}},6891:e=>{e.exports=function(e,r){var n=[];for(var o=0;o{t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.storage=localstorage();t.destroy=(()=>{let e=false;return()=>{if(!e){e=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(t){t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff);if(!this.useColors){return}const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0;let o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{if(e==="%%"){return}n++;if(e==="%c"){o=n}}));t.splice(o,0,r)}t.log=console.debug||console.log||(()=>{});function save(e){try{if(e){t.storage.setItem("debug",e)}else{t.storage.removeItem("debug")}}catch(e){}}function load(){let e;try{e=t.storage.getItem("debug")}catch(e){}if(!e&&typeof process!=="undefined"&&"env"in process){e=process.env.DEBUG}return e}function localstorage(){try{return localStorage}catch(e){}}e.exports=r(6243)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},6243:(e,t,r)=>{function setup(e){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=r(900);createDebug.destroy=destroy;Object.keys(e).forEach((t=>{createDebug[t]=e[t]}));createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let t=0;for(let r=0;r{if(t==="%%"){return"%"}s++;const o=createDebug.formatters[n];if(typeof o==="function"){const n=e[s];t=o.call(r,n);e.splice(s,1);s--}return t}));createDebug.formatArgs.call(r,e);const i=r.log||createDebug.log;i.apply(r,e)}debug.namespace=e;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(e);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>r===null?createDebug.enabled(e):r,set:e=>{r=e}});if(typeof createDebug.init==="function"){createDebug.init(debug)}return debug}function extend(e,t){const r=createDebug(this.namespace+(typeof t==="undefined"?":":t)+e);r.log=this.log;return r}function enable(e){createDebug.save(e);createDebug.names=[];createDebug.skips=[];let t;const r=(typeof e==="string"?e:"").split(/[\s,]+/);const n=r.length;for(t=0;t"-"+e))].join(",");createDebug.enable("");return e}function enabled(e){if(e[e.length-1]==="*"){return true}let t;let r;for(t=0,r=createDebug.skips.length;t{if(typeof process==="undefined"||process.type==="renderer"||process.browser===true||process.__nwjs){e.exports=r(8222)}else{e.exports=r(5332)}},5332:(e,t,r)=>{const n=r(6224);const o=r(3837);t.init=init;t.log=log;t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.destroy=o.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");t.colors=[6,2,3,4,5,1];try{const e=r(9318);if(e&&(e.stderr||e).level>=2){t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];if(/^(yes|on|true|enabled)$/i.test(n)){n=true}else if(/^(no|off|false|disabled)$/i.test(n)){n=false}else if(n==="null"){n=null}else{n=Number(n)}e[r]=n;return e}),{});function useColors(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(t){const{namespace:r,useColors:n}=this;if(n){const n=this.color;const o="[3"+(n<8?n:"8;5;"+n);const s=` ${o};1m${r} `;t[0]=s+t[0].split("\n").join("\n"+s);t.push(o+"m+"+e.exports.humanize(this.diff)+"")}else{t[0]=getDate()+r+" "+t[0]}}function getDate(){if(t.inspectOpts.hideDate){return""}return(new Date).toISOString()+" "}function log(...e){return process.stderr.write(o.format(...e)+"\n")}function save(e){if(e){process.env.DEBUG=e}else{delete process.env.DEBUG}}function load(){return process.env.DEBUG}function init(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;ne.trim())).join(" ")};s.O=function(e){this.inspectOpts.colors=this.useColors;return o.inspect(e,this.inspectOpts)}},2342:e=>{"use strict";function Denque(e,t){var t=t||{};this._head=0;this._tail=0;this._capacity=t.capacity;this._capacityMask=3;this._list=new Array(4);if(Array.isArray(e)){this._fromArray(e)}}Denque.prototype.peekAt=function peekAt(e){var t=e;if(t!==(t|0)){return void 0}var r=this.size();if(t>=r||t<-r)return undefined;if(t<0)t+=r;t=this._head+t&this._capacityMask;return this._list[t]};Denque.prototype.get=function get(e){return this.peekAt(e)};Denque.prototype.peek=function peek(){if(this._head===this._tail)return undefined;return this._list[this._head]};Denque.prototype.peekFront=function peekFront(){return this.peek()};Denque.prototype.peekBack=function peekBack(){return this.peekAt(-1)};Object.defineProperty(Denque.prototype,"length",{get:function length(){return this.size()}});Denque.prototype.size=function size(){if(this._head===this._tail)return 0;if(this._headthis._capacity)this.pop();if(this._head1e4&&this._tail<=this._list.length>>>2)this._shrinkArray();return t};Denque.prototype.push=function push(e){if(e===undefined)return this.size();var t=this._tail;this._list[t]=e;this._tail=t+1&this._capacityMask;if(this._tail===this._head){this._growArray()}if(this._capacity&&this.size()>this._capacity){this.shift()}if(this._head1e4&&e<=t>>>2)this._shrinkArray();return r};Denque.prototype.removeOne=function removeOne(e){var t=e;if(t!==(t|0)){return void 0}if(this._head===this._tail)return void 0;var r=this.size();var n=this._list.length;if(t>=r||t<-r)return void 0;if(t<0)t+=r;t=this._head+t&this._capacityMask;var o=this._list[t];var s;if(e0;s--){this._list[t]=this._list[t=t-1+n&this._capacityMask]}this._list[t]=void 0;this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--){this._list[t]=this._list[t=t+1+n&this._capacityMask]}this._list[t]=void 0;this._tail=this._tail-1+n&this._capacityMask}return o};Denque.prototype.remove=function remove(e,t){var r=e;var n;var o=t;if(r!==(r|0)){return void 0}if(this._head===this._tail)return void 0;var s=this.size();var i=this._list.length;if(r>=s||r<-s||t<1)return void 0;if(r<0)r+=s;if(t===1||!t){n=new Array(1);n[0]=this.removeOne(r);return n}if(r===0&&r+t>=s){n=this.toArray();this.clear();return n}if(r+t>s)t=s-r;var a;n=new Array(t);for(a=0;a0;a--){this._list[r=r+1+i&this._capacityMask]=void 0}return n}if(e===0){this._head=this._head+t+i&this._capacityMask;for(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])}r=this._head-1+i&this._capacityMask;while(o>0){this._list[r=r-1+i&this._capacityMask]=void 0;o--}if(e<0)this._tail=r}else{this._tail=r;r=r+t+i&this._capacityMask;for(a=s-(t+e);a>0;a--){this.push(this._list[r++])}r=this._tail;while(o>0){this._list[r=r+1+i&this._capacityMask]=void 0;o--}}if(this._head<2&&this._tail>1e4&&this._tail<=i>>>2)this._shrinkArray();return n};Denque.prototype.splice=function splice(e,t){var r=e;if(r!==(r|0)){return void 0}var n=this.size();if(r<0)r+=n;if(r>n)return void 0;if(arguments.length>2){var o;var s;var i;var a=arguments.length;var A=this._list.length;var c=2;if(!n||r0){this._head=this._head+r+A&this._capacityMask}}else{i=this.remove(r,t);this._head=this._head+r+A&this._capacityMask}while(a>c){this.unshift(arguments[--a])}for(o=r;o>0;o--){this.unshift(s[o-1])}}else{s=new Array(n-(r+t));var l=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1;this._capacityMask>>>=1};e.exports=Denque},1205:(e,t,r)=>{var n=r(1223);var noop=function(){};var isRequest=function(e){return e.setHeader&&typeof e.abort==="function"};var isChildProcess=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3};var eos=function(e,t,r){if(typeof t==="function")return eos(e,null,t);if(!t)t={};r=n(r||noop);var o=e._writableState;var s=e._readableState;var i=t.readable||t.readable!==false&&e.readable;var a=t.writable||t.writable!==false&&e.writable;var A=false;var onlegacyfinish=function(){if(!e.writable)onfinish()};var onfinish=function(){a=false;if(!i)r.call(e)};var onend=function(){i=false;if(!a)r.call(e)};var onexit=function(t){r.call(e,t?new Error("exited with error code: "+t):null)};var onerror=function(t){r.call(e,t)};var onclose=function(){process.nextTick(onclosenexttick)};var onclosenexttick=function(){if(A)return;if(i&&!(s&&(s.ended&&!s.destroyed)))return r.call(e,new Error("premature close"));if(a&&!(o&&(o.ended&&!o.destroyed)))return r.call(e,new Error("premature close"))};var onrequest=function(){e.req.on("finish",onfinish)};if(isRequest(e)){e.on("complete",onfinish);e.on("abort",onclose);if(e.req)onrequest();else e.on("request",onrequest)}else if(a&&!o){e.on("end",onlegacyfinish);e.on("close",onlegacyfinish)}if(isChildProcess(e))e.on("exit",onexit);e.on("end",onend);e.on("finish",onfinish);if(t.error!==false)e.on("error",onerror);e.on("close",onclose);return function(){A=true;e.removeListener("complete",onfinish);e.removeListener("abort",onclose);e.removeListener("request",onrequest);if(e.req)e.req.removeListener("finish",onfinish);e.removeListener("end",onlegacyfinish);e.removeListener("close",onlegacyfinish);e.removeListener("finish",onfinish);e.removeListener("exit",onexit);e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose)}};e.exports=eos},5010:(e,t,r)=>{var n=r(7147);var o=r(3837);var s=r(2781);var i=s.Readable;var a=s.Writable;var A=s.PassThrough;var c=r(4833);var l=r(2361).EventEmitter;t.createFromBuffer=createFromBuffer;t.createFromFd=createFromFd;t.BufferSlicer=BufferSlicer;t.FdSlicer=FdSlicer;o.inherits(FdSlicer,l);function FdSlicer(e,t){t=t||{};l.call(this);this.fd=e;this.pend=new c;this.pend.max=1;this.refCount=0;this.autoClose=!!t.autoClose}FdSlicer.prototype.read=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.read(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.write=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.write(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.createReadStream=function(e){return new ReadStream(this,e)};FdSlicer.prototype.createWriteStream=function(e){return new WriteStream(this,e)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var e=this;e.refCount-=1;if(e.refCount>0)return;if(e.refCount<0)throw new Error("invalid unref");if(e.autoClose){n.close(e.fd,onCloseDone)}function onCloseDone(t){if(t){e.emit("error",t)}else{e.emit("close")}}};o.inherits(ReadStream,i);function ReadStream(e,t){t=t||{};i.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end;this.pos=this.start;this.destroyed=false}ReadStream.prototype._read=function(e){var t=this;if(t.destroyed)return;var r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null){r=Math.min(r,t.endOffset-t.pos)}if(r<=0){t.destroyed=true;t.push(null);t.context.unref();return}t.context.pend.go((function(e){if(t.destroyed)return e();var o=new Buffer(r);n.read(t.context.fd,o,0,r,t.pos,(function(r,n){if(r){t.destroy(r)}else if(n===0){t.destroyed=true;t.push(null);t.context.unref()}else{t.pos+=n;t.push(o.slice(0,n))}e()}))}))};ReadStream.prototype.destroy=function(e){if(this.destroyed)return;e=e||new Error("stream destroyed");this.destroyed=true;this.emit("error",e);this.context.unref()};o.inherits(WriteStream,a);function WriteStream(e,t){t=t||{};a.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end==null?Infinity:+t.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}WriteStream.prototype._write=function(e,t,r){var o=this;if(o.destroyed)return;if(o.pos+e.length>o.endOffset){var s=new Error("maximum file length exceeded");s.code="ETOOBIG";o.destroy();r(s);return}o.context.pend.go((function(t){if(o.destroyed)return t();n.write(o.context.fd,e,0,e.length,o.pos,(function(e,n){if(e){o.destroy();t();r(e)}else{o.bytesWritten+=n;o.pos+=n;o.emit("progress");t();r()}}))}))};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};o.inherits(BufferSlicer,l);function BufferSlicer(e,t){l.call(this);t=t||{};this.refCount=0;this.buffer=e;this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}BufferSlicer.prototype.read=function(e,t,r,n,o){var s=n+r;var i=s-this.buffer.length;var a=i>0?i:r;this.buffer.copy(e,t,n,s);setImmediate((function(){o(null,a)}))};BufferSlicer.prototype.write=function(e,t,r,n,o){e.copy(this.buffer,n,t,t+r);setImmediate((function(){o(null,r,e)}))};BufferSlicer.prototype.createReadStream=function(e){e=e||{};var t=new A(e);t.destroyed=false;t.start=e.start||0;t.endOffset=e.end;t.pos=t.endOffset||this.buffer.length;var r=this.buffer.slice(t.start,t.pos);var n=0;while(true){var o=n+this.maxChunkSize;if(o>=r.length){if(nr.endOffset){var i=new Error("maximum file length exceeded");i.code="ETOOBIG";r.destroyed=true;o(i);return}e.copy(t.buffer,r.pos,0,e.length);r.bytesWritten+=e.length;r.pos=s;r.emit("progress");o()};r.destroy=function(){r.destroyed=true};return r};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(e,t){return new BufferSlicer(e,t)}function createFromFd(e,t){return new FdSlicer(e,t)}},7281:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(9930);const i=r(8098);const a=r(9126);const{env:A,cwd:c}=process;const isWritable=e=>{try{o.accessSync(e,o.constants.W_OK);return true}catch(e){return false}};function useDirectory(e,t){if(t.create){a.sync(e)}if(t.thunk){return(...t)=>n.join(e,...t)}return e}function getNodeModuleDirectory(e){const t=n.join(e,"node_modules");if(!isWritable(t)&&(o.existsSync(t)||!isWritable(n.join(e)))){return}return t}e.exports=(e={})=>{if(A.CACHE_DIR&&!["true","false","1","0"].includes(A.CACHE_DIR)){return useDirectory(n.join(A.CACHE_DIR,e.name),e)}let{cwd:t=c()}=e;if(e.files){t=s(t,e.files)}t=i.sync(t);if(!t){return}const r=getNodeModuleDirectory(t);if(!r){return undefined}return useDirectory(n.join(t,"node_modules",".cache",e.name),e)}},3186:(e,t,r)=>{e.exports=r(7147).constants||r(2057)},6863:(e,t,r)=>{e.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var n=r(7147);var o=n.realpath;var s=n.realpathSync;var i=process.version;var a=/^v[0-5]\./.test(i);var A=r(1734);function newError(e){return e&&e.syscall==="realpath"&&(e.code==="ELOOP"||e.code==="ENOMEM"||e.code==="ENAMETOOLONG")}function realpath(e,t,r){if(a){return o(e,t,r)}if(typeof t==="function"){r=t;t=null}o(e,t,(function(n,o){if(newError(n)){A.realpath(e,t,r)}else{r(n,o)}}))}function realpathSync(e,t){if(a){return s(e,t)}try{return s(e,t)}catch(r){if(newError(r)){return A.realpathSync(e,t)}else{throw r}}}function monkeypatch(){n.realpath=realpath;n.realpathSync=realpathSync}function unmonkeypatch(){n.realpath=o;n.realpathSync=s}},1734:(e,t,r)=>{var n=r(1017);var o=process.platform==="win32";var s=r(7147);var i=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function rethrow(){var e;if(i){var t=new Error;e=debugCallback}else e=missingCallback;return e;function debugCallback(e){if(e){t.message=e.message;e=t;missingCallback(e)}}function missingCallback(e){if(e){if(process.throwDeprecation)throw e;else if(!process.noDeprecation){var t="fs: missing callback "+(e.stack||e.message);if(process.traceDeprecation)console.trace(t);else console.error(t)}}}}function maybeCallback(e){return typeof e==="function"?e:rethrow()}var a=n.normalize;if(o){var A=/(.*?)(?:[\/\\]+|$)/g}else{var A=/(.*?)(?:[\/]+|$)/g}if(o){var c=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/}else{var c=/^[\/]*/}t.realpathSync=function realpathSync(e,t){e=n.resolve(e);if(t&&Object.prototype.hasOwnProperty.call(t,e)){return t[e]}var r=e,i={},a={};var l;var u;var h;var d;start();function start(){var t=c.exec(e);l=t[0].length;u=t[0];h=t[0];d="";if(o&&!a[h]){s.lstatSync(h);a[h]=true}}while(l=e.length){if(t)t[i]=e;return r(null,e)}A.lastIndex=u;var n=A.exec(e);g=h;h+=n[0];d=g+n[1];u=A.lastIndex;if(l[d]||t&&t[d]===d){return process.nextTick(LOOP)}if(t&&Object.prototype.hasOwnProperty.call(t,d)){return gotResolvedLink(t[d])}return s.lstat(d,gotStat)}function gotStat(e,n){if(e)return r(e);if(!n.isSymbolicLink()){l[d]=true;if(t)t[d]=d;return process.nextTick(LOOP)}if(!o){var i=n.dev.toString(32)+":"+n.ino.toString(32);if(a.hasOwnProperty(i)){return gotTarget(null,a[i],d)}}s.stat(d,(function(e){if(e)return r(e);s.readlink(d,(function(e,t){if(!o)a[i]=t;gotTarget(e,t)}))}))}function gotTarget(e,o,s){if(e)return r(e);var i=n.resolve(g,o);if(t)t[s]=i;gotResolvedLink(i)}function gotResolvedLink(t){e=n.resolve(t,e.slice(u));start()}}},3002:(e,t,r)=>{"use strict";const n=r(1808);class Locked extends Error{constructor(e){super(`${e} is locked`)}}const o={old:new Set,young:new Set};const s=1e3*15;let i;const getAvailablePort=e=>new Promise(((t,r)=>{const o=n.createServer();o.unref();o.on("error",r);o.listen(e,(()=>{const{port:e}=o.address();o.close((()=>{t(e)}))}))}));const portCheckSequence=function*(e){if(e){yield*e}yield 0};e.exports=async e=>{let t;if(e){t=typeof e.port==="number"?[e.port]:e.port}if(i===undefined){i=setInterval((()=>{o.old=o.young;o.young=new Set}),s);if(i.unref){i.unref()}}for(const r of portCheckSequence(t)){try{let t=await getAvailablePort({...e,port:r});while(o.old.has(t)||o.young.has(t)){if(r!==0){throw new Locked(r)}t=await getAvailablePort({...e,port:r})}o.young.add(t);return t}catch(e){if(!["EADDRINUSE","EACCES"].includes(e.code)&&!(e instanceof Locked)){throw e}}}throw new Error("No available ports found")};e.exports.makeRange=(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)){throw new TypeError("`from` and `to` must be integer numbers")}if(e<1024||e>65535){throw new RangeError("`from` must be between 1024 and 65535")}if(t<1024||t>65536){throw new RangeError("`to` must be between 1024 and 65536")}if(t{t.setopts=setopts;t.ownProp=ownProp;t.makeAbs=makeAbs;t.finish=finish;t.mark=mark;t.isIgnored=isIgnored;t.childrenIgnored=childrenIgnored;function ownProp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var n=r(1017);var o=r(3973);var s=r(8714);var i=o.Minimatch;function alphasort(e,t){return e.localeCompare(t,"en")}function setupIgnores(e,t){e.ignore=t.ignore||[];if(!Array.isArray(e.ignore))e.ignore=[e.ignore];if(e.ignore.length){e.ignore=e.ignore.map(ignoreMap)}}function ignoreMap(e){var t=null;if(e.slice(-3)==="/**"){var r=e.replace(/(\/\*\*)+$/,"");t=new i(r,{dot:true})}return{matcher:new i(e,{dot:true}),gmatcher:t}}function setopts(e,t,r){if(!r)r={};if(r.matchBase&&-1===t.indexOf("/")){if(r.noglobstar){throw new Error("base matching requires globstar")}t="**/"+t}e.silent=!!r.silent;e.pattern=t;e.strict=r.strict!==false;e.realpath=!!r.realpath;e.realpathCache=r.realpathCache||Object.create(null);e.follow=!!r.follow;e.dot=!!r.dot;e.mark=!!r.mark;e.nodir=!!r.nodir;if(e.nodir)e.mark=true;e.sync=!!r.sync;e.nounique=!!r.nounique;e.nonull=!!r.nonull;e.nosort=!!r.nosort;e.nocase=!!r.nocase;e.stat=!!r.stat;e.noprocess=!!r.noprocess;e.absolute=!!r.absolute;e.maxLength=r.maxLength||Infinity;e.cache=r.cache||Object.create(null);e.statCache=r.statCache||Object.create(null);e.symlinks=r.symlinks||Object.create(null);setupIgnores(e,r);e.changedCwd=false;var o=process.cwd();if(!ownProp(r,"cwd"))e.cwd=o;else{e.cwd=n.resolve(r.cwd);e.changedCwd=e.cwd!==o}e.root=r.root||n.resolve(e.cwd,"/");e.root=n.resolve(e.root);if(process.platform==="win32")e.root=e.root.replace(/\\/g,"/");e.cwdAbs=s(e.cwd)?e.cwd:makeAbs(e,e.cwd);if(process.platform==="win32")e.cwdAbs=e.cwdAbs.replace(/\\/g,"/");e.nomount=!!r.nomount;r.nonegate=true;r.nocomment=true;e.minimatch=new i(t,r);e.options=e.minimatch.options}function finish(e){var t=e.nounique;var r=t?[]:Object.create(null);for(var n=0,o=e.matches.length;n{e.exports=glob;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(4124);var A=r(2361).EventEmitter;var c=r(1017);var l=r(9491);var u=r(8714);var h=r(9010);var d=r(7625);var g=d.setopts;var p=d.ownProp;var E=r(2492);var m=r(3837);var C=d.childrenIgnored;var I=d.isIgnored;var y=r(1223);function glob(e,t,r){if(typeof t==="function")r=t,t={};if(!t)t={};if(t.sync){if(r)throw new TypeError("callback provided to sync glob");return h(e,t)}return new Glob(e,t,r)}glob.sync=h;var B=glob.GlobSync=h.GlobSync;glob.glob=glob;function extend(e,t){if(t===null||typeof t!=="object"){return e}var r=Object.keys(t);var n=r.length;while(n--){e[r[n]]=t[r[n]]}return e}glob.hasMagic=function(e,t){var r=extend({},t);r.noprocess=true;var n=new Glob(e,r);var o=n.minimatch.set;if(!e)return false;if(o.length>1)return true;for(var s=0;sthis.maxLength)return t();if(!this.stat&&p(this.cache,r)){var s=this.cache[r];if(Array.isArray(s))s="DIR";if(!o||s==="DIR")return t(null,s);if(o&&s==="FILE")return t()}var i;var a=this.statCache[r];if(a!==undefined){if(a===false)return t(null,a);else{var A=a.isDirectory()?"DIR":"FILE";if(o&&A==="FILE")return t();else return t(null,A,a)}}var c=this;var l=E("stat\0"+r,lstatcb_);if(l)n.lstat(r,l);function lstatcb_(o,s){if(s&&s.isSymbolicLink()){return n.stat(r,(function(n,o){if(n)c._stat2(e,r,null,s,t);else c._stat2(e,r,n,o,t)}))}else{c._stat2(e,r,o,s,t)}}};Glob.prototype._stat2=function(e,t,r,n,o){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR")){this.statCache[t]=false;return o()}var s=e.slice(-1)==="/";this.statCache[t]=n;if(t.slice(-1)==="/"&&n&&!n.isDirectory())return o(null,false,n);var i=true;if(n)i=n.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||i;if(s&&i==="FILE")return o();return o(null,i,n)}},9010:(e,t,r)=>{e.exports=globSync;globSync.GlobSync=GlobSync;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(1957).Glob;var A=r(3837);var c=r(1017);var l=r(9491);var u=r(8714);var h=r(7625);var d=h.setopts;var g=h.ownProp;var p=h.childrenIgnored;var E=h.isIgnored;function globSync(e,t){if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(e,t).found}function GlobSync(e,t){if(!e)throw new Error("must provide pattern");if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(e,t);d(this,e,t);if(this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;nthis.maxLength)return false;if(!this.stat&&g(this.cache,t)){var o=this.cache[t];if(Array.isArray(o))o="DIR";if(!r||o==="DIR")return o;if(r&&o==="FILE")return false}var s;var i=this.statCache[t];if(!i){var a;try{a=n.lstatSync(t)}catch(e){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[t]=false;return false}}if(a&&a.isSymbolicLink()){try{i=n.statSync(t)}catch(e){i=a}}else{i=a}}this.statCache[t]=i;var o=true;if(i)o=i.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||o;if(r&&o==="FILE")return false;return o};GlobSync.prototype._mark=function(e){return h.mark(this,e)};GlobSync.prototype._makeAbs=function(e){return h.makeAbs(this,e)}},1621:e=>{"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":e.length===1?"-":"--";const n=t.indexOf(r+e);const o=t.indexOf("--");return n!==-1&&(o===-1||n{h("replaying proxy buffer for failed request");A.default(e.listenerCount("data")>0);e.push(C);e.push(null)}));return I}))}}t["default"]=HttpsProxyAgent;function resume(e){e.resume()}function isDefaultPort(e,t){return Boolean(!t&&e===80||t&&e===443)}function isHTTPS(e){return typeof e==="string"?/^https:?$/i.test(e):false}function omit(e,...t){const r={};let n;for(n in e){if(!t.includes(n)){r[n]=e[n]}}return r}},7219:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(3734));function createHttpsProxyAgent(e){return new o.default(e)}(function(e){e.HttpsProxyAgent=o.default;e.prototype=o.default.prototype})(createHttpsProxyAgent||(createHttpsProxyAgent={}));e.exports=createHttpsProxyAgent},595:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=n(r(8237));const s=o.default("https-proxy-agent:parse-proxy-response");function parseProxyResponse(e){return new Promise(((t,r)=>{let n=0;const o=[];function read(){const t=e.read();if(t)ondata(t);else e.once("readable",read)}function cleanup(){e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose);e.removeListener("readable",read)}function onclose(e){s("onclose had error %o",e)}function onend(){s("onend")}function onerror(e){cleanup();s("onerror %o",e);r(e)}function ondata(e){o.push(e);n+=e.length;const r=Buffer.concat(o,n);const i=r.indexOf("\r\n\r\n");if(i===-1){s("have not received end of HTTP headers yet...");read();return}const a=r.toString("ascii",0,r.indexOf("\r\n"));const A=+a.split(" ")[1];s("got proxy server response: %o",a);t({statusCode:A,buffered:r})}e.on("error",onerror);e.on("close",onclose);e.on("end",onend);read()}))}t["default"]=parseProxyResponse},2492:(e,t,r)=>{var n=r(2940);var o=Object.create(null);var s=r(1223);e.exports=n(inflight);function inflight(e,t){if(o[e]){o[e].push(t);return null}else{o[e]=[t];return makeres(e)}}function makeres(e){return s((function RES(){var t=o[e];var r=t.length;var n=slice(arguments);try{for(var s=0;sr){t.splice(0,r);process.nextTick((function(){RES.apply(null,n)}))}else{delete o[e]}}}))}function slice(e){var t=e.length;var r=[];for(var n=0;n{try{var n=r(3837);if(typeof n.inherits!=="function")throw"";e.exports=n.inherits}catch(t){e.exports=r(8544)}},8544:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9126:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const{promisify:s}=r(3837);const i=r(1383);const a=i.satisfies(process.version,">=10.12.0");const checkPath=e=>{if(process.platform==="win32"){const t=/[<>:"|?*]/.test(e.replace(o.parse(e).root,""));if(t){const t=new Error(`Path contains invalid characters: ${e}`);t.code="EINVAL";throw t}}};const processOptions=e=>{const t={mode:511,fs:n};return{...t,...e}};const permissionError=e=>{const t=new Error(`operation not permitted, mkdir '${e}'`);t.code="EPERM";t.errno=-4048;t.path=e;t.syscall="mkdir";return t};const makeDir=async(e,t)=>{checkPath(e);t=processOptions(t);const r=s(t.fs.mkdir);const i=s(t.fs.stat);if(a&&t.fs.mkdir===n.mkdir){const n=o.resolve(e);await r(n,{mode:t.mode,recursive:true});return n}const make=async e=>{try{await r(e,t.mode);return e}catch(t){if(t.code==="EPERM"){throw t}if(t.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(t.message.includes("null bytes")){throw t}await make(o.dirname(e));return make(e)}try{const t=await i(e);if(!t.isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw t}return e}};return make(o.resolve(e))};e.exports=makeDir;e.exports.sync=(e,t)=>{checkPath(e);t=processOptions(t);if(a&&t.fs.mkdirSync===n.mkdirSync){const r=o.resolve(e);n.mkdirSync(r,{mode:t.mode,recursive:true});return r}const make=e=>{try{t.fs.mkdirSync(e,t.mode)}catch(r){if(r.code==="EPERM"){throw r}if(r.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(r.message.includes("null bytes")){throw r}make(o.dirname(e));return make(e)}try{if(!t.fs.statSync(e).isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw r}}return e};return make(o.resolve(e))}},1446:(e,t,r)=>{const n=r(6113);const o=r(7147);const s=8192;function md5FileSync(e){const t=o.openSync(e,"r");const r=n.createHash("md5");const i=Buffer.alloc(s);try{let e;do{e=o.readSync(t,i,0,s);r.update(i.slice(0,e))}while(e===s)}finally{o.closeSync(t)}return r.digest("hex")}function md5File(e){return new Promise(((t,r)=>{const s=n.createHash("md5");const i=o.createReadStream(e);i.on("error",(e=>{r(e)}));s.once("readable",(()=>{t(s.read().toString("hex"))}));i.pipe(s)}))}e.exports=md5File;e.exports.sync=md5FileSync},1529:e=>{e.exports=Pager;function Pager(e,t){if(!(this instanceof Pager))return new Pager(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?alloc(this.deduplicate.length):null}Pager.prototype.updated=function(e){while(this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate]){e.deduplicate++;if(e.deduplicate===this.deduplicate.length){e.deduplicate=0;if(e.buffer.equals&&e.buffer.equals(this.deduplicate))e.buffer=this.deduplicate;break}}if(e.updated||!this.updates)return;e.updated=true;this.updates.push(e)};Pager.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();e.updated=false;return e};Pager.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;grow(this,e)}factor(e,this.path);var r=this.pages;for(var n=this.level;n>0;n--){var o=this.path[n];var s=r[o];if(!s){if(t)return;s=r[o]=new Array(32768)}r=s}return r};Pager.prototype.get=function(e,t){var r=this._array(e,t);var n=this.path[0];var o=r&&r[n];if(!o&&!t){o=r[n]=new Page(e,alloc(this.pageSize));if(e>=this.length)this.length=e+1}if(o&&o.buffer===this.deduplicate&&this.deduplicate&&!t){o.buffer=copy(o.buffer);o.deduplicate=0}return o};Pager.prototype.set=function(e,t){var r=this._array(e,false);var n=this.path[0];if(e>=this.length)this.length=e+1;if(!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=undefined;return}if(this.deduplicate&&t.equals&&t.equals(this.deduplicate)){t=this.deduplicate}var o=r[n];var s=truncate(t,this.pageSize);if(o)o.buffer=s;else r[n]=new Page(e,s)};Pager.prototype.toBuffer=function(){var e=new Array(this.length);var t=alloc(this.pageSize);var r=0;while(rt)return e.slice(0,t);var r=alloc(t);e.copy(r);return r}function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function copy(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);e.copy(t);return t}function Page(e,t){this.offset=e*t.length;this.buffer=t;this.updated=false;this.deduplicate=0}function factor(e,t){e=(e-(t[0]=e&32767))/32768;e=(e-(t[1]=e&32767))/32768;t[3]=(e-(t[2]=e&32767))/32768&32767}},3973:(e,t,r)=>{e.exports=minimatch;minimatch.Minimatch=Minimatch;var n=function(){try{return r(1017)}catch(e){}}()||{sep:"/"};minimatch.sep=n.sep;var o=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={};var s=r(3717);var i={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};var a="[^/]";var A=a+"*?";var c="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var l="(?:(?!(?:\\/|^)\\.).)*?";var u=charSet("().*{}+?[]^$\\!");function charSet(e){return e.split("").reduce((function(e,t){e[t]=true;return e}),{})}var h=/\/+/;minimatch.filter=filter;function filter(e,t){t=t||{};return function(r,n,o){return minimatch(r,e,t)}}function ext(e,t){t=t||{};var r={};Object.keys(e).forEach((function(t){r[t]=e[t]}));Object.keys(t).forEach((function(e){r[e]=t[e]}));return r}minimatch.defaults=function(e){if(!e||typeof e!=="object"||!Object.keys(e).length){return minimatch}var t=minimatch;var r=function minimatch(r,n,o){return t(r,n,ext(e,o))};r.Minimatch=function Minimatch(r,n){return new t.Minimatch(r,ext(e,n))};r.Minimatch.defaults=function defaults(r){return t.defaults(ext(e,r)).Minimatch};r.filter=function filter(r,n){return t.filter(r,ext(e,n))};r.defaults=function defaults(r){return t.defaults(ext(e,r))};r.makeRe=function makeRe(r,n){return t.makeRe(r,ext(e,n))};r.braceExpand=function braceExpand(r,n){return t.braceExpand(r,ext(e,n))};r.match=function(r,n,o){return t.match(r,n,ext(e,o))};return r};Minimatch.defaults=function(e){return minimatch.defaults(e).Minimatch};function minimatch(e,t,r){assertValidPattern(t);if(!r)r={};if(!r.nocomment&&t.charAt(0)==="#"){return false}return new Minimatch(t,r).match(e)}function Minimatch(e,t){if(!(this instanceof Minimatch)){return new Minimatch(e,t)}assertValidPattern(e);if(!t)t={};e=e.trim();if(!t.allowWindowsEscape&&n.sep!=="/"){e=e.split(n.sep).join("/")}this.options=t;this.set=[];this.pattern=e;this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.partial=!!t.partial;this.make()}Minimatch.prototype.debug=function(){};Minimatch.prototype.make=make;function make(){var e=this.pattern;var t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate();var r=this.globSet=this.braceExpand();if(t.debug)this.debug=function debug(){console.error.apply(console,arguments)};this.debug(this.pattern,r);r=this.globParts=r.map((function(e){return e.split(h)}));this.debug(this.pattern,r);r=r.map((function(e,t,r){return e.map(this.parse,this)}),this);this.debug(this.pattern,r);r=r.filter((function(e){return e.indexOf(false)===-1}));this.debug(this.pattern,r);this.set=r}Minimatch.prototype.parseNegate=parseNegate;function parseNegate(){var e=this.pattern;var t=false;var r=this.options;var n=0;if(r.nonegate)return;for(var o=0,s=e.length;od){throw new TypeError("pattern is too long")}};Minimatch.prototype.parse=parse;var g={};function parse(e,t){assertValidPattern(e);var r=this.options;if(e==="**"){if(!r.noglobstar)return o;else e="*"}if(e==="")return"";var n="";var s=!!r.nocase;var c=false;var l=[];var h=[];var d;var p=false;var E=-1;var m=-1;var C=e.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var I=this;function clearStateChar(){if(d){switch(d){case"*":n+=A;s=true;break;case"?":n+=a;s=true;break;default:n+="\\"+d;break}I.debug("clearStateChar %j %j",d,n);d=false}}for(var y=0,B=e.length,Q;y-1;D--){var N=h[D];var T=n.slice(0,N.reStart);var O=n.slice(N.reStart,N.reEnd-8);var _=n.slice(N.reEnd-8,N.reEnd);var M=n.slice(N.reEnd);_+=M;var L=T.split("(").length-1;var F=M;for(y=0;y=0;i--){s=e[i];if(s)break}for(i=0;i>> no match, partial?",e,u,t,h);if(u===a)return true}return false}var g;if(typeof c==="string"){g=l===c;this.debug("string match",c,l,g)}else{g=l.match(c);this.debug("pattern match",c,l,g)}if(!g)return false}if(s===a&&i===A){return true}else if(s===a){return r}else if(i===A){return s===a-1&&e[s]===""}throw new Error("wtf?")};function globUnescape(e){return e.replace(/\\(.)/g,"$1")}function regExpEscape(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},1257:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoMemoryServer=t.MongoMemoryServerStates=t.MongoMemoryServerEvents=void 0;const n=r(4351);const o=(0,n.__importStar)(r(8517));const s=(0,n.__importDefault)(r(3002));const i=r(1978);const a=r(843);const A=(0,n.__importDefault)(r(8237));const c=r(2361);const l=r(7147);const u=r(5517);const h=r(1383);const d=r(3386);const g=(0,A.default)("MongoMS:MongoMemoryServer");o.setGracefulCleanup();var p;(function(e){e["stateChange"]="stateChange"})(p=t.MongoMemoryServerEvents||(t.MongoMemoryServerEvents={}));var E;(function(e){e["new"]="new";e["starting"]="starting";e["running"]="running";e["stopped"]="stopped"})(E=t.MongoMemoryServerStates||(t.MongoMemoryServerStates={}));class MongoMemoryServer extends c.EventEmitter{constructor(e){super();this._state=E.new;this.opts=Object.assign({},e);if(!(0,i.isNullOrUndefined)(this.opts.auth)){this.auth=(0,i.authDefault)(this.opts.auth)}}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("create: Called .create() method");const t=new MongoMemoryServer(Object.assign({},e));yield t.start();return t}))}start(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start: Called .start() method");switch(this._state){case E.new:case E.stopped:break;case E.running:case E.starting:default:throw new d.StateError([E.new,E.stopped],this.state)}(0,i.assertion)((0,i.isNullOrUndefined)((t=this._instanceInfo)===null||t===void 0?void 0:t.instance.mongodProcess),new Error('Cannot start because "instance.mongodProcess" is already defined!'));this.stateChange(E.starting);yield this._startUpInstance(e).catch((e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!A.default.enabled("MongoMS:MongoMemoryServer")){console.warn("Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n",e)}this.debug("_startUpInstance threw a Error: ",e);yield this.stop({doCleanup:false,force:false});this.stateChange(E.stopped);throw e}))));this.stateChange(E.running);this.debug("start: Instance fully Started")}))}stateChange(e){this._state=e;this.emit(p.stateChange,e)}debug(e,...t){var r,n;const o=(n=(r=this._instanceInfo)===null||r===void 0?void 0:r.port)!==null&&n!==void 0?n:"unknown";g(`Mongo[${o}]: ${e}`,...t)}getNewPort(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield(0,s.default)({port:e});if(e!=t&&typeof e==="number"){this.debug(`getNewPort: starting with port "${t}", since "${e}" was locked`)}return t}))}getStartOptions(e=false){var t,r,s;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`getStartOptions: forceSamePort: ${e}`);const n=(t=this.opts.instance)!==null&&t!==void 0?t:{};let a=true;let A=typeof n.port==="number"?n.port:undefined;if(!e||(0,i.isNullOrUndefined)(A)){A=yield this.getNewPort(A)}const c={port:A,dbName:(0,i.generateDbName)(n.dbName),ip:(r=n.ip)!==null&&r!==void 0?r:"127.0.0.1",storageEngine:(s=n.storageEngine)!==null&&s!==void 0?s:"ephemeralForTest",replSet:n.replSet,dbPath:n.dbPath,tmpDir:undefined};if((0,i.isNullOrUndefined)(this._instanceInfo)){if(!c.dbPath){c.tmpDir=o.dirSync({mode:493,prefix:"mongo-mem-",unsafeCleanup:true});c.dbPath=c.tmpDir.name;a=true}else{this.debug(`getStartOptions: Checking if "${c.dbPath}}" (no new tmpDir) already has data`);const e=yield l.promises.readdir(c.dbPath);a=e.length===0}}else{a=false}const u=(typeof n.auth==="boolean"?n.auth:true)&&!(0,i.isNullOrUndefined)(this.auth)&&!this.auth.disable&&(this.auth.force||a)&&!n.replSet;return{data:c,createAuth:u,mongodOptions:{instance:Object.assign(Object.assign({},c),{args:n.args,auth:u?false:n.auth}),binary:this.opts.binary,spawn:this.opts.spawn}}}))}_startUpInstance(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("_startUpInstance: Called MongoMemoryServer._startUpInstance() method");if(!(0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');if(!e){const e=yield this.getNewPort(this._instanceInfo.port);this._instanceInfo.instance.instanceOpts.port=e;this._instanceInfo.port=e}yield this._instanceInfo.instance.start();return}const{mongodOptions:r,createAuth:n,data:o}=yield this.getStartOptions(e);this.debug(`_startUpInstance: Creating new MongoDB instance with options:`,r);const s=yield a.MongoInstance.create(r);this.debug(`_startUpInstance: Instance Started, createAuth: "${n}"`);if(!(0,i.isNullOrUndefined)(this.auth)&&n){this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);yield this.createAuth(o);if(o.storageEngine!=="ephemeralForTest"){this.debug("_startUpInstance: Killing No-Auth instance");yield s.stop();this.debug("_startUpInstance: Starting Auth Instance");s.instanceOpts.auth=true;yield s.start()}else{console.warn("Not Restarting MongoInstance for Auth\n"+'Storage engine is "ephemeralForTest", which does not write data on shutdown, and mongodb does not allow changing "auth" runtime')}}else{if((t=this.opts.auth)===null||t===void 0?void 0:t.disable){this.debug('_startUpInstance: AutomaticAuth.disable is set to "true" skipping "createAuth"')}}this._instanceInfo=Object.assign(Object.assign({},o),{dbPath:o.dbPath,instance:s})}))}stop(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop: Called .stop() method");let n={doCleanup:true,force:false};if(typeof e==="boolean"){n.doCleanup=e}if(typeof e==="object"){n=e}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('stop: "instanceInfo" is not defined (never ran?)');return false}if(this._state===E.stopped){this.debug('stop: state is "stopped", trying to stop / kill anyway')}this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${(r=(t=this._instanceInfo.instance)===null||t===void 0?void 0:t.mongodProcess)===null||r===void 0?void 0:r.pid}`);yield this._instanceInfo.instance.stop();this.stateChange(E.stopped);if(n.doCleanup){yield this.cleanup(n)}return true}))}cleanup(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){assertionIsMMSState(E.stopped,this.state);let t={doCleanup:true,force:false};if(typeof e==="boolean"){t.force=e}if(typeof e==="object"){t=e}this.debug(`cleanup:`,t);if(!t.doCleanup){this.debug('cleanup: "doCleanup" is set to false');return}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('cleanup: "instanceInfo" is undefined');return}(0,i.assertion)((0,i.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess),new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));const r=this._instanceInfo.tmpDir;if(!(0,i.isNullOrUndefined)(r)){this.debug(`cleanup: removing tmpDir at ${r.name}`);r.removeCallback()}if(t.force){const e=this._instanceInfo.dbPath;const t=yield(0,i.statPath)(e);if((0,i.isNullOrUndefined)(t)){this.debug(`cleanup: force is true, but path "${e}" dosnt exist anymore`)}else{(0,i.assertion)(t.isDirectory(),new Error("Defined dbPath is not an directory"));if((0,h.lt)(process.version,"14.14.0")){yield l.promises.rmdir(e,{recursive:true,maxRetries:1})}else{yield l.promises.rm(e,{recursive:true,maxRetries:1})}}}this.stateChange(E.new);this._instanceInfo=undefined}))}get instanceInfo(){return this._instanceInfo}get state(){return this._state}ensureInstance(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("ensureInstance: Called .ensureInstance() method");switch(this._state){case E.running:if(this._instanceInfo){return this._instanceInfo}throw new d.EnsureInstanceError(true);case E.new:case E.stopped:break;case E.starting:return new Promise(((e,t)=>this.once(p.stateChange,(r=>{if(r!=E.running){t(new Error(`"ensureInstance" waited for "running" but got an different state: "${r}"`));return}(0,i.assertion)(!(0,i.isNullOrUndefined)(this._instanceInfo),new Error("InstanceInfo is undefined!"));e(this._instanceInfo)}))));default:throw new d.StateError([E.running,E.new,E.stopped,E.starting],this.state)}this.debug('ensureInstance: no running instance, calling "start()" command');yield this.start();this.debug('ensureInstance: "start()" command was succesfully resolved');if(!this._instanceInfo){throw new d.EnsureInstanceError(false)}return this._instanceInfo}))}getUri(e,t){this.debug("getUri:",this.state,e,t);switch(this.state){case E.running:case E.starting:break;case E.stopped:default:throw new d.StateError([E.running,E.starting],this.state)}assertionInstanceInfo(this._instanceInfo);return(0,i.uriTemplate)(t||"127.0.0.1",this._instanceInfo.port,(0,i.generateDbName)(e))}createAuth(e){var t,r,o;return(0,n.__awaiter)(this,void 0,void 0,(function*(){(0,i.assertion)(!(0,i.isNullOrUndefined)(this.auth),new Error('"createAuth" got called, but "this.auth" is undefined!'));this.debug("createAuth: options:",this.auth);const n=yield u.MongoClient.connect((0,i.uriTemplate)(e.ip,e.port,"admin"),{});try{let e=n.db("admin");this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);yield e.command({createUser:this.auth.customRootName,pwd:this.auth.customRootPwd,mechanisms:["SCRAM-SHA-256"],customData:{createdBy:"mongodb-memory-server",as:"ROOTUSER"},roles:["root"],writeConcern:{w:"majority"}});if(this.auth.extraUsers.length>0){this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);this.auth.extraUsers.sort(((e,t)=>{if(e.database==="admin"){return-1}return e.database===t.database?0:1}));for(const s of this.auth.extraUsers){s.database=(0,i.isNullOrUndefined)(s.database)?"admin":s.database;if(s.database!==e.databaseName){e=n.db(s.database)}this.debug("createAuth: Creating User: ",s);yield e.command({createUser:s.createUser,pwd:s.pwd,customData:Object.assign(Object.assign({},s.customData),{createdBy:"mongodb-memory-server",as:"EXTRAUSER"}),roles:s.roles,authenticationRestrictions:(t=s.authenticationRestrictions)!==null&&t!==void 0?t:[],mechanisms:(r=s.mechanisms)!==null&&r!==void 0?r:["SCRAM-SHA-256"],digestPassword:(o=s.digestPassword)!==null&&o!==void 0?o:true})}}}finally{yield n.close()}}))}}t.MongoMemoryServer=MongoMemoryServer;t["default"]=MongoMemoryServer;function assertionInstanceInfo(e){(0,i.assertion)(!(0,i.isNullOrUndefined)(e),new Error('"instanceInfo" is undefined'))}function assertionIsMMSState(e,t){(0,i.assertion)(t===e,new d.StateError([e],t))}},8919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.DryMongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(8730);const i=r(1978);const a=(0,n.__importStar)(r(1017));const A=r(2037);const c=(0,n.__importDefault)(r(7281));const l=r(8278);const u=r(3386);const h=r(1);const d=(0,o.default)("MongoMS:DryMongoBinary");class DryMongoBinary{static locateBinary(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d(`locateBinary: Trying to locate Binary for version "${e.version}"`);const t=yield this.generateOptions(e);if(!!t.systemBinary){d(`locateBinary: env "SYSTEM_BINARY" was provided with value: "${t.systemBinary}"`);const e=yield this.getSystemPath(t.systemBinary);if((0,i.isNullOrUndefined)(e)){throw new u.NoSystemBinaryFoundError(t.systemBinary)}return e}if(this.binaryCache.has(e.version)){const t=this.binaryCache.get(e.version);d(`locateBinary: Requested Version found in cache: "[${e.version}, ${t}]"`);return t}d("locateBinary: running generateDownloadPath");const r=yield this.generateDownloadPath(t);if(!r[0]){d("locateBinary: could not find a existing binary");return undefined}d(`locateBinary: found binary at "${r[1]}"`);this.binaryCache.set(e.version,r[1]);return r[1]}))}static generateOptions(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generateOptions");const n=(t=(0,s.resolveConfig)(s.ResolveConfigVariables.VERSION))!==null&&t!==void 0?t:s.DEFAULT_VERSION;const o=(0,i.isNullOrUndefined)(e)?{version:n}:e;const c={version:o.version||n,downloadDir:(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR)||o.downloadDir||"",os:(r=o.os)!==null&&r!==void 0?r:yield(0,l.getOS)(),platform:o.platform||(0,A.platform)(),arch:o.arch||(0,A.arch)(),systemBinary:(0,s.resolveConfig)(s.ResolveConfigVariables.SYSTEM_BINARY)||o.systemBinary||""};c.downloadDir=a.dirname((yield this.generateDownloadPath(c))[1]);if((0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME)||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)||(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);d(`generateOptions: ARCHIVE_NAME or DOWNLOAD_URL defined, generating options based on that (input: "${e}")`);return this.parseArchiveNameRegex(e,c)}return c}))}static parseArchiveNameRegex(e,t){d(`parseArchiveNameRegex (input: "${e}")`);const r=/mongodb-(?linux|win32|osx|macos)(?:-ssl-|-)(?\w{4,})(?:-(?\w+)|)(?:-ssl-|-)(?:v|)(?[\d.]+(?:-latest|))\./gim.exec(e);(0,i.assertion)(!(0,i.isNullOrUndefined)(r),new u.NoRegexMatchError("input"));(0,i.assertion)(!(0,i.isNullOrUndefined)(r.groups),new u.NoRegexMatchError("input","groups"));const n=r.groups;(0,i.assertion)(typeof n.version==="string"&&n.version.length>1,new u.ParseArchiveRegexError("version"));(0,i.assertion)(typeof n.platform==="string"&&n.platform.length>1,new u.ParseArchiveRegexError("platform"));(0,i.assertion)(typeof n.arch==="string"&&n.arch.length>=4,new u.ParseArchiveRegexError("arch"));t.version=n.version;t.arch=n.arch;if(n.platform==="linux"){const e=!!n.dist?/([a-z]+)(\d*)/gim.exec(n.dist):null;t.os={os:"linux",dist:typeof(e===null||e===void 0?void 0:e[1])==="string"?e[1]:"unknown",release:""}}else{t.os={os:n.platform}}return t}static getBinaryName(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getBinaryName");let t;if((0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.USE_ARCHIVE_NAME_FOR_BINARY_NAME))){const r=yield new h.MongoBinaryDownloadUrl(e).getArchiveName();t=a.parse(r).name}else{const r=e.platform==="win32"?".exe":"";const n=(0,l.isLinuxOS)(e.os)?e.os.dist:e.os.os;t=`mongod-${e.arch}-${n}-${e.version}${r}`}return t}))}static combineBinaryName(e,t){d("combineBinaryName");return a.resolve(e,t)}static getSystemPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getSystempath");try{yield(0,i.checkBinaryPermissions)(e);d(`getSystemPath: found system binary path at "${e}"`);return e}catch(t){d(`getSystemPath: can't find system binary at "${e}".\n${t instanceof Error?t.message:t}`)}return undefined}))}static generatePaths(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generatePaths",e);const t={legacyHomeCache:"",modulesCache:"",relative:"",resolveConfig:""};const r=yield this.getBinaryName(e);let n=process.env["INIT_CWD"]||process.cwd();while(n.includes(`node_modules${a.sep}mongodb-memory-server`)){n=a.resolve(n,"..","..")}const o=(0,c.default)({name:"mongodb-memory-server",cwd:n});if(!(0,i.isNullOrUndefined)(o)){t.modulesCache=this.combineBinaryName(a.resolve(o),r)}const A=a.resolve(this.homedir(),".cache/mongodb-binaries");t.legacyHomeCache=this.combineBinaryName(A,r);const l=e.downloadDir||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR);if(!(0,i.isNullOrUndefined)(l)&&l.length>0){d(`generatePaths: resolveConfigValue is not empty`);t.resolveConfig=this.combineBinaryName(l,r)}t.relative=this.combineBinaryName(a.resolve(process.cwd(),"mongodb-binaries"),r);return t}))}static generateDownloadPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.PREFER_GLOBAL_PATH));d(`generateDownloadPath: Generating Download Path, preferGlobal: "${t}"`);const r=yield this.generatePaths(e);d("generateDownloadPath: Paths:",r,e.systemBinary);if(!!e.systemBinary&&(yield(0,i.pathExists)(e.systemBinary))){const t=yield this.getSystemPath(e.systemBinary);if(!(0,i.isNullOrUndefined)(t)){return[true,t]}}if(yield(0,i.pathExists)(r.resolveConfig)){d(`generateDownloadPath: Found binary in resolveConfig (DOWNLOAD_DIR): "${r.resolveConfig}"`);return[true,r.resolveConfig]}if(yield(0,i.pathExists)(r.legacyHomeCache)){d(`generateDownloadPath: Found binary in legacyHomeCache: "${r.legacyHomeCache}"`);return[true,r.legacyHomeCache]}if(yield(0,i.pathExists)(r.modulesCache)){d(`generateDownloadPath: Found binary in modulesCache: "${r.modulesCache}"`);return[true,r.modulesCache]}if(yield(0,i.pathExists)(r.relative)){d(`generateDownloadPath: Found binary in relative: "${r.relative}"`);return[true,r.relative]}d(`generateDownloadPath: no existing binary for version "${e.version}" was found`);if(r.resolveConfig.length>0){d(`generateDownloadPath: using resolveConfig (DOWNLOAD_DIR) "${r.resolveConfig}"`);return[false,r.resolveConfig]}if(t&&!!r.legacyHomeCache){d(`generateDownloadPath: using global (preferGlobal) "${r.legacyHomeCache}"`);return[false,r.legacyHomeCache]}if(r.modulesCache.length>0){d(`generateDownloadPath: using modulesCache "${r.modulesCache}"`);return[false,r.modulesCache]}d(`generateDownloadPath: using relative "${r.relative}"`);return[false,r.relative]}))}static homedir(){return(0,A.homedir)()}}t.DryMongoBinary=DryMongoBinary;DryMongoBinary.binaryCache=new Map},9125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=(0,n.__importDefault)(r(1017));const i=(0,n.__importDefault)(r(229));const a=(0,n.__importStar)(r(8730));const A=(0,n.__importDefault)(r(8237));const c=(0,n.__importStar)(r(1383));const l=r(1978);const u=r(2081);const h=r(4908);const d=r(8919);const g=(0,A.default)("MongoMS:MongoBinary");class MongoBinary{static download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("download");const{downloadDir:t,version:r}=e;yield(0,l.mkdir)(t);const n=s.default.resolve(t,`${r}.lock`);g(`download: Waiting to acquire Download lock for file "${n}"`);const o=yield h.LockFile.lock(n);g("download: Download lock acquired");try{if(!d.DryMongoBinary.binaryCache.has(r)){g(`download: Adding version ${r} to cache`);const t=new i.default(e);d.DryMongoBinary.binaryCache.set(r,yield t.getMongodPath())}}finally{g("download: Removing Download lock");yield o.unlock();g("download: Download lock removed")}const a=d.DryMongoBinary.binaryCache.get(r);(0,l.assertion)(typeof a==="string",new Error(`No Cache Path for version "${r}" found (and download failed silently?)`));return a}))}static getPath(e={}){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("getPath");const t=Object.assign(Object.assign({},yield d.DryMongoBinary.generateOptions(e)),{platform:e.platform||(0,a.default)(a.ResolveConfigVariables.PLATFORM)||o.default.platform(),checkMD5:e.checkMD5||(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.MD5_CHECK))});g(`getPath: MongoBinary options:`,JSON.stringify(t,null,2));let r=yield d.DryMongoBinary.locateBinary(t);if(!!t.systemBinary){if(!(0,l.isNullOrUndefined)(r)){g(`getPath: Spawning binaryPath "${r}" to get version`);const e=(0,u.spawnSync)(r,["--version"]).stdout.toString().match(/^\s*db\s+version\s+v?(\d+\.\d+\.\d+)(-\d*)?(-[a-zA-Z0-9].*)?\s*$/im);(0,l.assertion)(!(0,l.isNullOrUndefined)(e),new Error("Couldnt find an version from system binary output!"));if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.SYSTEM_BINARY_VERSION_CHECK))){g("getPath: Checking & Warning about version conflicts");const r=e[1];if(c.neq(t.version,r)){console.warn("getPath: MongoMemoryServer: Possible version conflict\n"+` SystemBinary version: "${r}"\n`+` Requested version: "${t.version}"\n\n`+" Using SystemBinary!")}}}else{throw new Error('Option "SYSTEM_BINARY" was set, but binaryPath was empty! (system binary could not be found?) [This Error should normally not be thrown, please report this]')}}(0,l.assertion)(typeof t.version==="string",new Error('"MongoBinary.options.version" is not an string!'));if(!r){if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD))){g('getPath: "RUNTIME_DOWNLOAD" is "true", trying to download');r=yield this.download(t)}else{g('getPath: "RUNTIME_DOWNLOAD" is "false", not downloading')}}if(!r){const e=(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD));throw new Error(`MongoBinary.getPath: could not find an valid binary path! (Got: "${r}", RUNTIME_DOWNLOAD: "${e}")`)}g(`getPath: Mongod binary path: "${r}"`);return r}))}}t.MongoBinary=MongoBinary;t["default"]=MongoBinary},229:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownload=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=r(7310);const i=(0,n.__importDefault)(r(1017));const a=r(7147);const A=(0,n.__importDefault)(r(1446));const c=(0,n.__importDefault)(r(5687));const l=r(9796);const u=(0,n.__importDefault)(r(2283));const h=(0,n.__importDefault)(r(8781));const d=(0,n.__importDefault)(r(1));const g=r(7219);const p=(0,n.__importStar)(r(8730));const E=(0,n.__importDefault)(r(8237));const m=r(1978);const C=r(8919);const I=r(4521);const y=r(3386);const B=(0,E.default)("MongoMS:MongoBinaryDownload");class MongoBinaryDownload{constructor(e){var t,r,n,s,i,a;(0,m.assertion)(typeof e.downloadDir==="string",new Error("An DownloadDir must be specified!"));const A=(t=e.version)!==null&&t!==void 0?t:(0,p.default)(p.ResolveConfigVariables.VERSION);(0,m.assertion)(typeof A==="string",new Error("An MongoDB Binary version must be specified!"));this.binaryOpts={platform:(r=e.platform)!==null&&r!==void 0?r:o.default.platform(),arch:(n=e.arch)!==null&&n!==void 0?n:o.default.arch(),version:A,downloadDir:e.downloadDir,checkMD5:(s=e.checkMD5)!==null&&s!==void 0?s:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.MD5_CHECK)),systemBinary:(i=e.systemBinary)!==null&&i!==void 0?i:"",os:(a=e.os)!==null&&a!==void 0?a:{os:"unknown"}};this.dlProgress={current:0,length:0,totalMb:0,lastPrintedAt:0}}get checkMD5(){return this.binaryOpts.checkMD5}set checkMD5(e){this.binaryOpts.checkMD5=e}get downloadDir(){return this.binaryOpts.downloadDir}set downloadDir(e){this.binaryOpts.downloadDir=e}get arch(){return this.binaryOpts.arch}set arch(e){this.binaryOpts.arch=e}get version(){return this.binaryOpts.version}set version(e){this.binaryOpts.version=e}get platform(){return this.binaryOpts.platform}set platform(e){this.binaryOpts.platform=e}getPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield C.DryMongoBinary.generateOptions(this.binaryOpts);return C.DryMongoBinary.combineBinaryName(this.downloadDir,yield C.DryMongoBinary.getBinaryName(e))}))}getMongodPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("getMongodPath");const e=yield this.getPath();if(yield(0,m.pathExists)(e)){B(`getMongodPath: mongod path "${e}" already exists, using this`);return e}const t=yield this.startDownload();yield this.extract(t);yield a.promises.unlink(t);if(yield(0,m.pathExists)(e)){return e}throw new Error(`Cannot find downloaded mongod binary by path "${e}"`)}))}startDownload(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("startDownload");const e=new d.default(this.binaryOpts);yield(0,m.mkdir)(this.downloadDir);try{yield a.promises.access(this.downloadDir,a.constants.X_OK|a.constants.W_OK)}catch(e){console.error(`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n`+"Needed Permissions: Write & Execute (-wx)\n");throw e}const t=yield e.getDownloadUrl();const r=yield this.download(t);yield this.makeMD5check(`${t}.md5`,r);return r}))}makeMD5check(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("makeMD5check: Checking MD5 of downloaded binary...");if(!this.checkMD5){B("makeMD5check: checkMD5 is disabled");return undefined}const r=yield this.download(e);const n=(yield a.promises.readFile(r)).toString("utf-8");const o=n.match(/^\s*([\w\d]+)\s*/i);const s=o?o[1]:null;const i=A.default.sync(t);B(`makeMD5check: Local MD5: ${i}, Remote MD5: ${s}`);if(s!==i){throw new y.Md5CheckFailedError(i,s||"unknown")}yield a.promises.unlink(r);return true}))}download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("download");const t=process.env["yarn_https-proxy"]||process.env.yarn_proxy||process.env["npm_config_https-proxy"]||process.env.npm_config_proxy||process.env.https_proxy||process.env.http_proxy||process.env.HTTPS_PROXY||process.env.HTTP_PROXY;const r=process.env.npm_config_strict_ssl==="true";const n=new s.URL(e);n.port=n.port||"443";const o={method:"GET",rejectUnauthorized:r,protocol:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.USE_HTTP))?"http:":"https:",agent:t?new g.HttpsProxyAgent(t):undefined};const a=n.pathname.split("/").pop();if(!a){throw new Error(`MongoBinaryDownload: missing filename for url "${e}"`)}const A=i.default.resolve(this.downloadDir,a);const c=i.default.resolve(this.downloadDir,`${a}.downloading`);B(`download: Downloading${t?` via proxy "${t}"`:""}: "${e}"`);if(yield(0,m.pathExists)(A)){B("download: Already downloaded archive found, skipping download");return A}this.assignDownloadingURL(n);const l=yield this.httpDownload(n,o,A,c);return l}))}extract(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extract");const n=yield this.getPath();B(`extract: archive: "${e}" final: "${n}"`);yield(0,m.mkdir)(i.default.dirname(n));const filter=e=>/(?:bin\/(?:mongod(?:\.exe)?)|(?:.*\.dll))$/i.test(e);if(/(.tar.gz|.tgz)$/.test(e)){yield this.extractTarGz(e,n,filter)}else if(/.zip$/.test(e)){yield this.extractZip(e,n,filter)}else{throw new Error(`MongoBinaryDownload: unsupported archive "${e}" (downloaded from "${(t=this._downloadingUrl)!==null&&t!==void 0?t:"unknown"}"). Broken archive from MongoDB Provider?`)}if(!(yield(0,m.pathExists)(n))){throw new Error(`MongoBinaryDownload: missing mongod binary in "${e}" (downloaded from "${(r=this._downloadingUrl)!==null&&r!==void 0?r:"unknown"}"). Broken archive from MongoDB Provider?`)}return n}))}extractTarGz(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractTarGz");const n=u.default.extract();n.on("entry",((e,n,o)=>{if(r(e.name)){n.pipe((0,a.createWriteStream)(t,{mode:509}))}n.on("end",(()=>o()));n.resume()}));return new Promise(((t,r)=>{(0,a.createReadStream)(e).on("error",(t=>{r("Unable to open tarball "+e+": "+t)})).pipe((0,l.createUnzip)()).on("error",(t=>{r("Error during unzip for "+e+": "+t)})).pipe(n).on("error",(t=>{r("Error during untar for "+e+": "+t)})).on("finish",(e=>{t(e)}))}))}))}extractZip(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractZip");return new Promise(((n,o)=>{h.default.open(e,{lazyEntries:true},((e,s)=>{if(e||!s){return o(e)}s.readEntry();s.on("end",(()=>n()));s.on("entry",(e=>{if(!r(e.fileName)){return s.readEntry()}s.openReadStream(e,((e,r)=>{if(e||!r){return o(e)}r.on("end",(()=>s.readEntry()));r.pipe((0,a.createWriteStream)(t,{mode:509}))}))}))}))}))}))}httpDownload(e,t,r,o){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("httpDownload");const s=this.assignDownloadingURL(e);return new Promise(((i,A)=>{B(`httpDownload: trying to download "${s}"`);c.default.get(e,t,(e=>{if(e.statusCode!=200){if(e.statusCode===403){A(new Error("Status Code is 403 (MongoDB's 404)\n"+"This means that the requested version-platform combination doesn't exist\n"+` Used Url: "${s}"\n`+"Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n"+"List of available versions can be found here:\n"+" https://www.mongodb.org/dl/linux for Linux\n"+" https://www.mongodb.org/dl/osx for OSX\n"+" https://www.mongodb.org/dl/win32 for Windows"));return}A(new Error("Status Code isnt 200!"));return}if(typeof e.headers["content-length"]!="string"){A(new Error('Response header "content-length" is empty!'));return}this.dlProgress.current=0;this.dlProgress.length=parseInt(e.headers["content-length"],10);this.dlProgress.totalMb=Math.round(this.dlProgress.length/1048576*10)/10;const c=(0,a.createWriteStream)(o);e.pipe(c);c.on("finish",(()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){var e;if(this.dlProgress.current{this.printDownloadProgress(e)}))})).on("error",(e=>{console.error(`Couldnt download "${s}"!`,e.message);A(e)}))}))}))}printDownloadProgress(e,t=false){this.dlProgress.current+=e.length;const r=Date.now();if(r-this.dlProgress.lastPrintedAt<2e3&&!t){return}this.dlProgress.lastPrintedAt=r;const n=Math.round(100*this.dlProgress.current/this.dlProgress.length*10)/10;const o=Math.round(this.dlProgress.current/1048576*10)/10;const s=this.platform==="win32"?"":"\r";const i=`Downloading MongoDB "${this.version}": ${n}% (${o}mb / ${this.dlProgress.totalMb}mb)${s}`;if(process.stdout.isTTY){(0,I.clearLine)(process.stdout,0);process.stdout.write(i)}else{console.log(i)}}assignDownloadingURL(e){this._downloadingUrl=e.href;return this._downloadingUrl}}t.MongoBinaryDownload=MongoBinaryDownload;t["default"]=MongoBinaryDownload},1:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownloadUrl=void 0;const n=r(4351);const o=r(8278);const s=r(8730);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1383));const A=r(1978);const c=r(7310);const l=r(3386);const u=r(3837);const h=(0,i.default)("MongoMS:MongoBinaryDownloadUrl");class MongoBinaryDownloadUrl{constructor(e){this.version=e.version;this.platform=this.translatePlatform(e.platform);this.arch=MongoBinaryDownloadUrl.translateArch(e.arch,this.platform);this.os=e.os}getDownloadUrl(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL);if(t){h(`Using "${t}" as the Download-URL`);const e=new c.URL(t);return e.toString()}const r=yield this.getArchiveName();h(`Using "${r}" as the Archive String`);const n=(e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_MIRROR))!==null&&e!==void 0?e:"https://fastdl.mongodb.org";h(`Using "${n}" as the mirror`);const o=new c.URL(n);if(!o.pathname.endsWith("/")){o.pathname=o.pathname+"/"}o.pathname=`${o.pathname}${this.platform}/${r}`;return o.toString()}))}getArchiveName(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);if(!!e){return e}switch(this.platform){case"osx":return this.getArchiveNameOsx();case"win32":case"windows":return this.getArchiveNameWin();case"linux":return this.getArchiveNameLinux();default:throw new l.UnknownPlatformError(this.platform)}}))}getArchiveNameWin(){let e=`mongodb-${this.platform}-${this.arch}`;if(!(0,A.isNullOrUndefined)(a.coerce(this.version))){if(a.satisfies(this.version,"4.2.x")){e+="-2012plus"}else if(a.lt(this.version,"4.1.0")){e+="-2008plus-ssl"}}e+=`-${this.version}.zip`;return e}getArchiveNameOsx(){let e=`mongodb-osx`;const t=a.coerce(this.version);if(!(0,A.isNullOrUndefined)(t)&&a.gte(t,"3.2.0")){e+="-ssl"}if((0,A.isNullOrUndefined)(t)||a.gte(t,"4.2.0")){e=`mongodb-macos`}if(this.arch==="arm64"){h('getArchiveNameOsx: Arch is "arm64", using x64 binary');this.arch="x86_64"}e+=`-${this.arch}-${this.version}.tgz`;return e}getArchiveNameLinux(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){let e;if(this.arch!=="i686"){if(!this.os){this.os=yield(0,o.getOS)()}e=this.getLinuxOSVersionString(this.os)}let t=`mongodb-linux-${this.arch}`;if(!!e){t+=`-${e}`}t+=`-${this.version}.tgz`;return t}))}getLinuxOSVersionString(e){var t;if(regexHelper(/ubuntu/i,e)){return this.getUbuntuVersionString(e)}else if(regexHelper(/amzn/i,e)){return this.getAmazonVersionString(e)}else if(regexHelper(/suse/i,e)){return this.getSuseVersionString(e)}else if(regexHelper(/(rhel|centos|scientific)/i,e)){return this.getRhelVersionString(e)}else if(regexHelper(/fedora/i,e)){return this.getFedoraVersionString(e)}else if(regexHelper(/debian/i,e)){return this.getDebianVersionString(e)}else if(regexHelper(/alpine/i,e)){console.warn("There is no offical build of MongoDB for Alpine!")}else if(regexHelper(/(arch|manjaro|arco)(?:linux)?$/i,e)){console.warn(`There is no official build of MongoDB for ArchLinux (${e.dist}). Falling back to Ubuntu 20.04 release.`);return this.getUbuntuVersionString({os:"linux",dist:"Ubuntu Linux",release:"20.04"})}else if(regexHelper(/gentoo/i,e)){console.warn(`There is no official build of MongoDB for Gentoo (${e.dist}). Falling back to Debian.`);return this.getDebianVersionString({os:"linux",dist:"Debian",release:"11"})}else if(regexHelper(/unknown/i,e)){console.warn("Couldnt parse dist information, please report this to https://github.com/nodkz/mongodb-memory-server/issues")}console.warn(`Unknown/unsupported linux "${e.dist}(${(t=e.id_like)===null||t===void 0?void 0:t.join(", ")})". Falling back to legacy MongoDB build!`);return this.getLegacyVersionString()}getDebianVersionString(e){let t="debian";const r=parseFloat(e.release);if(r>=11||["unstable","testing"].includes(e.release)){if(a.lt(this.version,"5.0.8")){h("debian11 detected, but version below 5.0.8 requested, using debian10");t+="10"}else{t+="11"}}else if(r>=10){t+="10"}else if(r>=9){t+="92"}else if(r>=8.1){t+="81"}else if(r>=7.1){t+="71"}if(r>=10){if(a.lt(this.version,"4.2.1")){throw new l.KnownVersionIncompatibilityError(`Debian ${r}`,this.version,">=4.2.1","Mongodb does not provide binaries for versions before 4.2.1 for Debian 10+ and also cannot be mapped to a previous Debian release")}}return t}getFedoraVersionString(e){let t="rhel";const r=parseInt(e.release,10);if(r>=34){t+="80"}if(r<34&&r>=19){t+="70"}if(r<19&&r>=12){t+="62"}if(r<12&&r>=6){t+="55"}return t}getRhelVersionString(e){let t="rhel";const{release:r}=e;if(r){if(/^8/.test(r)){t+="80"}else if(/^7/.test(r)){t+="70"}else if(/^6/.test(r)){t+="62"}else if(/^5/.test(r)){t+="55"}}if(t==="rhel"){h('getRhelVersionString: falling back to "70"');t+="70"}return t}getAmazonVersionString(e){let t="amazon";const r=parseInt(e.release,10);if(r>=2&&r<=3){t+="2"}return t}getLegacyVersionString(){return""}getSuseVersionString(e){const t=e.release.match(/(^11|^12|^15)/);return t?`suse${t[0]}`:""}getUbuntuVersionString(e){let t=undefined;{if(/^linux\s?mint\s*$/i.test(e.dist)){const r={17:"14.04",18:"16.04",19:"18.04",20:"20.04"};t={os:"linux",dist:"ubuntu",release:r[parseInt(e.release.split(".")[0])]||r[20]}}if(/^elementary\s?os\s*$/i.test(e.dist)){const r={3:"14.04",4:"16.04",5:"18.04",6:"20.04"};const[n,o]=e.release.split(".").map((e=>parseInt(e)));const s=n||o;t={os:"linux",dist:"ubuntu",release:r[s]||r[6]}}}if((0,A.isNullOrUndefined)(t)){if(!/^ubuntu(?:| linux)\s*$/i.test(e.dist)){console.warn(`Unmapped distro "${e.dist}" with ID_LIKE "ubuntu", defaulting to highest ubuntu version!\n`+'This means that your distro does not have a internal mapping in MMS or does not have a upstream release file (like "/etc/upstream-release/lsb-release"), but has set a ID_LIKE');t={os:"linux",dist:"ubuntu",release:"20.04"}}else{t=e}}const r=parseInt(t.release.split(".")[0],10);if(this.arch==="arm64"){if(a.satisfies(this.version,"<4.1.10")){this.arch="arm64";return"ubuntu1604"}if(a.satisfies(this.version,">=4.1.10")){this.arch="aarch64";if(a.satisfies(this.version,"<4.4.0")){return"ubuntu1804"}return`ubuntu${r||18}04`}}if(t.release==="14.10"){return"ubuntu1410-clang"}if(r>=18&&a.satisfies(this.version,"3.x.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an 3.x.x version, defaulting to "1604"`);return"ubuntu1604"}if(r>18&&a.satisfies(this.version,"<=4.3.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an "<=4.3.x" version, defaulting to "1804"`);return"ubuntu1804"}if(r>=21){return"ubuntu2004"}return`ubuntu${r||14}04`}translatePlatform(e){switch(e){case"darwin":return"osx";case"win32":const t=a.coerce(this.version);if((0,A.isNullOrUndefined)(t)){return"windows"}return a.gte(t,"4.3.0")?"windows":"win32";case"linux":case"elementary OS":return"linux";case"sunos":return"sunos5";default:throw new l.UnknownPlatformError(e)}}static translateArch(e,t){switch(e){case"ia32":(0,u.deprecate)((()=>{}),"mongodb-memory-server will fully drop support for ia32 in 9.0","MMS001")();if(t==="linux"){return"i686"}else if(t==="win32"){return"i386"}throw new l.UnknownArchitectureError(e,t);case"x86_64":case"x64":return"x86_64";case"arm64":return"arm64";case"aarch64":return"aarch64";default:throw new l.UnknownArchitectureError(e)}}}t.MongoBinaryDownloadUrl=MongoBinaryDownloadUrl;t["default"]=MongoBinaryDownloadUrl;function regexHelper(e,t){return e.test(t.dist)||(!(0,A.isNullOrUndefined)(t.id_like)?t.id_like.filter((t=>e.test(t))).length>=1:false)}},843:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoInstance=t.MongoInstanceEvents=void 0;const n=r(4351);const o=r(2081);const s=(0,n.__importStar)(r(1017));const i=r(9125);const a=(0,n.__importDefault)(r(8237));const A=r(1978);const c=r(1383);const l=r(2361);const u=r(5517);const h=r(3386);if((0,c.lt)(process.version,"12.22.0")){console.warn("Using NodeJS below 12.22.0")}const d=(0,a.default)("MongoMS:MongoInstance");var g;(function(e){e["instanceReplState"]="instanceReplState";e["instancePrimary"]="instancePrimary";e["instanceReady"]="instanceReady";e["instanceSTDOUT"]="instanceSTDOUT";e["instanceSTDERR"]="instanceSTDERR";e["instanceClosed"]="instanceClosed";e["instanceRawError"]="instanceRawError";e["instanceError"]="instanceError";e["killerLaunched"]="killerLaunched";e["instanceLaunched"]="instanceLaunched";e["instanceStarted"]="instanceStarted"})(g=t.MongoInstanceEvents||(t.MongoInstanceEvents={}));class MongoInstance extends l.EventEmitter{constructor(e){super();this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;this.instanceOpts=Object.assign({},e.instance);this.binaryOpts=Object.assign({},e.binary);this.spawnOpts=Object.assign({},e.spawn);this.on(g.instanceReady,(()=>{this.isInstanceReady=true;this.debug("constructor: Instance is ready!")}));this.on(g.instanceError,(e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`constructor: Instance has thrown an Error: ${e.toString()}`);this.isInstanceReady=false;this.isInstancePrimary=false;yield this.stop()}))))}debug(e,...t){var r;const n=(r=this.instanceOpts.port)!==null&&r!==void 0?r:"unknown";d(`Mongo[${n}]: ${e}`,...t)}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("create: Called .create() method");const t=new this(e);yield t.start();return t}))}prepareCommandArgs(){var e;this.debug("prepareCommandArgs");(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.port),new Error('"instanceOpts.port" is required to be set!'));(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.dbPath),new Error('"instanceOpts.dbPath" is required to be set!'));const t=[];t.push("--port",this.instanceOpts.port.toString());t.push("--dbpath",this.instanceOpts.dbPath);if(!!this.instanceOpts.replSet){this.isReplSet=true;t.push("--replSet",this.instanceOpts.replSet)}if(!!this.instanceOpts.storageEngine){t.push("--storageEngine",this.instanceOpts.storageEngine)}if(!!this.instanceOpts.ip){t.push("--bind_ip",this.instanceOpts.ip)}if(this.instanceOpts.auth){t.push("--auth");if(this.isReplSet){(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.keyfileLocation),new h.KeyFileMissingError);t.push("--keyFile",this.instanceOpts.keyfileLocation)}}else{t.push("--noauth")}const r=t.concat((e=this.instanceOpts.args)!==null&&e!==void 0?e:[]);this.debug("prepareCommandArgs: final argument array:"+JSON.stringify(r));return r}start(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start");this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;const e=new Promise(((e,t)=>{this.once(g.instanceReady,e);this.once(g.instanceError,t);this.once(g.instanceClosed,(()=>{t(new Error("Instance Exited before being ready and without throwing an error!"))}))}));const t=yield i.MongoBinary.getPath(this.binaryOpts);yield(0,A.checkBinaryPermissions)(t);this.debug("start: Starting Processes");this.mongodProcess=this._launchMongod(t);(0,A.assertion)(!(0,A.isNullOrUndefined)(this.mongodProcess.pid),new Error("MongoD Process failed to spawn"));this.killerProcess=this._launchKiller(process.pid,this.mongodProcess.pid);yield e;this.emit(g.instanceStarted);this.debug("start: Processes Started")}))}stop(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop");if(!this.mongodProcess&&!this.killerProcess){this.debug("stop: nothing to shutdown, returning");return false}if(!(0,A.isNullOrUndefined)(this.mongodProcess)){if(this.isReplSet){let e;try{this.debug("stop: trying shutdownServer");const t=this.instanceOpts.port;const r=this.instanceOpts.ip;(0,A.assertion)(!(0,A.isNullOrUndefined)(t),new Error('Cannot shutdown replset gracefully, no "port" is provided'));(0,A.assertion)(!(0,A.isNullOrUndefined)(r),new Error('Cannot shutdown replset gracefully, no "ip" is provided'));e=yield u.MongoClient.connect((0,A.uriTemplate)(r,t,"admin"),Object.assign(Object.assign({},this.extraConnectionOptions),{directConnection:true}));const n=e.db("admin");yield n.command({shutdown:1,force:true,timeoutSecs:1});this.debug("stop: after admin shutdown command")}catch(e){if(!(e instanceof u.MongoNetworkError&&/^connection \d+ to [\d.]+:\d+ closed$/i.test(e.message))){console.warn(e)}}finally{if(!(0,A.isNullOrUndefined)(e)){yield e.close()}}}yield(0,A.killProcess)(this.mongodProcess,"mongodProcess",this.instanceOpts.port);this.mongodProcess=undefined}else{this.debug("stop: mongodProcess: nothing to shutdown, skipping")}if(!(0,A.isNullOrUndefined)(this.killerProcess)){yield(0,A.killProcess)(this.killerProcess,"killerProcess",this.instanceOpts.port);this.killerProcess=undefined}else{this.debug("stop: killerProcess: nothing to shutdown, skipping")}this.debug("stop: Instance Finished Shutdown");return true}))}_launchMongod(e){var t,r;this.debug("_launchMongod: Launching Mongod Process");const n=(0,o.spawn)(s.resolve(e),this.prepareCommandArgs(),Object.assign(Object.assign({},this.spawnOpts),{stdio:"pipe"}));(t=n.stderr)===null||t===void 0?void 0:t.on("data",this.stderrHandler.bind(this));(r=n.stdout)===null||r===void 0?void 0:r.on("data",this.stdoutHandler.bind(this));n.on("close",this.closeHandler.bind(this));n.on("error",this.errorHandler.bind(this));if((0,A.isNullOrUndefined)(n.pid)){throw new h.StartBinaryFailedError(s.resolve(e))}this.emit(g.instanceLaunched);return n}_launchKiller(e,t){this.debug(`_launchKiller: Launching Killer Process (parent: ${e}, child: ${t})`);const r=(0,o.fork)(s.resolve(__dirname,"../../scripts/mongo_killer.js"),[e.toString(),t.toString()],{detached:true,stdio:"ignore"});r.unref();this.emit(g.killerLaunched);return r}errorHandler(e){this.emit(g.instanceRawError,e);this.emit(g.instanceError,e)}closeHandler(e,t){if(process.platform==="win32"&&e!=12&&e!=0||e!=0){this.debug("closeHandler: Mongod instance closed with an non-0 (or non 12 on windows) code!")}this.debug(`closeHandler: "${e}" "${t}"`);this.emit(g.instanceClosed,e,t)}stderrHandler(e){const t=e.toString().trim();this.debug(`stderrHandler: ""${t}""`);this.emit(g.instanceSTDERR,t);this.checkErrorInLine(t)}stdoutHandler(e){var t,r;const n=e.toString().trim();this.debug(`stdoutHandler: ""${n}""`);this.emit(g.instanceSTDOUT,n);if(/waiting for connections/i.test(n)){this.emit(g.instanceReady)}this.checkErrorInLine(n);if(/transition to \w+ from \w+/i.test(n)){const e=(r=(t=/transition to (\w+) from \w+/i.exec(n))===null||t===void 0?void 0:t[1])!==null&&r!==void 0?r:"UNKNOWN";this.emit(g.instanceReplState,e);if(e!=="PRIMARY"){this.isInstancePrimary=false}}if(/transition to primary complete; database writes are now permitted/i.test(n)){this.isInstancePrimary=true;this.debug('stdoutHandler: emitting "instancePrimary"');this.emit(g.instancePrimary)}}checkErrorInLine(e){var t,r;if(/address already in use/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError(`Port "${this.instanceOpts.port}" already in use`))}if(/exception in initAndListen: \w+[^:]: .+[^,], terminating/i.test(e)){const t=/exception in initAndListen: (\w+[^:]): (.+[^,]), terminating/i.exec(e);const{1:r,2:n}=t||[];this.emit(g.instanceError,new h.StdoutInstanceError(`Instance Failed to start with "${r}". Original Error:\n`+n))}if(/CURL_OPENSSL_3['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You should manually install libcurl3 or try to use an newer version of MongoDB"))}if(/CURL_OPENSSL_4['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl4 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You need to manually install libcurl4"))}if(/lib[^:]+(?=: cannot open shared object)/i.test(e)){const n=(r=(t=e.match(/(lib[^:]+)(?=: cannot open shared object)/i))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown";this.emit(g.instanceError,new h.StdoutInstanceError(`Instance failed to start because a library is missing or cannot be opened: "${n}"`))}if(/\*\*\*aborting after/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("Mongod internal error"))}}}t.MongoInstance=MongoInstance;t["default"]=MongoInstance},3386:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.StdoutInstanceError=t.KnownVersionIncompatibilityError=t.NoRegexMatchError=t.ParseArchiveRegexError=t.ReplsetCountLowError=t.AssertionFallbackError=t.BinaryNotFoundError=t.InsufficientPermissionsError=t.AuthNotObjectError=t.KeyFileMissingError=t.InstanceInfoError=t.StartBinaryFailedError=t.Md5CheckFailedError=t.NoSystemBinaryFoundError=t.EnsureInstanceError=t.WaitForPrimaryTimeoutError=t.UnknownArchitectureError=t.UnknownPlatformError=t.UnableToUnlockLockfileError=t.UnknownLockfileStatusError=t.StateError=void 0;const n=r(1978);class StateError extends Error{constructor(e,t){super(`Incorrect State for operation: "${t}", allowed States: "[${e.join(",")}]"\n`+"This may be because of using a v6.x way of calling functions, look at the following guide if anything applies:\n"+"https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7#no-function-other-than-start-create-ensureinstance-will-be-starting-anything");this.wantedStates=e;this.gotState=t}}t.StateError=StateError;class UnknownLockfileStatusError extends Error{constructor(e){super(`Unknown LockFile Status: "${e}"`);this.status=e}}t.UnknownLockfileStatusError=UnknownLockfileStatusError;class UnableToUnlockLockfileError extends Error{constructor(e,t){super(`Cannot unlock file "${t}", because it is not locked by this ${e?"instance":"process"}`);this.thisInstance=e;this.file=t}}t.UnableToUnlockLockfileError=UnableToUnlockLockfileError;class UnknownPlatformError extends Error{constructor(e){super(`Unknown Platform: "${e}"`);this.platform=e}}t.UnknownPlatformError=UnknownPlatformError;class UnknownArchitectureError extends Error{constructor(e,t){super();this.arch=e;this.platform=t;if(!(0,n.isNullOrUndefined)(t)){this.message=`Unsupported Architecture-Platform combination: arch: "${e}", platform: "${t}"`}else{this.message=`Unsupported Architecture: "${e}"`}}}t.UnknownArchitectureError=UnknownArchitectureError;class WaitForPrimaryTimeoutError extends Error{constructor(e,t){super(`Timed out after ${e}ms while waiting for a Primary (where: "${t}")`);this.timeout=e;this.where=t}}t.WaitForPrimaryTimeoutError=WaitForPrimaryTimeoutError;class EnsureInstanceError extends Error{constructor(e){super();this.isRunning=e;const t='"ensureInstance" failed, because';if(e){this.message=`${t} state was "running" but "instanceInfo" was undefined!`}else{this.message=`${t} "instanceInfo" was undefined after running "start"`}}}t.EnsureInstanceError=EnsureInstanceError;class NoSystemBinaryFoundError extends Error{constructor(e){super(`Config option "SYSTEM_BINARY" was provided with value "${e}", but no binary could be found!`);this.binaryPath=e}}t.NoSystemBinaryFoundError=NoSystemBinaryFoundError;class Md5CheckFailedError extends Error{constructor(e,t){super(`MD5 check failed! Binary MD5 is "${e}", Checkfile MD5 is "${t}"`);this.binarymd5=e;this.checkfilemd5=t}}t.Md5CheckFailedError=Md5CheckFailedError;class StartBinaryFailedError extends Error{constructor(e){super(`Starting the Binary Failed (PID is undefined)! Binary: "${e}"`);this.binary=e}}t.StartBinaryFailedError=StartBinaryFailedError;class InstanceInfoError extends Error{constructor(e){super(`"instanceInfo" was undefined when expected to be defined! (where: "${e}")`);this.where=e}}t.InstanceInfoError=InstanceInfoError;class KeyFileMissingError extends Error{constructor(){super(`"keyfileLocation" was undefined when expected!`)}}t.KeyFileMissingError=KeyFileMissingError;class AuthNotObjectError extends Error{constructor(){super('"auth" was not a object when it was expected!')}}t.AuthNotObjectError=AuthNotObjectError;class InsufficientPermissionsError extends Error{constructor(e){super(`File "${e}" does not have the required Permissions, required Permissions: "--x"`);this.path=e}}t.InsufficientPermissionsError=InsufficientPermissionsError;class BinaryNotFoundError extends Error{constructor(e){super(`No Binary at path "${e}" was found! (ENOENT)`);this.path=e}}t.BinaryNotFoundError=BinaryNotFoundError;class AssertionFallbackError extends Error{constructor(){super("Assert failed - no custom error")}}t.AssertionFallbackError=AssertionFallbackError;class ReplsetCountLowError extends Error{constructor(e){super(`ReplSet Count needs to be 1 or higher! (specified count: "${e}")`);this.count=e}}t.ReplsetCountLowError=ReplsetCountLowError;class ParseArchiveRegexError extends Error{constructor(e){super(`Expected "${e}" to be found in regex groups`);this.key=e}}t.ParseArchiveRegexError=ParseArchiveRegexError;class NoRegexMatchError extends Error{constructor(e,t){super();this.name=e;this.extra=t;const r=!!t?`(${t})`:"";this.message=`Expected "${e}" to have Regex Matches${r}`}}t.NoRegexMatchError=NoRegexMatchError;class KnownVersionIncompatibilityError extends Error{constructor(e,t,r,n){super();this.dist=e;this.requested_version=t;this.available_versions=r;this.extra=n;const o=!!n?`\n${n}`:"";this.message=`Requested Version "${t}" is not available for "${e}"! Available Versions: "${r}"${o}`}}t.KnownVersionIncompatibilityError=KnownVersionIncompatibilityError;class StdoutInstanceError extends Error{constructor(e){super(e)}}t.StdoutInstanceError=StdoutInstanceError},8278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.parseOS=t.parseLSB=t.getOS=t.isLinuxOS=void 0;const n=r(4351);const o=r(2037);const s=(0,n.__importDefault)(r(8237));const i=r(1978);const a=(0,s.default)("MongoMS:getos");const A={name:/^(?:distributor id:|DISTRIB_ID=)\s*(.*)$/im,codename:/^(?:codename:|DISTRIB_CODENAME=)\s*(.*)$/im,release:/^(?:release:|DISTRIB_RELEASE=)\s*(.*)$/im};const c={name:/^id\s*=\s*"?(\w*)"?$/im,codename:/^version_codename\s*=\s*(.*)$/im,release:/^version_id\s*=\s*"?(\d*(?:\.\d*)?)"?$/im,id_like:/^id_like\s*=\s*"?([\w\s]*)"?$/im};function isLinuxOS(e){return e.os==="linux"}t.isLinuxOS=isLinuxOS;let l;function getOS(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!l){const e=(0,o.platform)();if(e==="linux"){l=yield getLinuxInformation()}else{l={os:e}}}return l}))}t.getOS=getOS;function getLinuxInformation(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield(0,i.tryReleaseFile)("/etc/upstream-release/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(e)){a("getLinuxInformation: Using UpstreamLSB");return e}const t=yield(0,i.tryReleaseFile)("/etc/os-release",parseOS);if(!(0,i.isNullOrUndefined)(t)){a("getLinuxInformation: Using etcOsRelease");return t}const r=yield(0,i.tryReleaseFile)("/usr/lib/os-release",parseOS);if(!(0,i.isNullOrUndefined)(r)){a("getLinuxInformation: Using usrOsRelease");return r}const n=yield(0,i.tryReleaseFile)("/etc/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(n)){a("getLinuxInformation: Using etcLSBRelease");return n}console.warn("Could not find any Release File, using fallback binary");return{os:"linux",dist:"unknown",release:""}}))}function parseLSB(e){var t,r,n,o,s;return{os:"linux",dist:(r=(t=e.match(A.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(A.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(A.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:""}}t.parseLSB=parseLSB;function parseOS(e){var t,r,n,o,s,i;return{os:"linux",dist:(r=(t=e.match(c.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(c.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(c.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:"",id_like:(i=e.match(c.id_like))===null||i===void 0?void 0:i[1].toLocaleLowerCase().split(" ")}}t.parseOS=parseOS},4908:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.LockFile=t.LockFileEvents=t.LockFileStatus=void 0;const n=r(4351);const o=r(2361);const s=(0,n.__importStar)(r(1978));const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(4038);const l=r(5840);const u=r(3386);const h=(0,i.default)("MongoMS:LockFile");class RepeatError extends Error{constructor(e){super();this.repeat=e}}var d;(function(e){e[e["available"]=0]="available";e[e["availableInstance"]=1]="availableInstance";e[e["lockedSelf"]=2]="lockedSelf";e[e["lockedDifferent"]=3]="lockedDifferent"})(d=t.LockFileStatus||(t.LockFileStatus={}));var g;(function(e){e["lock"]="lock";e["unlock"]="unlock"})(g=t.LockFileEvents||(t.LockFileEvents={}));class LockFileEventsClass extends o.EventEmitter{}class LockFile{constructor(e,t){this.file=e;this.uuid=t}static lock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`lock: Locking file "${e}"`);const t=a.resolve(e.trim());s.assertion(t.length>0,new Error("Provided Path for lock file is length of 0"));const r=yield this.checkLock(t);switch(r){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(t);case d.available:return this.createLock(t);default:throw new u.UnknownLockfileStatusError(r)}}))}static checkLock(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`checkLock: for file "${e}" with uuid: "${t}"`);if(!(yield s.pathExists(e))){return d.available}try{const r=(yield A.promises.readFile(e)).toString().trim().split(" ");const n=parseInt(r[0]);if(n===process.pid){h(`checkLock: Lock File Already exists, and is for *this* process, with uuid: "${r[1]}"`);if(!this.files.has(e)){return d.available}if(!s.isNullOrUndefined(t)){return t===r[1]?d.availableInstance:d.lockedSelf}return d.lockedSelf}h(`checkLock: Lock File Aready exists, for a different process: "${n}"`);return s.isAlive(n)?d.lockedDifferent:d.available}catch(e){if(s.errorWithCode(e)&&e.code==="ENOENT"){h("checkLock: reading file failed with ENOENT");return d.available}throw e}}))}static waitForLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`waitForLock: Starting to wait for file "${e}"`);let t=undefined;let r=undefined;yield new Promise((o=>{r=t=>{if(t===e){o()}};t=setInterval((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.checkLock(e);h(`waitForLock: Interval for file "${e}" with status "${t}"`);if(t===d.available){o()}}))),1e3*3);this.events.on(g.unlock,r)}));if(t){clearInterval(t)}if(r){this.events.removeListener(g.unlock,r)}h(`waitForLock: File became available "${e}"`);yield s.ensureAsync();const o=yield this.checkLock(e);h(`waitForLock: Lock File Status reassessment for file "${e}": ${o}`);switch(o){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(e);case d.available:return this.createLock(e);default:throw new u.UnknownLockfileStatusError(o)}}))}static createLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`createLock: trying to create a lock file for "${e}"`);const t=(0,l.v4)();try{yield this.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(this.files.has(e)){h(`createLock: Map already has file "${e}"`);throw new RepeatError(true)}yield s.mkdir(a.dirname(e));yield A.promises.writeFile(e,`${process.pid.toString()} ${t}`);this.files.add(e);this.events.emit(g.lock,e)}))))}catch(t){if(t instanceof RepeatError&&t.repeat){return this.waitForLock(e)}}h(`createLock: Lock File Created for file "${e}"`);return new this(e,t)}))}unlock(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`unlock: Unlocking file "${this.file}"`);if(s.isNullOrUndefined(this.file)||((e=this.file)===null||e===void 0?void 0:e.length)<=0){h("unlock: invalid file, returning");return}switch(yield LockFile.checkLock(this.file,this.uuid)){case d.available:h(`unlock: Lock Status was already "available" for file "${this.file}"`);yield this.unlockCleanup(false);return;case d.availableInstance:h(`unlock: Lock Status was "availableInstance" for file "${this.file}"`);yield this.unlockCleanup(true);return;case d.lockedSelf:throw new u.UnableToUnlockLockfileError(true,this.file);default:throw new u.UnableToUnlockLockfileError(false,this.file)}}))}unlockCleanup(e=true){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return yield LockFile.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`unlockCleanup: for file "${this.file}"`);if(s.isNullOrUndefined(this.file)){return}if(e){yield A.promises.unlink(this.file).catch((e=>{h(`unlockCleanup: lock file unlink failed: "${e}"`)}))}LockFile.files.delete(this.file);LockFile.events.emit(g.unlock,this.file);this.file=undefined;this.uuid=undefined}))))}))}}t.LockFile=LockFile;LockFile.files=new Set;LockFile.events=new LockFileEventsClass;LockFile.mutex=new c.Mutex},8730:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.envToBool=t.envName=t.resolveConfig=t.processConfigOption=t.findPackageJson=t.setDefaultValue=t.defaultValues=t.DEFAULT_VERSION=t.ENV_CONFIG_PREFIX=t.ResolveConfigVariables=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(1362));const s=r(1156);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(1978);const l=(0,i.default)("MongoMS:ResolveConfig");var u;(function(e){e["DOWNLOAD_DIR"]="DOWNLOAD_DIR";e["PLATFORM"]="PLATFORM";e["ARCH"]="ARCH";e["VERSION"]="VERSION";e["DEBUG"]="DEBUG";e["DOWNLOAD_MIRROR"]="DOWNLOAD_MIRROR";e["DOWNLOAD_URL"]="DOWNLOAD_URL";e["PREFER_GLOBAL_PATH"]="PREFER_GLOBAL_PATH";e["DISABLE_POSTINSTALL"]="DISABLE_POSTINSTALL";e["SYSTEM_BINARY"]="SYSTEM_BINARY";e["MD5_CHECK"]="MD5_CHECK";e["ARCHIVE_NAME"]="ARCHIVE_NAME";e["RUNTIME_DOWNLOAD"]="RUNTIME_DOWNLOAD";e["USE_HTTP"]="USE_HTTP";e["SYSTEM_BINARY_VERSION_CHECK"]="SYSTEM_BINARY_VERSION_CHECK";e["USE_ARCHIVE_NAME_FOR_BINARY_NAME"]="USE_ARCHIVE_NAME_FOR_BINARY_NAME"})(u=t.ResolveConfigVariables||(t.ResolveConfigVariables={}));t.ENV_CONFIG_PREFIX="MONGOMS_";t.DEFAULT_VERSION="5.0.8";t.defaultValues=new Map([[u.VERSION,t.DEFAULT_VERSION],[u.PREFER_GLOBAL_PATH,"true"],[u.RUNTIME_DOWNLOAD,"true"],[u.USE_HTTP,"false"],[u.SYSTEM_BINARY_VERSION_CHECK,"true"],[u.USE_ARCHIVE_NAME_FOR_BINARY_NAME,"false"]]);function setDefaultValue(e,r){t.defaultValues.set(e,r)}t.setDefaultValue=setDefaultValue;let h=undefined;function findPackageJson(e){var t;for(const r of(0,s.findSync)(e||process.cwd())){l(`findPackageJson: Found package.json at "${r}"`);const e=JSON.parse((0,A.readFileSync)(r).toString());const n=(t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.mongodbMemoryServer;if(!(0,c.isNullOrUndefined)(n)&&Object.keys(n!==null&&n!==void 0?n:{}).length>0){l(`findPackageJson: Found package with non-empty config field at "${r}"`);const e=a.dirname(r);h={filePath:e,config:processConfigOption(n,e)};break}}return h}t.findPackageJson=findPackageJson;function processConfigOption(e,t){l("processConfigOption",e,t);if(typeof e!=="object"){l("processConfigOptions: input was not a object");return{}}const r=e;const n=(0,o.default)(u.DOWNLOAD_DIR);const s=(0,o.default)(u.SYSTEM_BINARY);if(n in r){r[n]=a.resolve(t,r[n])}if(s in r){r[s]=a.resolve(t,r[s])}return r}t.processConfigOption=processConfigOption;function resolveConfig(e){var r,n,s;return(s=(n=(r=process.env[envName(e)])!==null&&r!==void 0?r:h===null||h===void 0?void 0:h.config[(0,o.default)(e)])!==null&&n!==void 0?n:t.defaultValues.get(e))===null||s===void 0?void 0:s.toString()}t.resolveConfig=resolveConfig;t["default"]=resolveConfig;function envName(e){return`${t.ENV_CONFIG_PREFIX}${e}`}t.envName=envName;function envToBool(e=""){if(typeof e!=="string"){l("envToBool: input was not a string!");return false}return["1","on","yes","true"].indexOf(e.toLowerCase())!==-1}t.envToBool=envToBool;if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through Environment Variable")}findPackageJson();if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through package.json")}},1978:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mkdir=t.checkBinaryPermissions=t.ManagerAdvanced=t.ManagerBase=t.tryReleaseFile=t.pathExists=t.statPath=t.authDefault=t.ensureAsync=t.isAlive=t.killProcess=t.assertion=t.isNullOrUndefined=t.uriTemplate=t.getHost=t.generateDbName=t.errorWithCode=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(7147);const i=r(3386);const a=(0,o.default)("MongoMS:utils");function errorWithCode(e){return e instanceof Error&&"code"in e}t.errorWithCode=errorWithCode;function generateDbName(e){return e||""}t.generateDbName=generateDbName;function getHost(e){return e.replace(/(?:^mongodb:\/{2})|(?:\/.*$)|(?:.*@)/gim,"")}t.getHost=getHost;function uriTemplate(e,t,r,n){const o=!isNullOrUndefined(t)?`${e}:${t}`:e;return`mongodb://${o}/${r}`+(!isNullOrUndefined(n)?`?${n.join("&")}`:"")}t.uriTemplate=uriTemplate;function isNullOrUndefined(e){return e===null||e===undefined}t.isNullOrUndefined=isNullOrUndefined;function assertion(e,t){if(!e){throw t!==null&&t!==void 0?t:new i.AssertionFallbackError}}t.assertion=assertion;function killProcess(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){function ilog(e){a(`Mongo[${r||"unknown"}] killProcess: ${e}`)}if(!isAlive(e.pid)){ilog("given childProcess's PID was not alive anymore");return}const n=1e3*10;yield new Promise(((r,s)=>{let i=setTimeout((()=>{ilog("killProcess: timeout triggered, trying SIGKILL");if(!o.default.enabled("MongoMS:utils")){console.warn('An Process didnt exit with signal "SIGINT" within 10 seconds, using "SIGKILL"!\n'+"Enable debug logs for more information")}e.kill("SIGKILL");i=setTimeout((()=>{ilog("killProcess: timeout triggered again, rejecting");s(new Error(`Process "${t}" didnt exit, enable debug for more information.`))}),n)}),n);e.once(`exit`,((e,n)=>{ilog(`killProcess: ${t}: got exit signal, Code: ${e}, Signal: ${n}`);clearTimeout(i);r()}));ilog(`killProcess: ${t}: sending "SIGINT"`);e.kill("SIGINT")}))}))}t.killProcess=killProcess;function isAlive(e){if(isNullOrUndefined(e)){return false}try{process.kill(e,0);return true}catch(e){return false}}t.isAlive=isAlive;function ensureAsync(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return new Promise((e=>process.nextTick(e)))}))}t.ensureAsync=ensureAsync;function authDefault(e){return Object.assign({force:false,disable:false,customRootName:"mongodb-memory-server-root",customRootPwd:"rootuser",extraUsers:[],keyfileContent:"0123456789"},e)}t.authDefault=authDefault;function statPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(["ENOENT","EACCES"].includes(e.code)){return undefined}throw e}))}))}t.statPath=statPath;function pathExists(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return!isNullOrUndefined(yield statPath(e))}))}t.pathExists=pathExists;function tryReleaseFile(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{const r=yield s.promises.readFile(e);return t(r.toString())}catch(t){if(errorWithCode(t)&&!["ENOENT","EACCES"].includes(t.code)){throw t}a(`tryReleaseFile: "${e}" does not exist`);return undefined}}))}t.tryReleaseFile=tryReleaseFile;class ManagerBase{}t.ManagerBase=ManagerBase;class ManagerAdvanced extends ManagerBase{}t.ManagerAdvanced=ManagerAdvanced;function checkBinaryPermissions(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{yield s.promises.access(e,s.constants.X_OK)}catch(t){if(errorWithCode(t)){if(t.code==="EACCES"){throw new i.InsufficientPermissionsError(e)}if(t.code==="ENOENT"){throw new i.BinaryNotFoundError(e)}}throw t}}))}t.checkBinaryPermissions=checkBinaryPermissions;function mkdir(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.promises.mkdir(e,{recursive:true})}))}t.mkdir=mkdir},5517:(e,t,r)=>{"use strict";const n=r(3994);const o=r(2138);const s=r(1545).connect;s.MongoError=n.MongoError;s.MongoNetworkError=n.MongoNetworkError;s.MongoTimeoutError=n.MongoTimeoutError;s.MongoServerSelectionError=n.MongoServerSelectionError;s.MongoParseError=n.MongoParseError;s.MongoWriteConcernError=n.MongoWriteConcernError;s.MongoBulkWriteError=r(4239).BulkWriteError;s.BulkWriteError=s.MongoBulkWriteError;s.ServerApiVersion=n.ServerApiVersion;s.Admin=r(3238);s.MongoClient=r(1545);s.Db=r(6662);s.Collection=r(5193);s.Server=r(8421);s.ReplSet=r(382);s.Mongos=r(2048);s.ReadPreference=n.ReadPreference;s.GridStore=r(9406);s.Chunk=r(3890);s.Logger=n.Logger;s.AggregationCursor=r(7429);s.CommandCursor=r(538);s.Cursor=r(7159);s.GridFSBucket=r(2573);s.CoreServer=n.Server;s.CoreConnection=n.Connection;s.Binary=n.BSON.Binary;s.Code=n.BSON.Code;s.Map=n.BSON.Map;s.DBRef=n.BSON.DBRef;s.Double=n.BSON.Double;s.Int32=n.BSON.Int32;s.Long=n.BSON.Long;s.MinKey=n.BSON.MinKey;s.MaxKey=n.BSON.MaxKey;s.ObjectID=n.BSON.ObjectID;s.ObjectId=n.BSON.ObjectID;s.Symbol=n.BSON.Symbol;s.Timestamp=n.BSON.Timestamp;s.BSONRegExp=n.BSON.BSONRegExp;s.Decimal128=n.BSON.Decimal128;s.connect=s;s.instrument=function(e,t){if(typeof e==="function"){t=e;e={}}const r=new o;r.instrument(s.MongoClient,t);return r};e.exports=s},3238:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(7057);const s=r(1681);const i=r(1969);const a=r(9263);const A=r(9929);const c=r(2548);function Admin(e,t,r){if(!(this instanceof Admin))return new Admin(e,t);this.s={db:e,topology:t,promiseLibrary:r}}Admin.prototype.command=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():{};const o=new s(this.s.db,e,t);return c(this.s.db.s.topology,o,r)};Admin.prototype.buildInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{serverStatus:1},e);return c(this.s.db.s.topology,r,t)};Admin.prototype.ping=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={ping:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.addUser=function(e,t,r,s){const i=Array.prototype.slice.call(arguments,2);s=typeof i[i.length-1]==="function"?i.pop():undefined;if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}r=i.length?i.shift():{};r=Object.assign({},r);r=n(r,{db:this.s.db});r.dbName="admin";const a=new o(this.s.db,e,t,r);return c(this.s.db.s.topology,a,s)};Admin.prototype.removeUser=function(e,t,r){const o=Array.prototype.slice.call(arguments,1);r=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():{};t=Object.assign({},t);t=n(t,{db:this.s.db});t.dbName="admin";const s=new i(this.s.db,e,t);return c(this.s.db.s.topology,s,r)};Admin.prototype.validateCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new a(this,e,t);return c(this.s.db.s.topology,n,r)};Admin.prototype.listDatabases=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return c(this.s.db.s.topology,new A(this.s.db,e),t)};Admin.prototype.replSetGetStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{replSetGetStatus:1},e);return c(this.s.db.s.topology,r,t)};e.exports=Admin},7429:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(7159);const s=r(4847).CursorState;class AggregationCursor extends o{constructor(e,t,r){super(e,t,r)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead()){throw n.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw n.create({message:"batchSize requires an integer",driver:true})}this.operation.options.batchSize=e;this.setCursorBatchSize(e);return this}geoNear(e){this.operation.addToPipeline({$geoNear:e});return this}group(e){this.operation.addToPipeline({$group:e});return this}limit(e){this.operation.addToPipeline({$limit:e});return this}match(e){this.operation.addToPipeline({$match:e});return this}maxTimeMS(e){this.operation.options.maxTimeMS=e;return this}out(e){this.operation.addToPipeline({$out:e});return this}project(e){this.operation.addToPipeline({$project:e});return this}lookup(e){this.operation.addToPipeline({$lookup:e});return this}redact(e){this.operation.addToPipeline({$redact:e});return this}skip(e){this.operation.addToPipeline({$skip:e});return this}sort(e){this.operation.addToPipeline({$sort:e});return this}unwind(e){this.operation.addToPipeline({$unwind:e});return this}getLogger(){return this.logger}}AggregationCursor.prototype.get=AggregationCursor.prototype.toArray;e.exports=AggregationCursor},2138:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;class Instrumentation extends n{constructor(){super()}instrument(e,t){this.$MongoClient=e;const r=this.$prototypeConnect=e.prototype.connect;const n=this;e.prototype.connect=function(e){this.s.options.monitorCommands=true;this.on("commandStarted",(e=>n.emit("started",e)));this.on("commandSucceeded",(e=>n.emit("succeeded",e)));this.on("commandFailed",(e=>n.emit("failed",e)));return r.call(this,e)};if(typeof t==="function")t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}e.exports=Instrumentation},1749:(e,t)=>{"use strict";function asyncIterator(){const e=this;return{next:function(){return Promise.resolve().then((()=>e.next())).then((t=>{if(!t){return e.close().then((()=>({value:t,done:true})))}return{value:t,done:false}}))}}}t.asyncIterator=asyncIterator},4239:(e,t,r)=>{"use strict";const n=r(3994).BSON.Long;const o=r(3994).MongoError;const s=r(3994).BSON.ObjectID;const i=r(3994).BSON;const a=r(3994).MongoWriteConcernError;const A=r(1371).emitWarningOnce;const c=r(1371).toError;const l=r(1371).handleCallback;const u=r(1371).applyRetryableWrites;const h=r(1371).applyWriteConcern;const d=r(1371).executeLegacyOperation;const g=r(1371).isPromiseLike;const p=r(1371).hasAtomicOperators;const E=r(1178).maxWireVersion;const m=64;const C=1;const I=2;const y=3;const B=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 Batch{constructor(e,t){this.originalZeroIndex=t;this.currentIndex=0;this.originalIndexes=[];this.batchType=e;this.operations=[];this.size=0;this.sizeBytes=0}}const Q=Symbol("upsertedIds");const b=Symbol("insertedIds");class BulkWriteResult{constructor(e){this.result=e;this[Q]=undefined;this[b]=undefined}get insertedCount(){return typeof this.result.nInserted!=="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!=="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!=="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!=="number"?0:this.result.nRemoved}get upsertedCount(){return!this.result.upserted?0:this.result.upserted.length}get upsertedIds(){if(this[Q]){return this[Q]}this[Q]={};for(const e of this.result.upserted||[]){this[Q][e.index]=e._id}return this[Q]}get insertedIds(){if(this[b]){return this[b]}this[b]={};for(const e of this.result.insertedIds||[]){this[b][e.index]=e._id}return this[b]}get n(){return this.result.insertedCount}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){if(ee.multi))}if(e.batch.batchType===y){r.retryWrites=r.retryWrites&&!e.batch.operations.some((e=>e.limit===0))}}try{if(e.batch.batchType===C){this.s.topology.insert(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===I){this.s.topology.update(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===y){this.s.topology.remove(this.s.namespace,e.batch.operations,r,e.resultHandler)}}catch(r){r.ok=0;l(t,null,mergeBatchResults(e.batch,this.s.bulkResult,r,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const r=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";l(e,new BulkWriteError(c({message:r,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null);return true}if(t.getWriteConcernError()){l(e,new BulkWriteError(c(t.getWriteConcernError()),t),null);return true}}}Object.defineProperty(BulkOperationBase.prototype,"length",{enumerable:true,get:function(){return this.s.currentIndex}});e.exports={Batch:Batch,BulkOperationBase:BulkOperationBase,mergeBatchResults:mergeBatchResults,bson:B,INSERT:C,UPDATE:I,REMOVE:y,BulkWriteError:BulkWriteError,BulkWriteResult:BulkWriteResult}},5035:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);const a=e.s.maxKeySize;if(e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+a+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}if(t===n.INSERT){e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id})}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentBatch.operations.push(r);e.s.currentBatchSize+=1;e.s.currentBatchSizeBytes+=a+o;e.s.currentIndex+=1;return e}class OrderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,true)}}function initializeOrderedBulkOp(e,t,r){return new OrderedBulkOperation(e,t,r)}initializeOrderedBulkOp.OrderedBulkOperation=OrderedBulkOperation;e.exports=initializeOrderedBulkOp;e.exports.Bulk=OrderedBulkOperation},325:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null;if(t===n.INSERT){e.s.currentBatch=e.s.currentInsertBatch}else if(t===n.UPDATE){e.s.currentBatch=e.s.currentUpdateBatch}else if(t===n.REMOVE){e.s.currentBatch=e.s.currentRemoveBatch}const a=e.s.maxKeySize;if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);if(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+a+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)}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.operations.push(r);e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentIndex=e.s.currentIndex+1;if(t===n.INSERT){e.s.currentInsertBatch=e.s.currentBatch;e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})}else if(t===n.UPDATE){e.s.currentUpdateBatch=e.s.currentBatch}else if(t===n.REMOVE){e.s.currentRemoveBatch=e.s.currentBatch}e.s.currentBatch.size+=1;e.s.currentBatch.sizeBytes+=a+o;return e}class UnorderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,false)}handleWriteError(e,t){if(this.s.batches.length){return false}return super.handleWriteError(e,t)}}function initializeUnorderedBulkOp(e,t,r){return new UnorderedBulkOperation(e,t,r)}initializeUnorderedBulkOp.UnorderedBulkOperation=UnorderedBulkOperation;e.exports=initializeUnorderedBulkOp;e.exports.Bulk=UnorderedBulkOperation},1117:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(9386).isResumableError;const i=r(3994).MongoError;const a=r(7159);const A=r(1178).relayEvents;const c=r(1178).maxWireVersion;const l=r(1371).maybePromise;const u=r(1371).now;const h=r(1371).calculateDurationInMs;const d=r(1554);const g=Symbol("resumeQueue");const p=["resumeAfter","startAfter","startAtOperationTime","fullDocument"];const E=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(p);const m={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class ChangeStream extends o{constructor(e,t,o){super();const s=r(5193);const i=r(6662);const a=r(1545);this.pipeline=t||[];this.options=o||{};this.parent=e;this.namespace=e.s.namespace;if(e instanceof s){this.type=m.COLLECTION;this.topology=e.s.db.serverConfig}else if(e instanceof i){this.type=m.DATABASE;this.topology=e.serverConfig}else if(e instanceof a){this.type=m.CLUSTER;this.topology=e.topology}else{throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient")}this.promiseLibrary=e.s.promiseLibrary;if(!this.options.readPreference&&e.s.readPreference){this.options.readPreference=e.s.readPreference}this[g]=new n;this.cursor=createChangeStreamCursor(this,o);this.closed=false;this.on("newListener",(e=>{if(e==="change"&&this.cursor&&this.listenerCount("change")===0){this.cursor.on("data",(e=>processNewChange(this,e)))}}));this.on("removeListener",(e=>{if(e==="change"&&this.listenerCount("change")===0&&this.cursor){this.cursor.removeAllListeners("data")}}))}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.hasNext(e)}))}))}next(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.next(((t,r)=>{if(t){this[g].push((()=>this.next(e)));processError(this,t,e);return}processNewChange(this,r,e)}))}))}))}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,(e=>{if(this.closed)return e();this.closed=true;if(!this.cursor)return e();const t=this.cursor;return t.close((r=>{["data","close","end","error"].forEach((e=>t.removeAllListeners(e)));this.cursor=undefined;return e(r)}))}))}pipe(e,t){if(!this.pipeDestinations){this.pipeDestinations=[]}this.pipeDestinations.push(e);return this.cursor.pipe(e,t)}unpipe(e){if(this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1){this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1)}return this.cursor.unpipe(e)}stream(e){this.streamOptions=e;return this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}class ChangeStreamCursor extends a{constructor(e,t,r){super(e,t,r);r=r||{};this._resumeToken=null;this.startAtOperationTime=r.startAtOperationTime;if(r.startAfter){this.resumeToken=r.startAfter}else if(r.resumeAfter){this.resumeToken=r.resumeAfter}}set resumeToken(e){this._resumeToken=e;this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of E){if(this.options[t])e[t]=this.options[t]}if(this.resumeToken||this.startAtOperationTime){["resumeAfter","startAfter","startAtOperationTime"].forEach((t=>delete e[t]));if(this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else if(this.startAtOperationTime&&c(this.server)>=7){e.startAtOperationTime=this.startAtOperationTime}}return e}cacheResumeToken(e){if(this.bufferedCount()===0&&this.cursorState.postBatchResumeToken){this.resumeToken=this.cursorState.postBatchResumeToken}else{this.resumeToken=e}this.hasReceived=true}_processBatch(e,t){const r=t.cursor;if(r.postBatchResumeToken){this.cursorState.postBatchResumeToken=r.postBatchResumeToken;if(r[e].length===0){this.resumeToken=r.postBatchResumeToken}}}_initializeCursor(e){super._initializeCursor(((t,r)=>{if(t||r==null){e(t,r);return}const n=r.documents[0];if(this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&c(this.server)>=7){this.startAtOperationTime=n.operationTime}this._processBatch("firstBatch",n);this.emit("init",r);this.emit("response");e(t,r)}))}_getMore(e){super._getMore(((t,r)=>{if(t){e(t);return}this._processBatch("nextBatch",r);this.emit("more",r);this.emit("response");e(t,r)}))}}function createChangeStreamCursor(e,t){const r={fullDocument:t.fullDocument||"default"};applyKnownOptions(r,t,p);if(e.type===m.CLUSTER){r.allChangesForCluster=true}const n=[{$changeStream:r}].concat(e.pipeline);const o=applyKnownOptions({},t,E);const s=new ChangeStreamCursor(e.topology,new d(e.parent,n,t),o);A(s,e,["resumeTokenChanged","end","close"]);if(e.listenerCount("change")>0){s.on("data",(function(t){processNewChange(e,t)}))}s.on("error",(function(t){processError(e,t)}));if(e.pipeDestinations){const t=s.stream(e.streamOptions);for(let r of e.pipeDestinations){t.pipe(r)}}return s}function applyKnownOptions(e,t,r){r.forEach((r=>{if(t[r]){e[r]=t[r]}}));return e}const C=3e4;function waitForTopologyConnected(e,t,r){setTimeout((()=>{if(t&&t.start==null){t.start=u()}const n=t.start||u();const o=t.timeout||C;const s=t.readPreference;if(e.isConnected({readPreference:s})){return r()}if(h(n)>o){return r(new i("Timed out waiting for connection"))}waitForTopologyConnected(e,t,r)}),500)}function processNewChange(e,t,r){const n=e.cursor;if(t==null){e.closed=true}if(e.closed){if(r)r(new i("ChangeStream is closed"));return}if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");if(!r)return e.emit("error",t);return r(t)}n.cacheResumeToken(t._id);e.options.startAtOperationTime=undefined;if(!r)return e.emit("change",t);return r(undefined,t)}function processError(e,t,r){const n=e.topology;const o=e.cursor;if(e.closed){if(r)r(new i("ChangeStream is closed"));return}function resumeWithCursor(t){e.cursor=t;processResumeQueue(e)}function unresumableError(t){if(!r){e.emit("error",t);e.emit("close")}processResumeQueue(e,t);e.closed=true}if(o&&s(t,c(o.server))){e.cursor=undefined;["data","close","end","error"].forEach((e=>o.removeAllListeners(e)));o.close();waitForTopologyConnected(n,{readPreference:o.options.readPreference},(t=>{if(t)return unresumableError(t);const n=createChangeStreamCursor(e,o.resumeOptions);if(!r)return resumeWithCursor(n);n.hasNext((e=>{if(e)return unresumableError(e);resumeWithCursor(n)}))}));return}if(!r)return e.emit("error",t);return r(t)}function getCursor(e,t){if(e.isClosed()){t(new i("ChangeStream is closed."));return}if(e.cursor){t(undefined,e.cursor);return}e[g].push(t)}function processResumeQueue(e,t){while(e[g].length){const r=e[g].pop();if(e.isClosed()&&!t){r(new i("Change Stream is not open."));return}r(t,e.cursor)}}e.exports=ChangeStream},9820:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2425);const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(3111).MongoNetworkTimeoutError;const A=r(3111).MongoWriteConcernError;const c=r(2337);const l=r(6292).StreamDescription;const u=r(9206);const h=r(9815);const d=r(5474).updateSessionFromResponse;const g=r(1178).uuidV4;const p=r(1371).now;const E=r(1371).calculateDurationInMs;const m=Symbol("stream");const C=Symbol("queue");const I=Symbol("messageStream");const y=Symbol("generation");const B=Symbol("lastUseTime");const Q=Symbol("clusterTime");const b=Symbol("description");const w=Symbol("ismaster");const S=Symbol("autoEncrypter");class Connection extends n{constructor(e,t){super(t);this.id=t.id;this.address=streamIdentifier(e);this.bson=t.bson;this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.host=t.host||"localhost";this.port=t.port||27017;this.monitorCommands=typeof t.monitorCommands==="boolean"?t.monitorCommands:false;this.serverApi=t.serverApi;this.closed=false;this.destroyed=false;this[b]=new l(this.address,t);this[y]=t.generation;this[B]=p();if(t.autoEncrypter){this[S]=t.autoEncrypter}this[C]=new Map;this[I]=new o(t);this[I].on("message",messageHandler(this));this[m]=e;e.on("error",(()=>{}));this[I].on("error",(e=>this.handleIssue({destroy:e})));e.on("close",(()=>this.handleIssue({isClose:true})));e.on("timeout",(()=>this.handleIssue({isTimeout:true,destroy:true})));e.pipe(this[I]);this[I].pipe(e)}get description(){return this[b]}get ismaster(){return this[w]}set ismaster(e){this[b].receiveResponse(e);this[w]=e}get generation(){return this[y]||0}get idleTime(){return E(this[B])}get clusterTime(){return this[Q]}get stream(){return this[m]}markAvailable(){this[B]=p()}handleIssue(e){if(this.closed){return}if(e.destroy){this[m].destroy(typeof e.destroy==="boolean"?undefined:e.destroy)}this.closed=true;for(const t of this[C]){const r=t[1];if(e.isTimeout){r.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null}))}else if(e.isClose){r.cb(new i(`connection ${this.id} to ${this.address} closed`))}else{r.cb(typeof e.destroy==="boolean"?undefined:e.destroy)}}this[C].clear();this.emit("close")}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(this[m]==null||this.destroyed){this.destroyed=true;if(typeof t==="function"){t()}return}if(e.force){this[m].destroy();this.destroyed=true;if(typeof t==="function"){t()}return}this[m].end((e=>{this.destroyed=true;if(typeof t==="function"){t(e)}}))}applyApiVersion(e){if(this.serverApi){e.serverApi=this.serverApi}return e}command(e,t,r,n){if(typeof r==="function"){n=r;r={}}u.command(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}query(e,t,r,n,o){u.query(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}getMore(e,t,r,n,o){u.getMore(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}killCursors(e,t,r){u.killCursors(makeServerTrampoline(this),e,t,this.applyApiVersion({}),r)}insert(e,t,r,n){u.insert(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}update(e,t,r,n){u.update(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}remove(e,t,r,n){u.remove(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}}function makeServerTrampoline(e){const t={description:e.description,clusterTime:e[Q],s:{bson:e.bson,pool:{write:write.bind(e),isConnected:()=>true}}};if(e[S]){t.autoEncrypter=e[S]}return t}function messageHandler(e){return function messageHandler(t){e.emit("message",t);if(!e[C].has(t.responseTo)){return}const r=e[C].get(t.responseTo);const n=r.cb;e[C].delete(t.responseTo);if(t.moreToCome){e[C].set(t.requestId,r)}else if(r.socketTimeoutOverride){e[m].setTimeout(e.socketTimeout)}try{t.parse(r)}catch(e){n(new s(e));return}if(t.documents[0]){const o=t.documents[0];const i=r.session;if(i){d(i,o)}if(o.$clusterTime){e[Q]=o.$clusterTime;e.emit("clusterTimeReceived",o.$clusterTime)}if(r.command){if(o.writeConcernError){n(new A(o.writeConcernError,o));return}if(o.ok===0||o.$err||o.errmsg||o.code){n(new s(o));return}}}n(undefined,new c(r.fullResult?t:t.documents[0],e,t))}}function streamIdentifier(e){if(typeof e.address==="function"){return`${e.remoteAddress}:${e.remotePort}`}return g().toString("hex")}function write(e,t,r){if(typeof t==="function"){r=t}t=t||{};const n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false,noResponse:typeof t.noResponse==="boolean"?t.noResponse:false,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,raw:typeof t.raw==="boolean"?t.raw:false};if(this[b]&&this[b].compressor){n.agreedCompressor=this[b].compressor;if(this[b].zlibCompressionLevel){n.zlibCompressionLevel=this[b].zlibCompressionLevel}}if(typeof t.socketTimeout==="number"){n.socketTimeoutOverride=true;this[m].setTimeout(t.socketTimeout)}if(this.monitorCommands){this.emit("commandStarted",new h.CommandStartedEvent(this,e));n.started=p();n.cb=(t,o)=>{if(t){this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,n.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,n.started))}else{this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,n.started))}}if(typeof r==="function"){r(t,o)}}}if(!n.noResponse){this[C].set(n.requestId,n)}try{this[I].writeCommand(e,n)}catch(e){if(!n.noResponse){this[C].delete(n.requestId);n.cb(e);return}}if(n.noResponse){n.cb()}}e.exports={Connection:Connection}},2529:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361).EventEmitter;const s=r(104);const i=r(1371).makeCounter;const a=r(3111).MongoError;const A=r(9820).Connection;const c=r(1178).eachAsync;const l=r(6573);const u=r(1178).relayEvents;const h=r(2926);const d=h.PoolClosedError;const g=h.WaitQueueTimeoutError;const p=r(897);const E=p.ConnectionPoolCreatedEvent;const m=p.ConnectionPoolClosedEvent;const C=p.ConnectionCreatedEvent;const I=p.ConnectionReadyEvent;const y=p.ConnectionClosedEvent;const B=p.ConnectionCheckOutStartedEvent;const Q=p.ConnectionCheckOutFailedEvent;const b=p.ConnectionCheckedOutEvent;const w=p.ConnectionCheckedInEvent;const S=p.ConnectionPoolClearedEvent;const v=Symbol("logger");const R=Symbol("connections");const k=Symbol("permits");const D=Symbol("minPoolSizeTimer");const N=Symbol("generation");const T=Symbol("connectionCounter");const O=Symbol("cancellationToken");const _=Symbol("waitQueue");const M=Symbol("cancelled");const L=new Set(["ssl","bson","connectionType","serverApi","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 resolveOptions(e,t){const r=Array.from(L).reduce(((t,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){t[r]=e[r]}return t}),{});return Object.freeze(Object.assign({},t,r))}class ConnectionPool extends o{constructor(e){super();e=e||{};this.closed=false;this.options=resolveOptions(e,{connectionType:A,maxPoolSize:typeof e.maxPoolSize==="number"?e.maxPoolSize:100,minPoolSize:typeof e.minPoolSize==="number"?e.minPoolSize:0,maxIdleTimeMS:typeof e.maxIdleTimeMS==="number"?e.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof e.waitQueueTimeoutMS==="number"?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata,useUnifiedTopology:e.useUnifiedTopology});if(e.minSize>e.maxSize){throw new TypeError("Connection pool minimum size must not be greater than maximum pool size")}this[v]=s("ConnectionPool",e);this[R]=new n;this[k]=this.options.maxPoolSize;this[D]=undefined;this[N]=0;this[T]=i(1);this[O]=new o;this[O].setMaxListeners(Infinity);this[_]=new n;process.nextTick((()=>{this.emit("connectionPoolCreated",new E(this));ensureMinPoolSize(this)}))}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[N]}get totalConnectionCount(){return this[R].length+(this.options.maxPoolSize-this[k])}get availableConnectionCount(){return this[R].length}get waitQueueSize(){return this[_].length}checkOut(e){this.emit("connectionCheckOutStarted",new B(this));if(this.closed){this.emit("connectionCheckOutFailed",new Q(this,"poolClosed"));e(new d(this));return}const t={callback:e};const r=this;const n=this.options.waitQueueTimeoutMS;if(n){t.timer=setTimeout((()=>{t[M]=true;t.timer=undefined;r.emit("connectionCheckOutFailed",new Q(r,"timeout"));t.callback(new g(r))}),n)}this[_].push(t);process.nextTick((()=>processWaitQueue(this)))}checkIn(e){const t=this.closed;const r=connectionIsStale(this,e);const n=!!(t||r||e.closed);if(!n){e.markAvailable();this[R].push(e)}this.emit("connectionCheckedIn",new w(this,e));if(n){const r=e.closed?"error":t?"poolClosed":"stale";destroyConnection(this,e,r)}process.nextTick((()=>processWaitQueue(this)))}clear(){this[N]+=1;this.emit("connectionPoolCleared",new S(this))}close(e,t){if(typeof e==="function"){t=e}e=Object.assign({force:false},e);if(this.closed){return t()}this[O].emit("cancel");while(this.waitQueueSize){const e=this[_].pop();clearTimeout(e.timer);if(!e[M]){e.callback(new a("connection pool closed"))}}if(this[D]){clearTimeout(this[D])}if(typeof this[T].return==="function"){this[T].return()}this.closed=true;c(this[R].toArray(),((t,r)=>{this.emit("connectionClosed",new y(this,t,"poolClosed"));t.destroy(e,r)}),(e=>{this[R].clear();this.emit("connectionPoolClosed",new m(this));t(e)}))}withConnection(e,t){this.checkOut(((r,n)=>{e(r,n,((e,r)=>{if(typeof t==="function"){if(e){t(e)}else{t(undefined,r)}}if(n){this.checkIn(n)}}))}))}}function ensureMinPoolSize(e){if(e.closed||e.options.minPoolSize===0){return}const t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rensureMinPoolSize(e)),10)}function connectionIsStale(e,t){return t.generation!==e[N]}function connectionIsIdle(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function createConnection(e,t){const r=Object.assign({id:e[T].next().value,generation:e[N]},e.options);e[k]--;l(r,e[O],((r,n)=>{if(r){e[k]++;e[v].debug(`connection attempt failed with error [${JSON.stringify(r)}]`);if(typeof t==="function"){t(r)}return}if(e.closed){n.destroy({force:true});return}u(n,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]);e.emit("connectionCreated",new C(e,n));n.markAvailable();e.emit("connectionReady",new I(e,n));if(typeof t==="function"){t(undefined,n);return}e[R].push(n);process.nextTick((()=>processWaitQueue(e)))}))}function destroyConnection(e,t,r){e.emit("connectionClosed",new y(e,t,r));e[k]++;process.nextTick((()=>t.destroy()))}function processWaitQueue(e){if(e.closed){return}while(e.waitQueueSize){const t=e[_].peekFront();if(t[M]){e[_].shift();continue}if(!e.availableConnectionCount){break}const r=e[R].shift();const n=connectionIsStale(e,r);const o=connectionIsIdle(e,r);if(!n&&!o&&!r.closed){e.emit("connectionCheckedOut",new b(e,r));clearTimeout(t.timer);e[_].shift();t.callback(undefined,r);return}const s=r.closed?"error":n?"stale":"idle";destroyConnection(e,r,s)}const t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{const n=e[_].shift();if(n==null||n[M]){if(t==null){e[R].push(r)}return}if(t){e.emit("connectionCheckOutFailed",new Q(e,t))}else{e.emit("connectionCheckedOut",new b(e,r))}clearTimeout(n.timer);n.callback(t,r)}));return}}e.exports={ConnectionPool:ConnectionPool}},2926:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class PoolClosedError extends n{constructor(e){super("Attempted to check out a connection from closed connection pool");this.name="MongoPoolClosedError";this.address=e.address}}class WaitQueueTimeoutError extends n{constructor(e){super("Timed out while checking out a connection from connection pool");this.name="MongoWaitQueueTimeoutError";this.address=e.address}}e.exports={PoolClosedError:PoolClosedError,WaitQueueTimeoutError:WaitQueueTimeoutError}},897:e=>{"use strict";class ConnectionPoolMonitoringEvent{constructor(e){this.time=new Date;this.address=e.address}}class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e);this.options=e.options}}class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t,r){super(e);this.connectionId=t.id;this.reason=r||"unknown"}}class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.reason=t}}class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}const t=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];e.exports={CMAP_EVENT_NAMES:t,ConnectionPoolCreatedEvent:ConnectionPoolCreatedEvent,ConnectionPoolClosedEvent:ConnectionPoolClosedEvent,ConnectionCreatedEvent:ConnectionCreatedEvent,ConnectionReadyEvent:ConnectionReadyEvent,ConnectionClosedEvent:ConnectionClosedEvent,ConnectionCheckOutStartedEvent:ConnectionCheckOutStartedEvent,ConnectionCheckOutFailedEvent:ConnectionCheckOutFailedEvent,ConnectionCheckedOutEvent:ConnectionCheckedOutEvent,ConnectionCheckedInEvent:ConnectionCheckedInEvent,ConnectionPoolClearedEvent:ConnectionPoolClearedEvent}},2425:(e,t,r)=>{"use strict";const n=r(2781).Duplex;const o=r(336);const s=r(3111).MongoParseError;const i=r(7793).decompress;const a=r(9814).Response;const A=r(8988).BinMsg;const c=r(3111).MongoError;const l=r(7272).opcodes.OP_COMPRESSED;const u=r(7272).opcodes.OP_MSG;const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(8988).Msg;const I=1024*1024*16*4;const y=Symbol("buffer");class MessageStream extends n{constructor(e){e=e||{};super(e);this.bson=e.bson;this.maxBsonMessageSize=e.maxBsonMessageSize||I;this[y]=new o}_write(e,t,r){const n=this[y];n.append(e);processIncomingData(this,r)}_read(){return}writeCommand(e,t){const r=t&&!!t.agreedCompressor;if(!r||!canCompress(e)){const t=e.toBin();this.push(Array.isArray(t)?Buffer.concat(t):t);return}const n=Buffer.concat(e.toBin());const o=n.slice(h);const s=n.readInt32LE(12);p({options:t},o,((r,n)=>{if(r){t.cb(r,null);return}const i=Buffer.alloc(h);i.writeInt32LE(h+d+n.length,0);i.writeInt32LE(e.requestId,4);i.writeInt32LE(0,8);i.writeInt32LE(g.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(s,0);a.writeInt32LE(o.length,4);a.writeUInt8(E[t.agreedCompressor],8);this.push(Buffer.concat([i,a,n]))}))}}function canCompress(e){const t=e instanceof C?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function processIncomingData(e,t){const r=e[y];if(r.length<4){t();return}const n=r.readInt32LE(0);if(n<0){t(new s(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new s(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}const o=r.slice(0,n);r.consume(n);const d={length:o.readInt32LE(0),requestId:o.readInt32LE(4),responseTo:o.readInt32LE(8),opCode:o.readInt32LE(12)};let g=d.opCode===u?A:a;const p=e.responseOptions;if(d.opCode!==l){const n=o.slice(h);e.emit("message",new g(e.bson,o,d,n,p));if(r.length>=4){processIncomingData(e,t)}else{t()}return}d.fromCompressed=true;d.opCode=o.readInt32LE(h);d.length=o.readInt32LE(h+4);const E=o[h+8];const m=o.slice(h+9);g=d.opCode===u?A:a;i(E,m,((n,s)=>{if(n){t(n);return}if(s.length!==d.length){t(new c("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new g(e.bson,o,d,s,p));if(r.length>=4){processIncomingData(e,t)}else{t()}}))}e.exports=MessageStream},6292:(e,t,r)=>{"use strict";const n=r(750).parseServerType;const o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];class StreamDescription{constructor(e,t){this.address=e;this.type=n(null);this.minWireVersion=undefined;this.maxWireVersion=undefined;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=n(e);o.forEach((t=>{if(typeof e[t]!=="undefined"){this[t]=e[t]}}));if(e.compression){this.compressor=this.compressors.filter((t=>e.compression.indexOf(t)!==-1))[0]}}}e.exports={StreamDescription:StreamDescription}},5193:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(1371).deprecateOptions;const s=r(1371).emitWarningOnce;const i=r(1371).checkCollectionName;const a=r(3994).BSON.ObjectID;const A=r(3994).MongoError;const c=r(1371).normalizeHintField;const l=r(1371).decorateCommand;const u=r(1371).decorateWithCollation;const h=r(1371).decorateWithReadConcern;const d=r(1371).formattedOrderClause;const g=r(3994).ReadPreference;const p=r(325);const E=r(5035);const m=r(1117);const C=r(1371).executeLegacyOperation;const I=r(2481);const y=r(7289);const B=r(1371).MongoDBNamespace;const Q=r(7429);const b=r(538);const w=r(6716).ensureIndex;const S=r(6716).group;const v=r(6716).parallelCollectionScan;const R=r(2296).removeDocuments;const k=r(6716).save;const D=r(2296).updateDocuments;const N=r(1554);const T=r(6976);const O=r(5131);const _=r(6394);const M=r(323);const L=r(6352);const F=r(6469);const U=r(2360).DropCollectionOperation;const P=r(3560);const G=r(5328);const Y=r(4451);const V=r(9961);const W=r(4497);const J=r(711);const q=r(5841);const j=r(4316);const z=r(1925);const $=r(8169);const K=r(4218);const X=r(7809);const Z=r(4245);const ee=r(3592);const te=r(9915);const re=r(4956);const ne=r(28);const oe=r(2779);const se=r(43);const ie=r(2808);const ae=r(6331);const Ae=r(2508);const ce=r(968);const le=r(9350);const ue=r(9068);const fe=r(2548);const he=["ignoreUndefined"];function Collection(e,t,r,n,o,s){i(n);const A=null;const c=s==null||s.slaveOk==null?e.slaveOk:s.slaveOk;const l=s==null||s.serializeFunctions==null?e.s.options.serializeFunctions:s.serializeFunctions;const u=s==null||s.raw==null?e.s.options.raw:s.raw;const h=s==null||s.promoteLongs==null?e.s.options.promoteLongs:s.promoteLongs;const d=s==null||s.promoteValues==null?e.s.options.promoteValues:s.promoteValues;const p=s==null||s.promoteBuffers==null?e.s.options.promoteBuffers:s.promoteBuffers;const E=s==null||s.bsonRegExp==null?e.s.options.bsonRegExp:s.bsonRegExp;const m=null;const C=new B(r,n);const Q=s.promiseLibrary||Promise;o=o==null?a:o;this.s={pkFactory:o,db:e,topology:t,options:s,namespace:C,readPreference:g.fromOptions(s),slaveOk:c,serializeFunctions:l,raw:u,promoteLongs:h,promoteValues:d,promoteBuffers:p,bsonRegExp:E,internalHint:A,collectionHint:m,promiseLibrary:Q,readConcern:y.fromOptions(s),writeConcern:I.fromOptions(s)}}Object.defineProperty(Collection.prototype,"dbName",{enumerable:true,get:function(){return this.s.namespace.db}});Object.defineProperty(Collection.prototype,"collectionName",{enumerable:true,get:function(){return this.s.namespace.collection}});Object.defineProperty(Collection.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Object.defineProperty(Collection.prototype,"readConcern",{enumerable:true,get:function(){if(this.s.readConcern==null){return this.s.db.readConcern}return this.s.readConcern}});Object.defineProperty(Collection.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return this.s.db.readPreference}return this.s.readPreference}});Object.defineProperty(Collection.prototype,"writeConcern",{enumerable:true,get:function(){if(this.s.writeConcern==null){return this.s.db.writeConcern}return this.s.writeConcern}});Object.defineProperty(Collection.prototype,"hint",{enumerable:true,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const de=["maxScan","fields","snapshot","oplogReplay"];Collection.prototype.find=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `find()` must be a callback or undefined")}let n=e;if(typeof r!=="function"){if(typeof t==="function"){r=t;t=undefined}else if(t==null){r=typeof n==="function"?n:undefined;n=typeof n==="object"?n:undefined}}n=n==null?{}:n;const o=n;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+"]");t.name="MongoError";throw t}}if(n!=null&&n._bsontype==="ObjectID"){n={_id:n}}if(!t)t={};let i=t.projection||t.fields;if(i&&!Buffer.isBuffer(i)&&Array.isArray(i)){i=i.length?i.reduce(((e,t)=>{e[t]=1;return e}),{}):{_id:1}}let a=Object.assign({},t);for(let e in this.s.options){if(he.indexOf(e)!==-1){a[e]=this.s.options[e]}}a.skip=t.skip?t.skip:0;a.limit=t.limit?t.limit:0;a.raw=typeof t.raw==="boolean"?t.raw:this.s.raw;a.hint=t.hint!=null?c(t.hint):this.s.collectionHint;a.timeout=typeof t.timeout==="undefined"?undefined:t.timeout;a.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk;a.readPreference=g.resolve(this,a);if(a.readPreference!=null&&(a.readPreference!=="primary"||a.readPreference.mode!=="primary")){a.slaveOk=true}if(n!=null&&typeof n!=="object"){throw A.create({message:"query selector must be an object",driver:true})}const p={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:n};if(typeof t.allowDiskUse==="boolean"){p.allowDiskUse=t.allowDiskUse}if(typeof a.awaitdata==="boolean"){a.awaitData=a.awaitdata}if(typeof a.timeout==="boolean")a.noCursorTimeout=!a.timeout;l(p,a,["session","collation"]);if(i)p.fields=i;a.db=this.s.db;a.promiseLibrary=this.s.promiseLibrary;if(a.raw==null&&typeof this.s.raw==="boolean")a.raw=this.s.raw;if(a.promoteLongs==null&&typeof this.s.promoteLongs==="boolean")a.promoteLongs=this.s.promoteLongs;if(a.promoteValues==null&&typeof this.s.promoteValues==="boolean")a.promoteValues=this.s.promoteValues;if(a.promoteBuffers==null&&typeof this.s.promoteBuffers==="boolean")a.promoteBuffers=this.s.promoteBuffers;if(a.bsonRegExp==null&&typeof this.s.bsonRegExp==="boolean")a.bsonRegExp=this.s.bsonRegExp;if(p.sort){p.sort=d(p.sort)}h(p,this,t);try{u(p,this,t)}catch(e){if(typeof r==="function")return r(e,null);throw e}const E=this.s.topology.cursor(new V(this,this.s.namespace,p,a),a);if(typeof r==="function"){r(null,E);return}return E}));Collection.prototype.insertOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new te(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insertMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{ordered:true};const n=new ee(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.bulkWrite=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:true};if(!Array.isArray(e)){throw A.create({message:"operations must be an array of documents",driver:true})}const n=new T(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insert=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:false};e=!Array.isArray(e)?[e]:e;if(t.keepGoing===true){t.ordered=false}return this.insertMany(e,t,r)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");Collection.prototype.updateOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new ue(this,e,t,r),n)};Collection.prototype.replaceOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new Ae(this,e,t,r),n)};Collection.prototype.updateMany=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new le(this,e,t,r),n)};Collection.prototype.update=n((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,D,[this,e,t,r,n])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");Collection.prototype.deleteOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new L(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeOne=Collection.prototype.deleteOne;Collection.prototype.deleteMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new M(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeMany=Collection.prototype.deleteMany;Collection.prototype.remove=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,R,[this,e,t,r])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");Collection.prototype.save=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,k,[this,e,t,r])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");Collection.prototype.findOne=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `findOne()` must be a callback or undefined")}if(typeof e==="function")r=e,e={},t={};if(typeof t==="function")r=t,t={};e=e||{};t=t||{};const n=new W(this,e,t);return fe(this.s.topology,n,r)}));Collection.prototype.rename=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t,{readPreference:g.PRIMARY});const n=new ie(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.drop=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new U(this.s.db,this.collectionName,e);return fe(this.s.topology,r,t)};Collection.prototype.options=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new se(this,e);return fe(this.s.topology,r,t)};Collection.prototype.isCapped=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new re(this,e);return fe(this.s.topology,r,t)};Collection.prototype.createIndex=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.createIndexes=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{};if(typeof t.maxTimeMS!=="number")delete t.maxTimeMS;const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.dropIndex=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift()||{}:{};t.readPreference=g.PRIMARY;const o=new P(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.dropIndexes=function(e,t){if(typeof e==="function")t=e,e={};e=e?Object.assign({},e):{};if(typeof e.maxTimeMS!=="number")delete e.maxTimeMS;const r=new G(this,e);return fe(this.s.topology,r,t)};Collection.prototype.dropAllIndexes=n(Collection.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");Collection.prototype.reIndex=n((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new ae(this,e);return fe(this.s.topology,r,t)}),"collection.reIndex is deprecated. Use db.command instead.");Collection.prototype.listIndexes=function(e){const t=new b(this.s.topology,new ne(this,e),e);return t};Collection.prototype.ensureIndex=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return C(this.s.topology,w,[this,e,t,r])}),"collection.ensureIndex is deprecated. Use createIndexes instead.");Collection.prototype.indexExists=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new X(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.indexInformation=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new Z(this.s.db,this.collectionName,e);return fe(this.s.topology,n,t)};Collection.prototype.count=n((function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};if(typeof t==="function")r=t,t={};t=t||{};return fe(this.s.topology,new Y(this,Object.assign({query:e},t)),r)}),"collection.count is deprecated, and will be removed in a future version."+" Use Collection.countDocuments or Collection.estimatedDocumentCount instead");Collection.prototype.estimatedDocumentCount=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new Y(this,e);return fe(this.s.topology,r,t)};Collection.prototype.countDocuments=function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};const o=new O(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.distinct=function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;const s=o.length?o.shift()||{}:{};const i=o.length?o.shift()||{}:{};const a=new F(this,e,s,i);return fe(this.s.topology,a,n)};Collection.prototype.indexes=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new K(this,e);return fe(this.s.topology,r,t)};Collection.prototype.stats=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new ce(this,e);return fe(this.s.topology,n,t)};Collection.prototype.findOneAndDelete=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new q(this,e,t),r)};Collection.prototype.findOneAndReplace=o({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new j(this,e,t,r),n)}));Collection.prototype.findOneAndUpdate=o({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new z(this,e,t,r),n)}));Collection.prototype.findAndModify=n(_findAndModify,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");Collection.prototype._findAndModify=_findAndModify;function _findAndModify(e,t,r,n,o){const s=Array.prototype.slice.call(arguments,1);o=typeof s[s.length-1]==="function"?s.pop():undefined;t=s.length?s.shift()||[]:[];r=s.length?s.shift():null;n=s.length?s.shift()||{}:{};n=Object.assign({},n);n.readPreference=g.PRIMARY;return fe(this.s.topology,new J(this,e,t,r,n),o)}Collection.prototype.findAndRemove=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift()||[]:[];r=o.length?o.shift()||{}:{};r.remove=true;return fe(this.s.topology,new J(this,e,t,null,r),n)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");Collection.prototype.aggregate=function(e,t,r){if(Array.isArray(e)){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}}else{const n=Array.prototype.slice.call(arguments,0);r=n.pop();const o=n[n.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?n.pop():{};e=n}const n=new Q(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Collection.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Collection.prototype.parallelCollectionScan=n((function(e,t){if(typeof e==="function")t=e,e={numCursors:1};e.numCursors=e.numCursors||1;e.batchSize=e.batchSize||1e3;e=Object.assign({},e);e.readPreference=g.resolve(this,e);e.promiseLibrary=this.s.promiseLibrary;if(e.session){e.session=undefined}return C(this.s.topology,v,[this,e,t],{skipSessions:true})}),"parallelCollectionScan is deprecated in MongoDB v4.1");Collection.prototype.geoHaystackSearch=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift()||{}:{};const s=new $(this,e,t,r);return fe(this.s.topology,s,n)}),"geoHaystackSearch is deprecated, and will be removed in a future version.");Collection.prototype.group=n((function(e,t,r,n,o,s,i,a){const A=Array.prototype.slice.call(arguments,3);a=typeof A[A.length-1]==="function"?A.pop():undefined;n=A.length?A.shift():null;o=A.length?A.shift():null;s=A.length?A.shift():null;i=A.length?A.shift()||{}:{};if(!(typeof o==="function")){s=o;o=null}if(!Array.isArray(e)&&e instanceof Object&&typeof e!=="function"&&!(e._bsontype==="Code")){e=Object.keys(e)}if(typeof n==="function"){n=n.toString()}if(typeof o==="function"){o=o.toString()}s=s==null?true:s;return C(this.s.topology,S,[this,e,t,r,n,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");Collection.prototype.mapReduce=function(e,t,r,n){if("function"===typeof r)n=r,r={};if(null==r.out){throw new Error("the out option parameter must be defined, see mongodb docs for possible values")}if("function"===typeof e){e=e.toString()}if("function"===typeof t){t=t.toString()}if("function"===typeof r.finalize){r.finalize=r.finalize.toString()}const o=new oe(this,e,t,r);return fe(this.s.topology,o,n)};Collection.prototype.initializeUnorderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return p(this.s.topology,this,e)};Collection.prototype.initializeOrderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return E(this.s.topology,this,e)};Collection.prototype.getLogger=function(){return this.s.db.s.logger};e.exports=Collection},538:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(3994).MongoError;const s=r(7159);const i=r(4847).CursorState;class CommandCursor extends s{constructor(e,t,r,n){super(e,t,r,n)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(this.s.state!==i.INIT){throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof n){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new n(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw o.create({message:"batchSize requires an integer",driver:true})}if(this.cmd.cursor){this.cmd.cursor.batchSize=e}this.setCursorBatchSize(e);return this}maxTimeMS(e){if(this.topology.lastIsMaster().minWireVersion>2){this.cmd.maxTimeMS=e}return this}getLogger(){return this.logger}}CommandCursor.prototype.get=CommandCursor.prototype.toArray;e.exports=CommandCursor},7703:(e,t,r)=>{"use strict";const n=r(8988).Msg;const o=r(9814).KillCursor;const s=r(9814).GetMore;const i=r(1371).deepCopy;const a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const A=new Set(["hello","ismaster","isMaster"]);const c={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"};const l={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"};const u=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"];const collectionName=e=>e.ns.split(".")[1];const shouldRedactCommand=(e,t)=>a.has(e)||A.has(e)&&!!t.speculativeAuthenticate;const extractCommand=e=>{let t;if(e instanceof s){t={getMore:i(e.cursorId),collection:collectionName(e),batchSize:e.numberToReturn}}else if(e instanceof o){t={killCursors:collectionName(e),cursors:i(e.cursorIds)}}else if(e instanceof n){t=i(e.command)}else if(e.query&&e.query.$query){let r;if(e.ns==="admin.$cmd"){r=Object.assign({},e.query.$query)}else{r={find:collectionName(e)};Object.keys(c).forEach((t=>{if(typeof e.query[t]!=="undefined")r[c[t]]=i(e.query[t])}))}Object.keys(l).forEach((t=>{if(typeof e[t]!=="undefined")r[l[t]]=i(e[t])}));u.forEach((t=>{if(e[t])r[t]=e[t]}));if(typeof e.pre32Limit!=="undefined"){r.limit=e.pre32Limit}if(e.query.$explain){t={explain:r}}else{t=r}}else{t=i(e.query||e)}const r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:shouldRedactCommand(r,t)}};e.exports={extractCommand:extractCommand}},147:e=>{"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"}},557:e=>{"use strict";class AuthContext{constructor(e,t,r){this.connection=e;this.credentials=t;this.options=r}}class AuthProvider{constructor(e){this.bson=e}prepare(e,t,r){r(undefined,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}e.exports={AuthContext:AuthContext,AuthProvider:AuthProvider}},2192:(e,t,r)=>{"use strict";const n=r(4228);const o=r(7324);const s=r(8728);const i=r(2640);const a=r(864).ScramSHA1;const A=r(864).ScramSHA256;const c=r(8857);function defaultAuthProviders(e){return{"mongodb-aws":new c(e),mongocr:new n(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new A(e)}}e.exports={defaultAuthProviders:defaultAuthProviders}},2640:(e,t,r)=>{"use strict";const n=r(7578);const o=r(557).AuthProvider;const s=r(1178).retrieveKerberos;const i=r(3111).MongoError;let a;class GSSAPI extends o{auth(e,t){const r=e.connection;const n=e.credentials;if(n==null)return t(new i("credentials required"));const o=n.username;function externalCommand(e,t){return r.command("$external.$cmd",e,t)}makeKerberosClient(e,((e,r)=>{if(e)return t(e);if(r==null)return t(new i("gssapi client missing"));r.step("",((e,n)=>{if(e)return t(e);externalCommand(saslStart(n),((e,n)=>{if(e)return t(e);const s=n.result;negotiate(r,10,s.payload,((e,n)=>{if(e)return t(e);externalCommand(saslContinue(n,s.conversationId),((e,n)=>{if(e)return t(e);const s=n.result;finalize(r,o,s.payload,((e,r)=>{if(e)return t(e);externalCommand({saslContinue:1,conversationId:s.conversationId,payload:r},((e,r)=>{if(e)return t(e);t(undefined,r)}))}))}))}))}))}))}))}}e.exports=GSSAPI;function makeKerberosClient(e,t){const r=e.options.host;const n=e.options.port;const o=e.credentials;if(!r||!n||!o){return t(new i(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${o?"host":"credentials"}.`))}if(a==null){try{a=s()}catch(e){return t(e)}}const A=o.username;const c=o.password;const l=o.mechanismProperties;const u=l["gssapiservicename"]||l["gssapiServiceName"]||"mongodb";performGssapiCanonicalizeHostName(r,l,((e,r)=>{if(e)return t(e);const n={};if(c!=null){Object.assign(n,{user:A,password:c})}a.initializeClient(`${u}${process.platform==="win32"?"/":"@"}${r}`,n,((e,r)=>{if(e)return t(new i(e));t(null,r)}))}))}function saslStart(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}function saslContinue(e,t){return{saslContinue:1,conversationId:t,payload:e}}function negotiate(e,t,r,n){e.step(r,((o,s)=>{if(o&&t===0)return n(o);if(o)return negotiate(e,t-1,r,n);n(undefined,s||"")}))}function finalize(e,t,r,n){e.unwrap(r,((r,o)=>{if(r)return n(r);e.wrap(o||"",{user:t},((e,t)=>{if(e)return n(e);n(undefined,t)}))}))}function performGssapiCanonicalizeHostName(e,t,r){const o=typeof t.gssapiCanonicalizeHostName==="boolean"?t.gssapiCanonicalizeHostName:false;if(!o)return r(undefined,e);n.resolveCname(e,((t,n)=>{if(t)return r(t);if(Array.isArray(n)&&n.length>0){return r(undefined,n[0])}r(undefined,e)}))}},2222:e=>{"use strict";function getDefaultAuthMechanism(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 MongoCredentials{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||{};if(/MONGODB-AWS/i.test(this.mechanism)){if(!this.username&&process.env.AWS_ACCESS_KEY_ID){this.username=process.env.AWS_ACCESS_KEY_ID}if(!this.password&&process.env.AWS_SECRET_ACCESS_KEY){this.password=process.env.AWS_SECRET_ACCESS_KEY}if(this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null){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){if(/DEFAULT/i.test(this.mechanism)){return new MongoCredentials({username:this.username,password:this.password,source:this.source,mechanism:getDefaultAuthMechanism(e),mechanismProperties:this.mechanismProperties})}return this}}e.exports={MongoCredentials:MongoCredentials}},4228:(e,t,r)=>{"use strict";const n=r(6113);const o=r(557).AuthProvider;class MongoCR extends o{auth(e,t){const r=e.connection;const o=e.credentials;const s=o.username;const i=o.password;const a=o.source;r.command(`${a}.$cmd`,{getnonce:1},((e,o)=>{let A=null;let c=null;if(e==null){const e=o.result;A=e.nonce;let t=n.createHash("md5");t.update(s+":mongo:"+i,"utf8");const r=t.digest("hex");t=n.createHash("md5");t.update(A+s+r,"utf8");c=t.digest("hex")}const l={authenticate:1,user:s,nonce:A,key:c};r.command(`${a}.$cmd`,l,t)}))}}e.exports=MongoCR},8857:(e,t,r)=>{"use strict";const n=r(557).AuthProvider;const o=r(2222).MongoCredentials;const s=r(3111).MongoError;const i=r(6113);const a=r(3685);const A=r(1178).maxWireVersion;const c=r(7310);let l;try{l=r(3847)}catch(e){}const u=110;const h="http://169.254.170.2";const d="http://169.254.169.254";const g="/latest/meta-data/iam/security-credentials";class MongoDBAWS extends n{auth(e,t){const r=e.connection;const n=e.credentials;if(A(r)<9){t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(l==null){t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(n.username==null){makeTempCredentials(n,((r,n)=>{if(r)return t(r);e.credentials=n;this.auth(e,t)}));return}const o=n.source;const a=this.bson;const c=n.username;const h=n.password;const d=n.mechanismProperties.AWS_SESSION_TOKEN;const g=c&&h&&d?{accessKeyId:c,secretAccessKey:h,sessionToken:d}:c&&h?{accessKeyId:c,secretAccessKey:h}:undefined;i.randomBytes(32,((e,n)=>{if(e){t(e);return}const i={saslStart:1,mechanism:"MONGODB-AWS",payload:a.serialize({r:n,p:u})};r.command(`${o}.$cmd`,i,((e,i)=>{if(e)return t(e);const A=i.result;const c=a.deserialize(A.payload.buffer);const u=c.h;const h=c.s.buffer;if(h.length!==64){t(new s(`Invalid server nonce length ${h.length}, expected 64`));return}if(h.compare(n,0,n.length,0,n.length)!==0){t(new s("Server nonce does not begin with client nonce"));return}if(u.length<1||u.length>255||u.indexOf("..")!==-1){t(new s(`Server returned an invalid host: "${u}"`));return}const p="Action=GetCallerIdentity&Version=2011-06-15";const E=l.sign({method:"POST",host:u,region:deriveRegion(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":p.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:p},g);const m=E.headers.Authorization;const C=E.headers["X-Amz-Date"];const I={a:m,d:C};if(d){I.t=d}const y={saslContinue:1,conversationId:1,payload:a.serialize(I)};r.command(`${o}.$cmd`,y,(e=>{if(e)return t(e);t()}))}))}))}}function makeTempCredentials(e,t){function done(r){if(r.AccessKeyId==null||r.SecretAccessKey==null||r.Token==null){t(new s("Could not obtain temporary MONGODB-AWS credentials"));return}t(undefined,new o({username:r.AccessKeyId,password:r.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:r.Token}}))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){request(`${h}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,undefined,((e,r)=>{if(e)return t(e);done(r)}));return}request(`${d}/latest/api/token`,{method:"PUT",json:false,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},((e,r)=>{if(e)return t(e);request(`${d}/${g}`,{json:false,headers:{"X-aws-ec2-metadata-token":r}},((e,n)=>{if(e)return t(e);request(`${d}/${g}/${n}`,{headers:{"X-aws-ec2-metadata-token":r}},((e,r)=>{if(e)return t(e);done(r)}))}))}))}function deriveRegion(e){const t=e.split(".");if(t.length===1||t[1]==="amazonaws"){return"us-east-1"}return t[1]}function request(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:true},c.parse(e),t);const n=a.request(t,(e=>{e.setEncoding("utf8");let n="";e.on("data",(e=>n+=e));e.on("end",(()=>{if(t.json===false){r(undefined,n);return}try{const e=JSON.parse(n);r(undefined,e)}catch(e){r(new s(`Invalid JSON response: "${n}"`))}}))}));n.on("error",(e=>r(e)));n.end()}e.exports=MongoDBAWS},8728:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(557).AuthProvider;const s=n();const i=s.Binary;class Plain extends o{auth(e,t){const r=e.connection;const n=e.credentials;const o=n.username;const s=n.password;const a=new i(`\0${o}\0${s}`);const A={saslStart:1,mechanism:"PLAIN",payload:a,autoAuthorize:1};r.command("$external.$cmd",A,t)}}e.exports=Plain},864:(e,t,r)=>{"use strict";const n=r(6113);const o=r(1867).Buffer;const s=r(7746).retrieveBSON;const i=r(3111).MongoError;const a=r(557).AuthProvider;const A=r(1371).emitWarning;const c=s();const l=c.Binary;let u;try{u=r(9178)}catch(e){}class ScramSHA extends a{constructor(e,t){super(e);this.cryptoMethod=t||"sha1"}prepare(e,t,r){const o=this.cryptoMethod;if(o==="sha256"&&typeof u!=="function"){A("Warning: no saslprep library specified. Passwords will not be sanitized")}n.randomBytes(24,((n,s)=>{if(n){return r(n)}Object.assign(t,{nonce:s});const i=t.credentials;const a=Object.assign({},e,{speculativeAuthenticate:Object.assign(makeFirstMessage(o,i,s),{db:i.source})});r(undefined,a)}))}auth(e,t){const r=e.response;if(r&&r.speculativeAuthenticate){continueScramConversation(this.cryptoMethod,r.speculativeAuthenticate,e,t);return}executeScram(this.cryptoMethod,e,t)}}function cleanUsername(e){return e.replace("=","=3D").replace(",","=2C")}function clientFirstMessageBare(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function makeFirstMessage(e,t,r){const n=cleanUsername(t.username);const s=e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256";return{saslStart:1,mechanism:s,payload:new l(o.concat([o.from("n,,","utf8"),clientFirstMessageBare(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:true}}}function executeScram(e,t,r){const n=t.connection;const o=t.credentials;const s=t.nonce;const i=o.source;const a=makeFirstMessage(e,o,s);n.command(`${i}.$cmd`,a,((n,o)=>{const s=resolveError(n,o);if(s){return r(s)}continueScramConversation(e,o.result,t,r)}))}function continueScramConversation(e,t,r,n){const s=r.connection;const a=r.credentials;const A=r.nonce;const c=a.source;const h=cleanUsername(a.username);const d=a.password;let g;if(e==="sha256"){g=typeof u==="function"?u(d):d}else{try{g=passwordDigest(h,d)}catch(e){return n(e)}}const p=o.isBuffer(t.payload)?new l(t.payload):t.payload;const E=parsePayload(p.value());const m=parseInt(E.i,10);if(m&&m<4096){n(new i(`Server returned an invalid iteration count ${m}`),false);return}const C=E.s;const I=E.r;if(I.startsWith("nonce")){n(new i(`Server returned an invalid nonce: ${I}`),false);return}const y=`c=biws,r=${I}`;const B=HI(g,o.from(C,"base64"),m,e);const Q=HMAC(e,B,"Client Key");const b=HMAC(e,B,"Server Key");const w=H(e,Q);const S=[clientFirstMessageBare(h,A),p.value().toString("base64"),y].join(",");const v=HMAC(e,w,S);const R=`p=${xor(Q,v)}`;const k=[y,R].join(",");const D=HMAC(e,b,S);const N={saslContinue:1,conversationId:t.conversationId,payload:new l(o.from(k))};s.command(`${c}.$cmd`,N,((e,t)=>{const r=resolveError(e,t);if(r){return n(r)}const a=t.result;const A=parsePayload(a.payload.value());if(!compareDigest(o.from(A.v,"base64"),D)){n(new i("Server returned an invalid signature"));return}if(!a||a.done!==false){return n(r,a)}const l={saslContinue:1,conversationId:a.conversationId,payload:o.alloc(0)};s.command(`${c}.$cmd`,l,n)}))}function parsePayload(e){const t={};const r=e.split(",");for(let e=0;e=200){_hiCachePurge()}h[s]=i;d+=1;return i}function compareDigest(e,t){if(e.length!==t.length){return false}if(typeof n.timingSafeEqual==="function"){return n.timingSafeEqual(e,t)}let r=0;for(let n=0;n{"use strict";const n=r(557).AuthProvider;class X509 extends n{prepare(e,t,r){const n=t.credentials;Object.assign(e,{speculativeAuthenticate:x509AuthenticateCommand(n)});r(undefined,e)}auth(e,t){const r=e.connection;const n=e.credentials;const o=e.response;if(o.speculativeAuthenticate){return t()}r.command("$external.$cmd",x509AuthenticateCommand(n),t)}}function x509AuthenticateCommand(e){const t={authenticate:1,mechanism:"MONGODB-X509"};if(e.username){Object.assign(t,{user:e.username})}return t}e.exports=X509},9815:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(9814).GetMore;const s=r(1371).calculateDurationInMs;const i=r(7703).extractCommand;const namespace=e=>e.ns;const databaseName=e=>e.ns.split(".")[0];const generateConnectionId=e=>e.options?`${e.options.host}:${e.options.port}`:e.address;const isLegacyPool=e=>e.s&&e.queue;const extractReply=(e,t)=>{if(e instanceof o){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),nextBatch:t.message.documents}}}if(e instanceof n){return{ok:1,cursorsUnknown:e.cursorIds}}if(e.query&&typeof e.query.$query!=="undefined"){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),firstBatch:t.message.documents}}}return t&&t.result?t.result:t};const extractConnectionDetails=e=>{if(isLegacyPool(e)){return{connectionId:generateConnectionId(e)}}const t=e;return{address:t.address,connectionId:t.id}};class CommandStartedEvent{constructor(e,t){const r=i(t);const n=r.name;const o=extractConnectionDetails(e);Object.assign(this,o,{requestId:t.requestId,databaseName:databaseName(t),commandName:n,command:r.shouldRedact?{}:r.cmd})}}class CommandSucceededEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),reply:o.shouldRedact?{}:extractReply(t,r)})}}class CommandFailedEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),failure:o.shouldRedact?{}:r})}}e.exports={CommandStartedEvent:CommandStartedEvent,CommandSucceededEvent:CommandSucceededEvent,CommandFailedEvent:CommandFailedEvent}},2337:e=>{"use strict";var CommandResult=function(e,t,r){this.result=e;this.connection=t;this.message=r};CommandResult.prototype.toJSON=function(){let e=Object.assign({},this,this.result);delete e.message;return e};CommandResult.prototype.toString=function(){return JSON.stringify(this.toJSON())};e.exports=CommandResult},9814:(e,t,r)=>{"use strict";var n=r(7746).retrieveBSON;var o=n();var s=o.Long;const i=r(1867).Buffer;var a=0;var A=r(7272).opcodes;var c=2;var l=4;var u=8;var h=16;var d=32;var g=64;var p=128;var E=1;var m=2;var C=4;var I=8;var Query=function(e,t,r,n){var o=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1){throw new Error("namespace cannot contain a null character")}this.bson=e;this.ns=t;this.query=r;this.numberToSkip=n.numberToSkip||0;this.numberToReturn=n.numberToReturn||0;this.returnFieldSelector=n.returnFieldSelector||null;this.requestId=Query.getRequestId();this.pre32Limit=n.pre32Limit;this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:true;this.batchSize=o.numberToReturn;this.tailable=false;this.slaveOk=typeof n.slaveOk==="boolean"?n.slaveOk:false;this.oplogReplay=false;this.noCursorTimeout=false;this.awaitData=false;this.exhaust=false;this.partial=false};Query.prototype.incRequestId=function(){this.requestId=a++};Query.nextRequestId=function(){return a+1};Query.prototype.toBin=function(){var e=this;var t=[];var r=null;var n=0;if(this.tailable){n|=c}if(this.slaveOk){n|=l}if(this.oplogReplay){n|=u}if(this.noCursorTimeout){n|=h}if(this.awaitData){n|=d}if(this.exhaust){n|=g}if(this.partial){n|=p}if(e.batchSize!==e.numberToReturn)e.numberToReturn=e.batchSize;var o=i.alloc(4*4+4+i.byteLength(e.ns)+1+4+4);t.push(o);var s=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(s);if(e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0){r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(r)}var a=o.length+s.length+(r?r.length:0);var E=4;o[3]=a>>24&255;o[2]=a>>16&255;o[1]=a>>8&255;o[0]=a&255;o[E+3]=this.requestId>>24&255;o[E+2]=this.requestId>>16&255;o[E+1]=this.requestId>>8&255;o[E]=this.requestId&255;E=E+4;o[E+3]=0>>24&255;o[E+2]=0>>16&255;o[E+1]=0>>8&255;o[E]=0&255;E=E+4;o[E+3]=A.OP_QUERY>>24&255;o[E+2]=A.OP_QUERY>>16&255;o[E+1]=A.OP_QUERY>>8&255;o[E]=A.OP_QUERY&255;E=E+4;o[E+3]=n>>24&255;o[E+2]=n>>16&255;o[E+1]=n>>8&255;o[E]=n&255;E=E+4;E=E+o.write(this.ns,E,"utf8")+1;o[E-1]=0;o[E+3]=this.numberToSkip>>24&255;o[E+2]=this.numberToSkip>>16&255;o[E+1]=this.numberToSkip>>8&255;o[E]=this.numberToSkip&255;E=E+4;o[E+3]=this.numberToReturn>>24&255;o[E+2]=this.numberToReturn>>16&255;o[E+1]=this.numberToReturn>>8&255;o[E]=this.numberToReturn&255;E=E+4;return t};Query.getRequestId=function(){return++a};var GetMore=function(e,t,r,n){n=n||{};this.numberToReturn=n.numberToReturn||0;this.requestId=a++;this.bson=e;this.ns=t;this.cursorId=r};GetMore.prototype.toBin=function(){var e=4+i.byteLength(this.ns)+1+4+8+4*4;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_GETMORE>>24&255;r[t+2]=A.OP_GETMORE>>16&255;r[t+1]=A.OP_GETMORE>>8&255;r[t]=A.OP_GETMORE&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;t=t+r.write(this.ns,t,"utf8")+1;r[t-1]=0;r[t+3]=this.numberToReturn>>24&255;r[t+2]=this.numberToReturn>>16&255;r[t+1]=this.numberToReturn>>8&255;r[t]=this.numberToReturn&255;t=t+4;r[t+3]=this.cursorId.getLowBits()>>24&255;r[t+2]=this.cursorId.getLowBits()>>16&255;r[t+1]=this.cursorId.getLowBits()>>8&255;r[t]=this.cursorId.getLowBits()&255;t=t+4;r[t+3]=this.cursorId.getHighBits()>>24&255;r[t+2]=this.cursorId.getHighBits()>>16&255;r[t+1]=this.cursorId.getHighBits()>>8&255;r[t]=this.cursorId.getHighBits()&255;t=t+4;return r};var KillCursor=function(e,t,r){this.ns=t;this.requestId=a++;this.cursorIds=r};KillCursor.prototype.toBin=function(){var e=4+4+4*4+this.cursorIds.length*8;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_KILL_CURSORS>>24&255;r[t+2]=A.OP_KILL_CURSORS>>16&255;r[t+1]=A.OP_KILL_CURSORS>>8&255;r[t]=A.OP_KILL_CURSORS&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=this.cursorIds.length>>24&255;r[t+2]=this.cursorIds.length>>16&255;r[t+1]=this.cursorIds.length>>8&255;r[t]=this.cursorIds.length&255;t=t+4;for(var n=0;n>24&255;r[t+2]=this.cursorIds[n].getLowBits()>>16&255;r[t+1]=this.cursorIds[n].getLowBits()>>8&255;r[t]=this.cursorIds[n].getLowBits()&255;t=t+4;r[t+3]=this.cursorIds[n].getHighBits()>>24&255;r[t+2]=this.cursorIds[n].getHighBits()>>16&255;r[t+1]=this.cursorIds[n].getHighBits()>>8&255;r[t]=this.cursorIds[n].getHighBits()&255;t=t+4}return r};var Response=function(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.cursorId=new s(n.readInt32LE(4),n.readInt32LE(8));this.startingFrom=n.readInt32LE(12);this.numberReturned=n.readInt32LE(16);this.documents=new Array(this.numberReturned);this.cursorNotFound=(this.responseFlags&E)!==0;this.queryFailure=(this.responseFlags&m)!==0;this.shardConfigStale=(this.responseFlags&C)!==0;this.awaitCapable=(this.responseFlags&I)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false};Response.prototype.isParsed=function(){return this.parsed};Response.prototype.parse=function(e){if(this.parsed)return;e=e||{};var t=e.raw||false;var r=e.documentsReturnedIn||null;var n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;var o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;var s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;var i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;var a,A;A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};this.index=20;for(var c=0;c{"use strict";const n=r(1808);const o=r(4404);const s=r(6096);const i=r(3111).MongoError;const a=r(3111).MongoNetworkError;const A=r(3111).MongoNetworkTimeoutError;const c=r(2192).defaultAuthProviders;const l=r(557).AuthContext;const u=r(7161);const h=r(1178).makeClientMetadata;const d=u.MAX_SUPPORTED_WIRE_VERSION;const g=u.MAX_SUPPORTED_SERVER_VERSION;const p=u.MIN_SUPPORTED_WIRE_VERSION;const E=u.MIN_SUPPORTED_SERVER_VERSION;let m;function connect(e,t,r){if(typeof t==="function"){r=t;t=undefined}const n=e&&e.connectionType?e.connectionType:s;if(m==null){m=c(e.bson)}const o=e.family!==void 0?e.family:0;makeConnection(o,e,t,((t,o)=>{if(t){r(t,o);return}performInitialHandshake(new n(o,e),e,r)}))}function isModernConnectionType(e){return!(e instanceof s)}function checkSupportedServer(e,t){const r=e&&typeof e.maxWireVersion==="number"&&e.maxWireVersion>=p;const n=e&&typeof e.minWireVersion==="number"&&e.minWireVersion<=d;if(r){if(n){return null}const r=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${g})`;return new i(r)}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 ${p} (MongoDB ${E})`;return new i(o)}function performInitialHandshake(e,t,r){const callback=function(t,n){if(t&&e){e.destroy()}r(t,n)};const n=t.credentials;if(n){if(!n.mechanism.match(/DEFAULT/i)&&!m[n.mechanism]){callback(new i(`authMechanism '${n.mechanism}' not supported`));return}}const o=new l(e,n,t);prepareHandshakeDocument(o,((r,s)=>{if(r){return callback(r)}const a=Object.assign({},t);if(t.connectTimeoutMS||t.connectionTimeout){a.socketTimeout=t.connectTimeoutMS||t.connectionTimeout}s.helloOk=!!t.useUnifiedTopology;const A=(new Date).getTime();e.command("admin.$cmd",s,a,((r,a)=>{if(r){callback(r);return}const c=a.result;if(c.ok===0){callback(new i(c));return}if("isWritablePrimary"in c){c.ismaster=c.isWritablePrimary}if(t.useUnifiedTopology&&c.helloOk){e.helloOk=true}const l=checkSupportedServer(c,t);if(l){callback(l);return}if(!isModernConnectionType(e)){if(c.compression){const r=s.compression.filter((e=>c.compression.indexOf(e)!==-1));if(r.length){e.agreedCompressor=r[0]}if(t.compression&&t.compression.zlibCompressionLevel){e.zlibCompressionLevel=t.compression.zlibCompressionLevel}}}e.ismaster=c;e.lastIsMasterMS=(new Date).getTime()-A;if(!c.arbiterOnly&&n){Object.assign(o,{response:c});const t=n.resolveAuthMechanism(c);const r=m[t.mechanism];r.auth(o,(t=>{if(t)return callback(t);callback(undefined,e)}));return}callback(undefined,e)}))}))}function prepareHandshakeDocument(e,t){const r=e.options;const n=e.connection.serverApi;const o=r.compression&&r.compression.compressors?r.compression.compressors:[];const s={[n?"hello":"ismaster"]:true,client:r.metadata||h(r),compression:o};const a=e.credentials;if(a){if(a.mechanism.match(/DEFAULT/i)&&a.username){Object.assign(s,{saslSupportedMechs:`${a.source}.${a.username}`});m["scram-sha-256"].prepare(s,e,t);return}const r=m[a.mechanism];if(r==null){return t(new i(`No AuthProvider for ${a.mechanism} defined.`))}r.prepare(s,e,t);return}t(undefined,s)}const C=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function parseConnectOptions(e,t){const r=typeof t.host==="string"?t.host:"localhost";if(r.indexOf("/")!==-1){return{path:r}}const n={family:e,host:r,port:typeof t.port==="number"?t.port:27017,rejectUnauthorized:false};return n}function parseSslOptions(e,t){const r=parseConnectOptions(e,t);for(const e in t){if(t[e]!=null&&C.indexOf(e)!==-1){r[e]=t[e]}}if(t.checkServerIdentity===false){r.checkServerIdentity=function(){return undefined}}else if(typeof t.checkServerIdentity==="function"){r.checkServerIdentity=t.checkServerIdentity}if(r.servername==null&&!n.isIP(r.host)){r.servername=r.host}return r}const I=new Set(["error","close","timeout","parseError"]);function makeConnection(e,t,r,s){const i=typeof t.ssl==="boolean"?t.ssl:false;const a=typeof t.keepAlive==="boolean"?t.keepAlive:true;let A=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;const c=typeof t.noDelay==="boolean"?t.noDelay:true;const l=typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:3e4;const u=typeof t.socketTimeoutMS==="number"?t.socketTimeoutMS:typeof t.socketTimeout==="number"?t.socketTimeout:0;const h=typeof t.rejectUnauthorized==="boolean"?t.rejectUnauthorized:true;if(A>u){A=Math.round(u/2)}let d;const callback=function(e,t){if(e&&d){d.destroy()}s(e,t)};try{if(i){d=o.connect(parseSslOptions(e,t));if(typeof d.disableRenegotiation==="function"){d.disableRenegotiation()}}else{d=n.createConnection(parseConnectOptions(e,t))}}catch(e){return callback(e)}d.setKeepAlive(a,A);d.setTimeout(l);d.setNoDelay(c);const g=i?"secureConnect":"connect";let p;function errorHandler(e){return t=>{I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}d.removeListener(g,connectHandler);callback(connectionFailureError(e,t))}}function connectHandler(){I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}if(d.authorizationError&&h){return callback(d.authorizationError)}d.setTimeout(u);callback(null,d)}I.forEach((e=>d.once(e,errorHandler(e))));if(r){p=errorHandler("cancel");r.once("cancel",p)}d.once(g,connectHandler)}function connectionFailureError(e,t){switch(e){case"error":return new a(t);case"timeout":return new A(`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.exports=connect},6096:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(6113);const s=r(7746).debugOptions;const i=r(7272).parseHeader;const a=r(7793).decompress;const A=r(9814).Response;const c=r(8988).BinMsg;const l=r(3111).MongoNetworkError;const u=r(3111).MongoNetworkTimeoutError;const h=r(3111).MongoError;const d=r(104);const g=r(7272).opcodes.OP_COMPRESSED;const p=r(7272).opcodes.OP_MSG;const E=r(7272).MESSAGE_HEADER_SIZE;const m=r(1867).Buffer;const C=r(9814).Query;const I=r(2337);let y=0;const B=1024*1024*16*4;const Q=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"];let b=undefined;let w=false;let S={};class Connection extends n{constructor(e,t){super();t=t||{};if(!t.bson){throw new TypeError("must pass in valid bson parser")}this.id=y++;this.options=t;this.logger=d("Connection",t);this.bson=t.bson;this.tag=t.tag;this.maxBsonMessageSize=t.maxBsonMessageSize||B;this.helloOk=undefined;this.port=t.port||27017;this.host=t.host||"localhost";this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.keepAlive=typeof t.keepAlive==="boolean"?t.keepAlive:true;this.keepAliveInitialDelay=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;this.connectionTimeout=typeof t.connectionTimeout==="number"?t.connectionTimeout:3e4;if(this.keepAliveInitialDelay>this.socketTimeout){this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)}if(this.logger.isDebug()){this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(Q,t))}]`)}this.responseOptions={promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false};this.flushing=false;this.queue=[];this.writeStream=null;this.destroyed=false;this.timedOut=false;const r=o.createHash("sha1");r.update(this.address);this.hashedName=r.digest("hex");this.workItems=[];this.socket=e;this.socket.once("error",errorHandler(this));this.socket.once("timeout",timeoutHandler(this));this.socket.once("close",closeHandler(this));this.socket.on("data",dataHandler(this));if(w){addConnection(this.id,this)}}setSocketTimeout(e){if(this.socket){this.socket.setTimeout(e)}}resetSocketTimeout(){if(this.socket){this.socket.setTimeout(this.socketTimeout)}}static enableConnectionAccounting(e){if(e){b=e}w=true;S={}}static disableConnectionAccounting(){w=false;b=undefined}static connections(){return S}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",(()=>this.socket.unref()));return}this.socket.unref()}flush(e){while(this.workItems.length>0){const t=this.workItems.shift();if(t.cb){t.cb(e)}}}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(w){deleteConnection(this.id)}if(this.socket==null){this.destroyed=true;return}if(e.force||this.timedOut){this.socket.destroy();this.destroyed=true;if(typeof t==="function")t(null,null);return}this.socket.end((e=>{this.destroyed=true;if(typeof t==="function")t(e,null)}))}write(e){if(this.logger.isDebug()){if(!Array.isArray(e)){this.logger.debug(`writing buffer [ ${e.length} ] to ${this.address}`)}else{for(let t=0;t{};function _callback(e,t){n(e,t);n=noop}function errorHandler(e){o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);if(e==null){e=new h(`runCommand failed for connection to '${o.address}'`)}o.on("error",noop);_callback(e)}function messageHandler(e){if(e.responseTo!==a.requestId){return}o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);e.parse({promoteValues:true});const t=e.documents[0];if(t.ok===0||t.$err||t.errmsg||t.code){_callback(new h(t));return}_callback(undefined,new I(t,this,e))}o.setSocketTimeout(s);v.forEach((e=>o.once(e,errorHandler)));o.on("message",messageHandler);o.write(a.toBin())}}const v=["error","close","timeout","parseError"];function deleteConnection(e){delete S[e];if(b){b.deleteConnection(e)}}function addConnection(e,t){S[e]=t;if(b){b.addConnection(e,t)}}function errorHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`)}e.emit("error",new l(t),e)}}function timeoutHandler(e){return function(){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] timed out`)}e.timedOut=true;e.emit("timeout",new u(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}function closeHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} with for [${e.address}] closed`)}if(!t){e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}}function processMessage(e,t){const r=i(t);if(r.opCode!==g){const n=r.opCode===p?c:A;e.emit("message",new n(e.bson,t,r,t.slice(E),e.responseOptions),e);return}r.fromCompressed=true;let n=E;r.opCode=t.readInt32LE(n);n+=4;r.length=t.readInt32LE(n);n+=4;const o=t[n];n++;a(o,t.slice(n),((n,o)=>{if(n){e.emit("error",n);return}if(o.length!==r.length){e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));return}const s=r.opCode===p?c:A;e.emit("message",new s(e.bson,t,r,o,e.responseOptions),e)}))}function dataHandler(e){return function(t){while(t.length>0){if(e.bytesRead>0&&e.sizeOfMessage>0){const r=e.sizeOfMessage-e.bytesRead;if(r>t.length){t.copy(e.buffer,e.bytesRead);e.bytesRead=e.bytesRead+t.length;t=m.alloc(0)}else{t.copy(e.buffer,e.bytesRead,0,r);t=t.slice(r);const n=e.buffer;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;processMessage(e,n)}}else{if(e.stubBuffer!=null&&e.stubBuffer.length>0){if(e.stubBuffer.length+t.length>4){const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=r;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null}else{const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=m.alloc(0)}}else{if(t.length>4){const r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",t,e);return}if(r>4&&rt.length){e.buffer=m.alloc(r);t.copy(e.buffer,0);e.bytesRead=t.length;e.sizeOfMessage=r;e.stubBuffer=null;t=m.alloc(0)}else if(r>4&&re.maxBsonMessageSize){const n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=m.alloc(0)}else{const n=t.slice(0,r);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=t.slice(r);processMessage(e,n)}}else{e.stubBuffer=m.alloc(t.length);t.copy(e.stubBuffer,0);t=m.alloc(0)}}}}}}e.exports=Connection},104:(e,t,r)=>{"use strict";var n=r(3837).format,o=r(3111).MongoError;var s={};var i={};var a=null;var A=process.pid;var c=null;var Logger=function(e,t){if(!(this instanceof Logger))return new Logger(e,t);t=t||{};this.className=e;if(t.logger){c=t.logger}else if(c==null){c=console.log}if(t.loggerLevel){a=t.loggerLevel||"error"}if(i[this.className]==null)s[this.className]=true};Logger.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","DEBUG",this.className,A,r,e);var a={type:"debug",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}};Logger.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","WARN",this.className,A,r,e);var a={type:"warn",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","INFO",this.className,A,r,e);var a={type:"info",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","ERROR",this.className,A,r,e);var a={type:"error",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.isInfo=function(){return a==="info"||a==="debug"},Logger.prototype.isError=function(){return a==="error"||a==="info"||a==="debug"},Logger.prototype.isWarn=function(){return a==="error"||a==="warn"||a==="info"||a==="debug"},Logger.prototype.isDebug=function(){return a==="debug"};Logger.reset=function(){a="error";i={}};Logger.currentLogger=function(){return c};Logger.setCurrentLogger=function(e){if(typeof e!=="function")throw new o("current logger must be a function");c=e};Logger.filter=function(e,t){if(e==="class"&&Array.isArray(t)){i={};t.forEach((function(e){i[e]=true}))}};Logger.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn"){throw new Error(n("%s is an illegal logging level",e))}a=e};e.exports=Logger},8988:(e,t,r)=>{"use strict";const n=r(1867).Buffer;const o=r(7272).opcodes;const s=r(7272).databaseNamespace;const i=r(4485);const a=r(3111).MongoError;let A=0;const c=1;const l=2;const u=1<<16;class Msg{constructor(e,t,r,n){if(r==null)throw new Error("query must be specified for query");this.bson=e;this.ns=t;this.command=r;this.command.$db=s(t);if(n.readPreference&&n.readPreference.mode!==i.PRIMARY){this.command.$readPreference=n.readPreference.toJSON()}this.options=n||{};this.requestId=n.requestId?n.requestId:Msg.getRequestId();this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checksumPresent=false;this.moreToCome=n.moreToCome||false;this.exhaustAllowed=typeof n.exhaustAllowed==="boolean"?n.exhaustAllowed:false}toBin(){const e=[];let t=0;if(this.checksumPresent){t|=c}if(this.moreToCome){t|=l}if(this.exhaustAllowed){t|=u}const r=n.alloc(4*4+4);e.push(r);let s=r.length;const i=this.command;s+=this.makeDocumentSegment(e,i);r.writeInt32LE(s,0);r.writeInt32LE(this.requestId,4);r.writeInt32LE(0,8);r.writeInt32LE(o.OP_MSG,12);r.writeUInt32LE(t,16);return e}makeDocumentSegment(e,t){const r=n.alloc(1);r[0]=0;const o=this.serializeBson(t);e.push(r);e.push(o);return r.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}Msg.getRequestId=function(){A=A+1&2147483647;return A};class BinMsg{constructor(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.checksumPresent=(this.responseFlags&c)!==0;this.moreToCome=(this.responseFlags&l)!==0;this.exhaustAllowed=(this.responseFlags&u)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false;this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{};this.index=4;const t=e.raw||false;const r=e.documentsReturnedIn||null;const n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;const o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;const s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;const i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;const A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};while(this.index{"use strict";const n=r(3837).inherits;const o=r(2361).EventEmitter;const s=r(3111).MongoError;const i=r(3111).MongoTimeoutError;const a=r(3111).MongoWriteConcernError;const A=r(104);const c=r(3837).format;const l=r(8988).Msg;const u=r(2337);const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(9815);const I=r(1867).Buffer;const y=r(6573);const B=r(5474).updateSessionFromResponse;const Q=r(1178).eachAsync;const b=r(1178).makeStateMachine;const w=r(1371).now;const S="disconnected";const v="connecting";const R="connected";const k="draining";const D="destroying";const N="destroyed";const T=b({[S]:[v,k,S],[v]:[v,R,k,S],[R]:[R,S,k],[k]:[k,D,N],[D]:[D,N],[N]:[N]});const O=new Set(["error","close","timeout","parseError","connect","message"]);var _=0;var Pool=function(e,t){o.call(this);this.topology=e;this.s={state:S,cancellationToken:new o};this.s.cancellationToken.setMaxListeners(Infinity);this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:true,keepAliveInitialDelay:12e4,noDelay:true,ssl:false,checkServerIdentity:true,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:false,promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false,reconnect:true,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:false,legacyCompatMode:true},t);this.id=_++;this.retriesLeft=this.options.reconnectTries;this.reconnectId=null;this.reconnectError=null;if(!t.bson||t.bson&&(typeof t.bson.serialize!=="function"||typeof t.bson.deserialize!=="function")){throw new Error("must pass in valid bson parser")}this.logger=A("Pool",t);this.availableConnections=[];this.inUseConnections=[];this.connectingConnections=0;this.executing=false;this.queue=[];this.numberOfConsecutiveTimeouts=0;this.connectionIndex=0;const r=this;this._messageHandler=messageHandler(this);this._connectionCloseHandler=function(e){const t=this;connectionFailureHandler(r,"close",e,t)};this._connectionErrorHandler=function(e){const t=this;connectionFailureHandler(r,"error",e,t)};this._connectionTimeoutHandler=function(e){const t=this;connectionFailureHandler(r,"timeout",e,t)};this._connectionParseErrorHandler=function(e){const t=this;connectionFailureHandler(r,"parseError",e,t)}};n(Pool,o);Object.defineProperty(Pool.prototype,"size",{enumerable:true,get:function(){return this.options.size}});Object.defineProperty(Pool.prototype,"minSize",{enumerable:true,get:function(){return this.options.minSize}});Object.defineProperty(Pool.prototype,"connectionTimeout",{enumerable:true,get:function(){return this.options.connectionTimeout}});Object.defineProperty(Pool.prototype,"socketTimeout",{enumerable:true,get:function(){return this.options.socketTimeout}});Object.defineProperty(Pool.prototype,"state",{enumerable:true,get:function(){return this.s.state}});function resetPoolState(e){e.inUseConnections=[];e.availableConnections=[];e.connectingConnections=0;e.executing=false;e.numberOfConsecutiveTimeouts=0;e.connectionIndex=0;e.retriesLeft=e.options.reconnectTries;e.reconnectId=null}function connectionFailureHandler(e,t,r,n){if(n){if(n._connectionFailHandled){return}n._connectionFailHandled=true;n.destroy();removeConnection(e,n);n.flush(r)}if(t==="timeout"){e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1;if(e.numberOfConsecutiveTimeouts>e.options.reconnectTries){e.numberOfConsecutiveTimeouts=0;e.destroy(true);return e.emit("close",e)}}if(e.socketCount()===0){if(e.state!==N&&e.state!==D&&e.state!==k){if(e.options.reconnect){T(e,S)}}t=t==="error"?"close":t;e.emit(t,r)}if(!e.reconnectId&&e.options.reconnect){e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e),e.options.reconnectInterval)}const o=totalConnectionCount(e);if(o{if(r==null){e.reconnectId=null;e.retriesLeft=e.options.reconnectTries;e.emit("reconnect",e)}if(typeof t==="function"){t(r,n)}}))}}function moveConnectionBetween(e,t,r){var n=t.indexOf(e);if(n!==-1){t.splice(n,1);r.push(e)}}function messageHandler(e){return function(t,r){var n=null;for(var o=0;o{if(t){if(typeof e==="function"){this.destroy();e(t);return}if(this.state===v){this.emit("error",t)}this.destroy();return}T(this,R);if(this.minSize){for(let e=0;e{for(const t of O){e.removeAllListeners(t)}e.on("error",(()=>{}));e.destroy(r,t)}),(t=>{if(t){if(typeof n==="function")n(t,null);return}resetPoolState(e);e.queue=[];T(e,N);if(typeof n==="function")n(null,null)}))}Pool.prototype.destroy=function(e,t){var r=this;if(typeof e==="function"){t=e;e=false}if(this.state===N||r.state===D){if(typeof t==="function")t(null,null);return}T(this,k);if(e){var n=r.availableConnections.concat(r.inUseConnections);while(r.queue.length>0){var o=r.queue.shift();if(typeof o.cb==="function"){o.cb(new s("Pool was force destroyed"))}}return destroy(r,n,{force:true},t)}if(this.reconnectId){clearTimeout(this.reconnectId)}function checkStatus(){if(r.state===N||r.state===D){if(typeof t==="function"){t()}return}flushMonitoringOperations(r.queue);if(r.queue.length===0){var e=r.availableConnections.concat(r.inUseConnections);for(var n=0;n0){return setTimeout(checkStatus,1)}}destroy(r,e,{force:false},t)}else{_execute(r)();setTimeout(checkStatus,1)}}checkStatus()};Pool.prototype.reset=function(e){if(this.s.state!==R){if(typeof e==="function"){e(new s("pool is not connected, reset aborted"))}return}this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);Q(t,((e,t)=>{for(const t of O){e.removeAllListeners(t)}e.destroy({force:true},t)}),(t=>{if(t){if(typeof e==="function"){e(t,null);return}}resetPoolState(this);createConnection(this,(()=>{if(typeof e==="function"){e(null,null)}}))}))};function serializeCommand(e,t,r){const n=t.toBin();const o=!!e.options.agreedCompressor;if(!o||!canCompress(t)){return r(null,n)}const s=I.concat(n);const i=s.slice(h);const a=s.readInt32LE(12);p(e,i,(function(n,o){if(n)return r(n,null);const s=I.alloc(h);s.writeInt32LE(h+d+o.length,0);s.writeInt32LE(t.requestId,4);s.writeInt32LE(0,8);s.writeInt32LE(g.OP_COMPRESSED,12);const A=I.alloc(d);A.writeInt32LE(a,0);A.writeInt32LE(i.length,4);A.writeUInt8(E[e.options.agreedCompressor],8);return r(null,[s,A,o])}))}Pool.prototype.write=function(e,t,r){var n=this;if(typeof t==="function"){r=t}t=t||{};if(!(typeof r==="function")&&!t.noResponse){throw new s("write method must provide a callback")}if(this.state===N||this.state===D){r(new s("pool destroyed"));return}if(this.state===k){r(new s("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r==="function"){var o=r;r=process.domain.bind((function(){var e=new Array(arguments.length);for(var t=0;t{if(t){n.emit("commandFailed",new C.CommandFailedEvent(this,e,t,i.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){n.emit("commandFailed",new C.CommandFailedEvent(this,e,o.result,i.started))}else{n.emit("commandSucceeded",new C.CommandSucceededEvent(this,e,o,i.started))}}if(typeof r==="function")r(t,o)}}serializeCommand(n,e,((e,r)=>{if(e)throw e;i.buffer=r;if(t.monitoring){n.queue.unshift(i)}else{n.queue.push(i)}if(!n.executing){process.nextTick((function(){_execute(n)()}))}}))};function canCompress(e){const t=e instanceof l?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function remove(e,t){for(var r=0;r{e.connectingConnections--;if(r){if(e.logger.isDebug()){e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`)}if(!e.reconnectId&&e.options.reconnect){if(e.state===v&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e,t),e.options.reconnectInterval);return}if(typeof t==="function"){t(r)}return}if(e.state===N||e.state===D){if(typeof t==="function"){t(new s("Pool was destroyed after connection creation"))}n.destroy();return}n.on("error",e._connectionErrorHandler);n.on("close",e._connectionCloseHandler);n.on("timeout",e._connectionTimeoutHandler);n.on("parseError",e._connectionParseErrorHandler);n.on("message",e._messageHandler);e.availableConnections.push(n);if(typeof t==="function"){t(null,n)}_execute(e)()}))}function flushMonitoringOperations(e){for(var t=0;t0){e.executing=false;return}while(true){const i=totalConnectionCount(e);if(e.availableConnections.length===0){flushMonitoringOperations(e.queue);if(i0){createConnection(e)}break}if(e.queue.length===0){break}var t=null;const a=e.availableConnections.filter((e=>e.workItems.length===0));if(a.length===0){t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]}else{t=a[e.connectionIndex++%a.length]}if(!t.isConnected()){removeConnection(e,t);flushMonitoringOperations(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=false;for(let r=0;r0){createConnection(e)}setTimeout((()=>_execute(e)()),10);break}}if(i0){e.queue.unshift(r);createConnection(e);break}}var o=r.buffer;if(r.monitoring){moveConnectionBetween(t,e.availableConnections,e.inUseConnections)}if(!r.noResponse){t.workItems.push(r)}if(!r.immediateRelease&&typeof r.socketTimeout==="number"){t.setSocketTimeout(r.socketTimeout)}var s=true;if(Array.isArray(o)){for(let e=0;e{"use strict";const n=r(1371).parsePackageVersion;const o=r(3111).MongoError;const s=r(3182)(require);function debugOptions(e,t){const r={};e.forEach((function(e){r[e]=t[e]}));return r}function retrieveBSON(){const e=r(4044);e.native=false;const t=s("bson-ext");const i=n(s("bson-ext/package.json")||{version:"0.0.0"});if(t){if(i.major>=4){throw new o("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver")}t.native=true;return t}return e}function noSnappyWarning(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}const i=Symbol("kPkgVersion");function retrieveSnappy(){const e=s("snappy");if(!e){return{compress:noSnappyWarning,uncompress:noSnappyWarning,compressSync:noSnappyWarning,uncompressSync:noSnappyWarning}}const t=s("snappy/package.json")||{version:"0.0.0"};const r=n(t);e[i]=r;if(r.major>=7){const t=e.compress;const r=e.uncompress;e.compress=(e,r)=>{t(e).then((e=>r(undefined,e))).catch((e=>r(e)))};e.uncompress=(e,t)=>{r(e).then((e=>t(undefined,e))).catch((e=>t(e)))}}return e}e.exports={PKG_VERSION:i,debugOptions:debugOptions,retrieveBSON:retrieveBSON,retrieveSnappy:retrieveSnappy}},4847:(e,t,r)=>{"use strict";const n=r(104);const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(1178).collationNotSupported;const A=r(4485);const c=r(1178).isUnifiedTopology;const l=r(2548);const u=r(2781).Readable;const h=r(1371).SUPPORTS;const d=r(1371).MongoDBNamespace;const g=r(1371).mergeOptions;const p=r(1018).OperationBase;const E=o();const m=E.Long;const C={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function handleCallback(e,t,r){try{e(t,r)}catch(t){process.nextTick((function(){throw t}))}}class CoreCursor extends u{constructor(e,t,r,o){super({objectMode:true});o=o||{};if(t instanceof p){this.operation=t;t=this.operation.ns.toString();o=this.operation.options;r=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=d.fromString(t);this.cmd=r;this.options=o;this.topology=e;this.cursorState={cursorId:null,cmd:r,documents:o.documents||[],cursorIndex:0,dead:false,killed:false,init:false,notified:false,limit:o.limit||r.limit||0,skip:o.skip||r.skip||0,batchSize:o.batchSize||r.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||r&&r.raw};if(typeof o.session==="object"){this.cursorState.session=o.session}const s=e.s.options;if(typeof s.promoteLongs==="boolean"){this.cursorState.promoteLongs=s.promoteLongs}else if(typeof o.promoteLongs==="boolean"){this.cursorState.promoteLongs=o.promoteLongs}if(typeof s.promoteValues==="boolean"){this.cursorState.promoteValues=s.promoteValues}else if(typeof o.promoteValues==="boolean"){this.cursorState.promoteValues=o.promoteValues}if(typeof s.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=s.promoteBuffers}else if(typeof o.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=o.promoteBuffers}if(typeof s.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=s.bsonRegExp}else if(typeof o.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=o.bsonRegExp}if(s.reconnect){this.cursorState.reconnect=s.reconnect}this.logger=n("Cursor",s);if(typeof r==="number"){this.cursorState.cursorId=m.fromNumber(r);this.cursorState.lastCursorId=this.cursorState.cursorId}else if(r instanceof m){this.cursorState.cursorId=r;this.cursorState.lastCursorId=r}if(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){nextFunction(this,e)}clone(){const e=g({},this.options);delete e.session;return this.topology.cursor(this.ns,this.cmd,e)}isDead(){return this.cursorState.dead===true}isKilled(){return this.cursorState.killed===true}isNotified(){return this.cursorState.notified===true}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex;const r=e0&&this.cursorState.currentLimit+n.length>this.cursorState.limit){n=n.slice(0,this.cursorState.limit-this.cursorState.currentLimit);this.kill()}this.cursorState.currentLimit=this.cursorState.currentLimit+n.length;this.cursorState.cursorIndex=this.cursorState.cursorIndex+n.length;return n}kill(e){this.cursorState.dead=true;this.cursorState.killed=true;this.cursorState.documents=[];if(this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===false){if(e)e(null,null);return}this.server.killCursors(this.ns,this.cursorState,e)}rewind(){if(this.cursorState.init){if(!this.cursorState.dead){this.kill()}this.cursorState.currentLimit=0;this.cursorState.init=false;this.cursorState.dead=false;this.cursorState.killed=false;this.cursorState.notified=false;this.cursorState.documents=[];this.cursorState.cursorId=null;this.cursorState.cursorIndex=0}}_read(){if(this.s&&this.s.state===C.CLOSED||this.isDead()){return this.push(null)}this._next(((e,t)=>{if(e){if(this.listeners("error")&&this.listeners("error").length>0){this.emit("error",e)}if(!this.isDead())this.close();this.emit("end");return this.emit("finish")}if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform==="function"&&t!=null){return this.push(this.cursorState.streamOptions.transform(t))}this.push(t);if(t===null&&this.isDead()){this.once("end",(()=>{this.close();this.emit("finish")}))}}))}_endSession(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};const r=this.cursorState.session;if(r&&(e.force||r.owner===this)){this.cursorState.session=undefined;if(this.operation){this.operation.clearSession()}r.endSession(t);return true}if(t){t()}return false}_getMore(e){if(this.logger.isDebug()){this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`)}let t=this.cursorState.batchSize;if(this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit){t=this.cursorState.limit-this.cursorState.currentLimit}const r=this.cursorState;this.server.getMore(this.ns,r,t,this.options,((t,n,o)=>{if(t||r.cursorId&&r.cursorId.isZero()){this._endSession()}e(t,n,o)}))}_initializeCursor(e){const t=this;if(c(t.topology)&&t.topology.shouldCheckForSessionSupport()){t.topology.selectServer(A.primaryPreferred,(t=>{if(t){e(t);return}this._initializeCursor(e)}));return}function done(r,n){const o=t.cursorState;if(r||o.cursorId&&o.cursorId.isZero()){t._endSession()}if(o.documents.length===0&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData){return setCursorNotified(t,e)}e(r,n)}const queryCallback=(e,r)=>{if(e){return done(e)}const n=r.message;if(Array.isArray(n.documents)&&n.documents.length===1){const e=n.documents[0];if(n.queryFailure){return done(new s(e),null)}if(!t.cmd.find||t.cmd.find&&t.cmd.virtual===false){if(e.$err||e.errmsg){return done(new s(e),null)}if(e.cursor!=null&&typeof e.cursor!=="string"){const r=e.cursor.id;if(e.cursor.ns){t.ns=e.cursor.ns}t.cursorState.cursorId=typeof r==="number"?m.fromNumber(r):r;t.cursorState.lastCursorId=t.cursorState.cursorId;t.cursorState.operationTime=e.operationTime;if(Array.isArray(e.cursor.firstBatch)){t.cursorState.documents=e.cursor.firstBatch}return done(null,n)}}}const o=n.cursorId||0;t.cursorState.cursorId=o instanceof m?o:m.fromNumber(o);t.cursorState.documents=n.documents;t.cursorState.lastCursorId=n.cursorId;if(t.cursorState.transforms&&typeof t.cursorState.transforms.query==="function"){t.cursorState.documents=t.cursorState.transforms.query(n)}done(null,n)};if(t.operation){if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}l(t.topology,t.operation,((e,r)=>{if(e){done(e);return}t.server=t.operation.server;t.cursorState.init=true;if(t.cursorState.cursorId!=null){return done()}queryCallback(e,r)}));return}const r={};if(t.cursorState.session){r.session=t.cursorState.session}if(t.operation){r.readPreference=t.operation.readPreference}else if(t.options.readPreference){r.readPreference=t.options.readPreference}return t.topology.selectServer(r,((r,n)=>{if(r){const n=t.disconnectHandler;if(n!=null){return n.addObjectAndMethod("cursor",t,"next",[e],e)}return e(r)}t.server=n;t.cursorState.init=true;if(a(t.server,t.cmd)){return e(new s(`server ${t.server.name} does not support collation`))}if(t.cursorState.cursorId!=null){return done()}if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}if(t.cmd.find!=null){n.query(t.ns,t.cmd,t.cursorState,t.options,queryCallback);return}const o=Object.assign({session:t.cursorState.session},t.options);n.command(t.ns,t.cmd,o,queryCallback)}))}}if(h.ASYNC_ITERATOR){CoreCursor.prototype[Symbol.asyncIterator]=r(1749).asyncIterator}function isConnectionDead(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=true;const r=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);_setCursorNotifiedImpl(e,(()=>t(r)));return true}return false}function isCursorDeadButNotkilled(e,t){if(e.cursorState.dead&&!e.cursorState.killed){e.cursorState.killed=true;setCursorNotified(e,t);return true}return false}function isCursorDeadAndKilled(e,t){if(e.cursorState.dead&&e.cursorState.killed){handleCallback(t,new s("cursor is dead"));return true}return false}function isCursorKilled(e,t){if(e.cursorState.killed){setCursorNotified(e,t);return true}return false}function setCursorDeadAndNotified(e,t){e.cursorState.dead=true;setCursorNotified(e,t)}function setCursorNotified(e,t){_setCursorNotifiedImpl(e,(()=>handleCallback(t,null,null)))}function _setCursorNotifiedImpl(e,t){e.cursorState.notified=true;e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.cursorState.session){e._endSession(t);return}return t()}function nextFunction(e,t){if(e.cursorState.notified){return t(new Error("cursor is exhausted"))}if(isCursorKilled(e,t))return;if(isCursorDeadButNotkilled(e,t))return;if(isCursorDeadAndKilled(e,t))return;if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect){return t(new s("no connection available"))}if(e.disconnectHandler!=null){if(e.topology.isDestroyed()){return t(new s("Topology was destroyed"))}e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor(((r,n)=>{if(r||n===null){t(r,n);return}nextFunction(e,t)}));return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)))}else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!m.ZERO.equals(e.cursorState.cursorId)){e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.topology.isDestroyed())return t(new i("connection destroyed, not possible to instantiate cursor"));if(isConnectionDead(e,t))return;e._getMore((function(r,n,o){if(r){return handleCallback(t,r)}e.connection=o;if(e.cursorState.documents.length===0&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===0&&e.cmd.tailable&&!m.ZERO.equals(e.cursorState.cursorId)){return nextFunction(e,t)}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){return setCursorDeadAndNotified(e,t)}nextFunction(e,t)}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&m.ZERO.equals(e.cursorState.cursorId)){setCursorDeadAndNotified(e,t)}else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill((()=>setCursorDeadAndNotified(e,(function(){handleCallback(t,new s(r?r.$err:undefined))}))));return}if(e.cursorState.transforms&&typeof e.cursorState.transforms.doc==="function"){r=e.cursorState.transforms.doc(r)}handleCallback(t,null,r)}}e.exports={CursorState:C,CoreCursor:CoreCursor}},3111:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=Symbol("errorLabels");class MongoError extends Error{constructor(e){if(e instanceof Error){super(e.message);this.stack=e.stack}else{if(typeof e==="string"){super(e)}else{super(e.message||e.errmsg||e.$err||"n/a");if(e.errorLabels){this[o]=new Set(e.errorLabels)}for(var t in e){if(t==="errorLabels"||t==="errmsg"){continue}this[t]=e[t]}}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new MongoError(e)}hasErrorLabel(e){if(this[o]==null){return false}return this[o].has(e)}addErrorLabel(e){if(this[o]==null){this[o]=new Set}this[o].add(e)}get errorLabels(){return this[o]?Array.from(this[o]):[]}}const s=Symbol("beforeHandshake");function isNetworkErrorBeforeHandshake(e){return e[s]===true}class MongoNetworkError extends MongoError{constructor(e,t){super(e);this.name="MongoNetworkError";if(t&&typeof t.beforeHandshake==="boolean"){this[s]=t.beforeHandshake}}}class MongoNetworkTimeoutError extends MongoNetworkError{constructor(e,t){super(e,t);this.name="MongoNetworkTimeoutError"}}class MongoParseError extends MongoError{constructor(e){super(e);this.name="MongoParseError"}}class MongoTimeoutError extends MongoError{constructor(e,t){if(t&&t.error){super(t.error.message||t.error)}else{super(e)}this.name="MongoTimeoutError";if(t){this.reason=t}}}class MongoServerSelectionError extends MongoTimeoutError{constructor(e,t){super(e,t);this.name="MongoServerSelectionError"}}function makeWriteConcernResultObject(e){const t=Object.assign({},e);if(t.ok===0){t.ok=1;delete t.errmsg;delete t.code;delete t.codeName}return t}class MongoWriteConcernError extends MongoError{constructor(e,t){super(e);this.name="MongoWriteConcernError";if(t&&Array.isArray(t.errorLabels)){this[o]=new Set(t.errorLabels)}if(t!=null){this.result=makeWriteConcernResultObject(t)}}}const i=new Set([n.HostUnreachable,n.HostNotFound,n.NetworkTimeout,n.ShutdownInProgress,n.PrimarySteppedDown,n.SocketException,n.NotMaster,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary]);const a=new Set([n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMaster,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary,n.PrimarySteppedDown,n.ShutdownInProgress,n.HostNotFound,n.HostUnreachable,n.NetworkTimeout,n.SocketException,n.ExceededTimeLimit]);function isRetryableEndTransactionError(e){return e.hasErrorLabel("RetryableWriteError")}function isRetryableWriteError(e){if(e instanceof MongoWriteConcernError){return a.has(e.code)||a.has(e.result.code)}return a.has(e.code)}function isRetryableError(e){return i.has(e.code)||e instanceof MongoNetworkError||e.message.match(/not master/)||e.message.match(/node is recovering/)}const A=new Set([n.ShutdownInProgress,n.PrimarySteppedDown,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterOrSecondary]);const c=new Set([n.NotMaster,n.NotMasterNoSlaveOk,n.LegacyNotPrimary]);const l=new Set([n.InterruptedAtShutdown,n.ShutdownInProgress]);function isRecoveringError(e){if(typeof e.code==="number"){return A.has(e.code)}return/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}function isNotMasterError(e){if(typeof e.code==="number"){return c.has(e.code)}if(isRecoveringError(e)){return false}return/not master/.test(e.message)}function isNodeShuttingDownError(e){return e.code&&l.has(e.code)}function isSDAMUnrecoverableError(e){if(e instanceof MongoParseError||e==null){return true}return isRecoveringError(e)||isNotMasterError(e)}e.exports={MongoError:MongoError,MongoNetworkError:MongoNetworkError,MongoNetworkTimeoutError:MongoNetworkTimeoutError,MongoParseError:MongoParseError,MongoTimeoutError:MongoTimeoutError,MongoServerSelectionError:MongoServerSelectionError,MongoWriteConcernError:MongoWriteConcernError,isRetryableError:isRetryableError,isSDAMUnrecoverableError:isSDAMUnrecoverableError,isNodeShuttingDownError:isNodeShuttingDownError,isRetryableWriteError:isRetryableWriteError,isNetworkErrorBeforeHandshake:isNetworkErrorBeforeHandshake,isRetryableEndTransactionError:isRetryableEndTransactionError}},3994:(e,t,r)=>{"use strict";let n=r(4044);const o=r(3182)(require);const s=r(1178).retrieveEJSON();try{const e=o("bson-ext");if(e){n=e}}catch(e){}const i=Object.freeze({v1:"1"});const a=Object.keys(i).map((e=>i[e]));e.exports={ServerApiVersion:i,ValidServerApiVersions:a,MongoError:r(3111).MongoError,MongoNetworkError:r(3111).MongoNetworkError,MongoParseError:r(3111).MongoParseError,MongoTimeoutError:r(3111).MongoTimeoutError,MongoServerSelectionError:r(3111).MongoServerSelectionError,MongoWriteConcernError:r(3111).MongoWriteConcernError,Connection:r(6096),Server:r(6495),ReplSet:r(1134),Mongos:r(8175),Logger:r(104),Cursor:r(4847).CoreCursor,ReadPreference:r(4485),Sessions:r(5474),BSON:n,EJSON:s,Topology:r(4149).Topology,Query:r(9814).Query,MongoCredentials:r(2222).MongoCredentials,defaultAuthProviders:r(2192).defaultAuthProviders,MongoCR:r(4228),X509:r(7324),Plain:r(8728),GSSAPI:r(2640),ScramSHA1:r(864).ScramSHA1,ScramSHA256:r(864).ScramSHA256,parseConnectionString:r(8767)}},2291:e=>{"use strict";const t="closing";const r="closed";const n="connecting";const o="connected";const s={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};const i={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function serverType(e){let t=e.s.description||e.s.serverDescription;if(t.topologyType===s.Single)return t.servers[0].type;return t.type}const a={useUnifiedTopology:true,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function drainTimerQueue(e){e.forEach(clearTimeout);e.clear()}function clearAndRemoveTimerFrom(e,t){clearTimeout(e);return t.delete(e)}e.exports={STATE_CLOSING:t,STATE_CLOSED:r,STATE_CONNECTING:n,STATE_CONNECTED:o,TOPOLOGY_DEFAULTS:a,TopologyType:s,ServerType:i,serverType:serverType,drainTimerQueue:drainTimerQueue,clearAndRemoveTimerFrom:clearAndRemoveTimerFrom}},2785:e=>{"use strict";class ServerDescriptionChangedEvent{constructor(e,t,r,n){Object.assign(this,{topologyId:e,address:t,previousDescription:r,newDescription:n})}}class ServerOpeningEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class ServerClosedEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class TopologyDescriptionChangedEvent{constructor(e,t,r){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:r})}}class TopologyOpeningEvent{constructor(e){Object.assign(this,{topologyId:e})}}class TopologyClosedEvent{constructor(e){Object.assign(this,{topologyId:e})}}class ServerHeartbeatStartedEvent{constructor(e){Object.assign(this,{connectionId:e})}}class ServerHeartbeatSucceededEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,reply:t})}}class ServerHeartbeatFailedEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,failure:t})}}e.exports={ServerDescriptionChangedEvent:ServerDescriptionChangedEvent,ServerOpeningEvent:ServerOpeningEvent,ServerClosedEvent:ServerClosedEvent,TopologyDescriptionChangedEvent:TopologyDescriptionChangedEvent,TopologyOpeningEvent:TopologyOpeningEvent,TopologyClosedEvent:TopologyClosedEvent,ServerHeartbeatStartedEvent:ServerHeartbeatStartedEvent,ServerHeartbeatSucceededEvent:ServerHeartbeatSucceededEvent,ServerHeartbeatFailedEvent:ServerHeartbeatFailedEvent}},1203:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(2361);const s=r(6573);const i=r(9820).Connection;const a=r(2291);const A=r(1178).makeStateMachine;const c=r(3111).MongoNetworkError;const l=r(7746).retrieveBSON();const u=r(1371).makeInterruptableAsyncInterval;const h=r(1371).calculateDurationInMs;const d=r(1371).now;const g=r(2785);const p=g.ServerHeartbeatStartedEvent;const E=g.ServerHeartbeatSucceededEvent;const m=g.ServerHeartbeatFailedEvent;const C=Symbol("server");const I=Symbol("monitorId");const y=Symbol("connection");const B=Symbol("cancellationToken");const Q=Symbol("rttPinger");const b=Symbol("roundTripTime");const w=a.STATE_CLOSED;const S=a.STATE_CLOSING;const v="idle";const R="monitoring";const k=A({[S]:[S,v,w],[w]:[w,R],[v]:[v,R,S],[R]:[R,v,S]});const D=new Set([S,w,R]);function isInCloseState(e){return e.s.state===w||e.s.state===S}class Monitor extends o{constructor(e,t){super(t);this[C]=e;this[y]=undefined;this[B]=new o;this[B].setMaxListeners(Infinity);this[I]=null;this.s={state:w};this.address=e.description.address;this.options=Object.freeze({connectTimeoutMS:typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof t.heartbeatFrequencyMS==="number"?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof t.minHeartbeatFrequencyMS==="number"?t.minHeartbeatFrequencyMS:500,useUnifiedTopology:t.useUnifiedTopology});const r=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:false,promoteLongs:true,promoteValues:true,promoteBuffers:true,bsonRegExp:true});delete r.credentials;delete r.autoEncrypter;this.connectOptions=Object.freeze(r)}connect(){if(this.s.state!==w){return}const e=this.options.heartbeatFrequencyMS;const t=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:e,minInterval:t,immediate:true})}requestCheck(){if(D.has(this.s.state)){return}this[I].wake()}reset(){const e=this[C].description.topologyVersion;if(isInCloseState(this)||e==null){return}k(this,S);resetMonitorState(this);k(this,v);const t=this.options.heartbeatFrequencyMS;const r=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:t,minInterval:r})}close(){if(isInCloseState(this)){return}k(this,S);resetMonitorState(this);this.emit("close");k(this,w)}}function resetMonitorState(e){if(e[I]){e[I].stop();e[I]=null}if(e[Q]){e[Q].close();e[Q]=undefined}e[B].emit("cancel");if(e[I]){clearTimeout(e[I]);e[I]=undefined}if(e[y]){e[y].destroy({force:true})}}function checkServer(e,t){let r=d();e.emit("serverHeartbeatStarted",new p(e.address));function failureHandler(n){if(e[y]){e[y].destroy({force:true});e[y]=undefined}e.emit("serverHeartbeatFailed",new m(h(r),n,e.address));e.emit("resetServer",n);e.emit("resetConnectionPool");t(n)}if(e[y]!=null&&!e[y].closed){const n=e.options.connectTimeoutMS;const o=e.options.heartbeatFrequencyMS;const s=e[C].description.topologyVersion;const i=s!=null;const a=e[y].serverApi;const A=e[y].helloOk;const c={[a||A?"hello":"ismaster"]:true};if(A)c.helloOk=A;const l={socketTimeout:n};if(i){c.maxAwaitTimeMS=o;c.topologyVersion=makeTopologyVersion(s);if(n){l.socketTimeout=n+o}l.exhaustAllowed=true;if(e[Q]==null){e[Q]=new RTTPinger(e[B],e.connectOptions)}}e[y].command("admin.$cmd",c,l,((n,o)=>{if(n){failureHandler(n);return}const s=o.result;const a=e[Q];if("isWritablePrimary"in s){s.ismaster=s.isWritablePrimary}const A=i&&a?a.roundTripTime:h(r);e.emit("serverHeartbeatSucceeded",new E(A,s,e.address));if(i&&s.topologyVersion){e.emit("serverHeartbeatStarted",new p(e.address));r=d()}else{if(e[Q]){e[Q].close();e[Q]=undefined}t(undefined,s)}}));return}s(e.connectOptions,e[B],((n,o)=>{if(o&&isInCloseState(e)){o.destroy({force:true});return}if(n){e[y]=undefined;if(!(n instanceof c)){e.emit("resetConnectionPool")}failureHandler(n);return}e[y]=o;e.emit("serverHeartbeatSucceeded",new E(h(r),o.ismaster,e.address));t(undefined,o.ismaster)}))}function monitorServer(e){return t=>{k(e,R);function done(){if(!isInCloseState(e)){k(e,v)}t()}process.nextTick((()=>e.emit("monitoring",e[C])));checkServer(e,((t,r)=>{if(t){if(e[C].description.type===n.Unknown){e.emit("resetServer",t);return done()}}if(r&&r.topologyVersion){setTimeout((()=>{if(!isInCloseState(e)){e[I].wake()}}))}done()}))}}function makeTopologyVersion(e){return{processId:e.processId,counter:l.Long.fromNumber(e.counter)}}class RTTPinger{constructor(e,t){this[y]=null;this[B]=e;this[b]=0;this.closed=false;const r=t.heartbeatFrequencyMS;this[I]=setTimeout((()=>measureRoundTripTime(this,t)),r)}get roundTripTime(){return this[b]}close(){this.closed=true;clearTimeout(this[I]);this[I]=undefined;if(this[y]){this[y].destroy({force:true})}}}function measureRoundTripTime(e,t){const r=d();const n=e[B];const o=t.heartbeatFrequencyMS;if(e.closed){return}function measureAndReschedule(n){if(e.closed){n.destroy({force:true});return}if(e[y]==null){e[y]=n}e[b]=h(r);e[I]=setTimeout((()=>measureRoundTripTime(e,t)),o)}if(e[y]==null){s(t,n,((t,r)=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule(r)}));return}e[y].command("admin.$cmd",{ismaster:1},(t=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule()}))}e.exports={Monitor:Monitor}},7062:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2529).ConnectionPool;const s=r(897).CMAP_EVENT_NAMES;const i=r(3111).MongoError;const a=r(1178).relayEvents;const A=r(7746).retrieveBSON();const c=r(104);const l=r(750).ServerDescription;const u=r(750).compareTopologyVersion;const h=r(4485);const d=r(1203).Monitor;const g=r(3111).MongoNetworkError;const p=r(3111).MongoNetworkTimeoutError;const E=r(1178).collationNotSupported;const m=r(7746).debugOptions;const C=r(3111).isSDAMUnrecoverableError;const I=r(3111).isRetryableWriteError;const y=r(3111).isNodeShuttingDownError;const B=r(3111).isNetworkErrorBeforeHandshake;const Q=r(1178).maxWireVersion;const b=r(1178).makeStateMachine;const w=r(7703).extractCommand;const S=r(2291);const v=S.ServerType;const R=r(1707).isTransactionCommand;const k=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];const D=S.STATE_CLOSING;const N=S.STATE_CLOSED;const T=S.STATE_CONNECTING;const O=S.STATE_CONNECTED;const _=b({[N]:[N,T],[T]:[T,D,O,N],[O]:[O,D,N],[D]:[D,N]});const M=Symbol("monitor");class Server extends n{constructor(e,t,r){super();this.s={description:e,options:t,logger:c("Server",t),bson:t.bson||new A([A.Binary,A.Code,A.DBRef,A.Decimal128,A.Double,A.Int32,A.Long,A.Map,A.MaxKey,A.MinKey,A.ObjectId,A.BSONRegExp,A.Symbol,A.Timestamp]),state:N,credentials:t.credentials,topology:r};this.serverApi=t.serverApi;const n=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(n);a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s));this.s.pool.on("clusterTimeReceived",(e=>{this.clusterTime=e}));this[M]=new d(this,this.s.options);a(this[M],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]);this[M].on("resetConnectionPool",(()=>{this.s.pool.clear()}));this[M].on("resetServer",(e=>markServerUnknown(this,e)));this[M].on("serverHeartbeatSucceeded",(e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:calculateRoundTripTime(this.description.roundTripTime,e.duration)}));if(this.s.state===T){_(this,O);this.emit("connect",this)}}))}get description(){return this.s.description}get supportsRetryableWrites(){return supportsRetryableWrites(this)}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter){return this.s.options.autoEncrypter}return null}connect(){if(this.s.state!==N){return}_(this,T);this[M].connect()}destroy(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{force:false},e);if(this.s.state===N){if(typeof t==="function"){t()}return}_(this,D);this[M].close();this.s.pool.close(e,(e=>{_(this,N);this.emit("closed");if(typeof t==="function"){t(e)}}))}requestCheck(){this[M].requestCheck()}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}r.serverApi=this.serverApi;if(this.s.state===D||this.s.state===N){n(new i("server is closed"));return}const o=basicReadValidations(this,r);if(o){return n(o)}r=Object.assign({},r,{wireProtocolCommand:false});if(this.s.logger.isDebug()){const n=w(t);this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:m(k,r)})}] against ${this.name}`)}if(E(this,t)){n(new i(`server ${this.name} does not support collation`));return}this.s.pool.withConnection(((n,o,s)=>{if(n){markServerUnknown(this,n);return s(n)}o.command(e,t,r,makeOperationHandler(this,o,t,r,s))}),n)}query(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.query(e,t,r,n,makeOperationHandler(this,s,t,n,i))}),o)}getMore(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.getMore(e,t,r,n,makeOperationHandler(this,s,null,n,i))}),o)}killCursors(e,t,r){if(this.s.state===D||this.s.state===N){if(typeof r==="function"){r(new i("server is closed"))}return}this.s.pool.withConnection(((r,n,o)=>{if(r){markServerUnknown(this,r);return o(r)}n.killCursors(e,t,makeOperationHandler(this,n,null,undefined,o))}),r)}insert(e,t,r,n){executeWriteOperation({server:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({server:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({server:this,op:"remove",ns:e,ops:t},r,n)}}Object.defineProperty(Server.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function supportsRetryableWrites(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==v.Standalone}function calculateRoundTripTime(e,t){if(e===-1){return t}const r=.2;return r*t+(1-r)*e}function basicReadValidations(e,t){if(t.readPreference&&!(t.readPreference instanceof h)){return new i("readPreference must be an instance of ReadPreference")}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.server;const o=e.op;const s=e.ns;const a=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===D||n.s.state===N){r(new i("server is closed"));return}if(E(n,t)){r(new i(`server ${n.name} does not support collation`));return}const A=t.writeConcern&&t.writeConcern.w===0;if(A||Q(n)<5){if((o==="update"||o==="remove")&&a.find((e=>e.hint))){r(new i(`servers < 3.4 do not support hint on ${o}`));return}}n.s.pool.withConnection(((e,r,i)=>{if(e){markServerUnknown(n,e);return i(e)}r[o](s,a,t,makeOperationHandler(n,r,a,t,i))}),r)}function markServerUnknown(e,t){if(t instanceof g&&!(t instanceof p)){e[M].reset()}e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function connectionIsStale(e,t){return t.generation!==e.generation}function shouldHandleStateChangeError(e,t){const r=t.topologyVersion;const n=e.description.topologyVersion;return u(n,r)<0}function inActiveTransaction(e,t){return e&&e.inTransaction()&&!R(t)}function makeOperationHandler(e,t,r,n,o){const s=n&&n.session;return function handleOperationResult(n,i){if(n&&!connectionIsStale(e.s.pool,t)){if(n instanceof g){if(s&&!s.hasEnded){s.serverSession.isDirty=true}if(supportsRetryableWrites(e)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(!(n instanceof p)||B(n)){markServerUnknown(e,n);e.s.pool.clear()}}else{if(Q(e)<9&&I(n)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(C(n)){if(shouldHandleStateChangeError(e,n)){if(Q(e)<=7||y(n)){e.s.pool.clear()}markServerUnknown(e,n);process.nextTick((()=>e.requestCheck()))}}}}o(n,i)}}e.exports={Server:Server}},750:(e,t,r)=>{"use strict";const n=r(1178).arrayStrictEqual;const o=r(1178).tagsStrictEqual;const s=r(1178).errorStrictEqual;const i=r(2291).ServerType;const a=r(1371).now;const A=new Set([i.RSPrimary,i.Standalone,i.Mongos]);const c=new Set([i.RSPrimary,i.RSSecondary,i.Mongos,i.Standalone]);const l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];class ServerDescription{constructor(e,t,r){r=r||{};t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t);if(t.isWritablePrimary!=null){t.ismaster=t.isWritablePrimary}this.address=e;this.error=r.error;this.roundTripTime=r.roundTripTime||-1;this.lastUpdateTime=a();this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null;this.opTime=t.lastWrite?t.lastWrite.opTime:null;this.type=parseServerType(t);this.topologyVersion=r.topologyVersion||t.topologyVersion;l.forEach((e=>{if(typeof t[e]!=="undefined")this[e]=t[e]}));if(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 c.has(this.type)}get isWritable(){return A.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||compareTopologyVersion(this.topologyVersion,e.topologyVersion)===0;return e!=null&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&n(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}}function parseServerType(e){if(!e||!e.ok){return i.Unknown}if(e.isreplicaset){return i.RSGhost}if(e.msg&&e.msg==="isdbgrid"){return i.Mongos}if(e.setName){if(e.hidden){return i.RSOther}else if(e.ismaster){return i.RSPrimary}else if(e.secondary){return i.RSSecondary}else if(e.arbiterOnly){return i.RSArbiter}else{return i.RSOther}}return i.Standalone}function compareTopologyVersion(e,t){if(e==null||t==null){return-1}if(e.processId.equals(t.processId)){if(e.counter===t.counter){return 0}else if(e.counter{"use strict";const n=r(2291).ServerType;const o=r(2291).TopologyType;const s=r(4485);const i=r(3111).MongoError;const a=1e4;const A=90;function writableServerSelector(){return function(e,t){return latencyWindowReducer(e,t.filter((e=>e.isWritable)))}}function maxStalenessReducer(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0){return r}const n=e.maxStalenessSeconds;const s=(t.heartbeatFrequencyMS+a)/1e3;if(n{const s=o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}if(t.type===o.ReplicaSetNoPrimary){if(r.length===0){return r}const n=r.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return r.reduce(((r,o)=>{const s=n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}return r}function tagSetMatch(e,t){const r=Object.keys(e);const n=Object.keys(t);for(let o=0;o{if(tagSetMatch(n,t.tags))e.push(t);return e}),[]);if(o.length){return o}}return[]}function latencyWindowReducer(e,t){const r=t.reduce(((e,t)=>e===-1?t.roundTripTime:Math.min(t.roundTripTime,e)),-1);const n=r+e.localThresholdMS;return t.reduce(((e,t)=>{if(t.roundTripTime<=n&&t.roundTripTime>=r)e.push(t);return e}),[])}function primaryFilter(e){return e.type===n.RSPrimary}function secondaryFilter(e){return e.type===n.RSSecondary}function nearestFilter(e){return e.type===n.RSSecondary||e.type===n.RSPrimary}function knownFilter(e){return e.type!==n.Unknown}function readPreferenceServerSelector(e){if(!e.isValid()){throw new TypeError("Invalid read preference specified")}return function(t,r){const n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n){throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`)}if(t.type===o.Unknown){return[]}if(t.type===o.Single||t.type===o.Sharded){return latencyWindowReducer(t,r.filter(knownFilter))}const a=e.mode;if(a===s.PRIMARY){return r.filter(primaryFilter)}if(a===s.PRIMARY_PREFERRED){const e=r.filter(primaryFilter);if(e.length){return e}}const A=a===s.NEAREST?nearestFilter:secondaryFilter;const c=latencyWindowReducer(t,tagSetReducer(e,maxStalenessReducer(e,t,r.filter(A))));if(a===s.SECONDARY_PREFERRED&&c.length===0){return r.filter(primaryFilter)}return c}}e.exports={writableServerSelector:writableServerSelector,readPreferenceServerSelector:readPreferenceServerSelector}},9663:(e,t,r)=>{"use strict";var n;const o=r(104);const s=r(2361).EventEmitter;const i=r(7578);function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}class SrvPollingEvent{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map((e=>`${e.name}:${e.port}`)))}}class SrvPoller extends s{constructor(e){super();if(!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=o("srvPoller",e);this.haMode=false;this.generation=0;this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){if(!this._timeout){this.schedule()}}stop(){if(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=false;this.schedule();this.emit("srvRecordDiscovery",new SrvPollingEvent(e))}failure(e,t){this.logger.warn(e,t);this.haMode=true;this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,((t,r)=>{if(e!==this.generation){return}if(t){this.failure("DNS error",t);return}const n=[];r.forEach((e=>{if(matchesParentDomain(e.name,this.srvHost)){n.push(e)}else{this.parentDomainMismatch(e)}}));if(!n.length){this.failure("No valid addresses found at host");return}this.success(n)}))}}n=SrvPollingEvent;e.exports.D=SrvPoller},4149:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(750).ServerDescription;const i=r(2291).ServerType;const a=r(7962).TopologyDescription;const A=r(2291).TopologyType;const c=r(2785);const l=r(7062).Server;const u=r(1178).relayEvents;const h=r(4485);const d=r(4847).CoreCursor;const g=r(3837).deprecate;const p=r(7746).retrieveBSON();const E=r(2306).createCompressionInfo;const m=r(5474).ClientSession;const C=r(3111).MongoError;const I=r(3111).MongoServerSelectionError;const y=r(2306).resolveClusterTime;const B=r(9663).D;const Q=r(2306).getMMAPError;const b=r(1178).makeStateMachine;const w=r(1178).eachAsync;const S=r(1371).emitDeprecationWarning;const v=r(5474).ServerSessionPool;const R=r(1178).makeClientMetadata;const k=r(897).CMAP_EVENT_NAMES;const D=r(750).compareTopologyVersion;const N=r(1371).emitWarning;const T=r(2291);const O=T.drainTimerQueue;const _=T.clearAndRemoveTimerFrom;const M=r(4547);const L=M.readPreferenceServerSelector;const F=M.writableServerSelector;let U=0;const P=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(k);const G=["connect","descriptionReceived","close","ended"];const Y=T.STATE_CLOSING;const V=T.STATE_CLOSED;const W=T.STATE_CONNECTING;const J=T.STATE_CONNECTED;const q=b({[V]:[V,W],[W]:[W,Y,J,V],[J]:[J,Y,V],[Y]:[Y,V]});const j=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]);const z=Symbol("cancelled");const $=Symbol("waitQueue");class Topology extends o{constructor(e,t){super();if(typeof t==="undefined"&&typeof e!=="string"){t=e;e=[];if(t.host){e.push({host:t.host,port:t.port})}}e=e||[];if(typeof e==="string"){e=parseStringSeedlist(e)}t=Object.assign({},T.TOPOLOGY_DEFAULTS,t);t=Object.freeze(Object.assign(t,{metadata:R(t),compression:{compressors:E(t)}}));j.forEach((e=>{if(t[e]){S(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}));const r=topologyTypeFromSeedlist(e,t);const o=U++;const i=e.reduce(((e,t)=>{if(t.domain_socket)t.host=t.domain_socket;const r=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;e.set(r,new s(r));return e}),new Map);this[$]=new n;this.s={id:o,options:t,seedlist:e,state:V,description:new a(r,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new p([p.Binary,p.Code,p.DBRef,p.Decimal128,p.Double,p.Int32,p.Long,p.Map,p.MaxKey,p.MinKey,p.ObjectId,p.BSONRegExp,p.Symbol,p.Timestamp]),servers:new Map,sessionPool:new v(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set};this.serverApi=t.serverApi;if(t.srvHost){this.s.srvPoller=t.srvPoller||new B({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel});this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type;const r=e.newDescription.type;if(t!==A.Sharded&&r===A.Sharded){this.s.handleSrvPolling=srvPollingHandler(this);this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling);this.s.srvPoller.start()}};this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)}this.setMaxListeners(Infinity)}get description(){return this.s.description}get parserType(){return p.native?"c++":"js"}connect(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.s.state===J){if(typeof t==="function"){t()}return}q(this,W);this.emit("topologyOpening",new c.TopologyOpeningEvent(this.s.id));this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,new a(A.Unknown),this.s.description));connectServers(this,Array.from(this.s.description.servers.values()));h.translate(e);const r=e.readPreference||h.primary;const connectHandler=e=>{if(e){this.close();if(typeof t==="function"){t(e)}else{this.emit("error",e)}return}q(this,J);this.emit("open",e,this);this.emit("connect",this);if(typeof t==="function")t(e,this)};if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:r},connectHandler);return}this.selectServer(L(r),e,connectHandler)}close(e,t){if(typeof e==="function"){t=e;e={}}if(typeof e==="boolean"){e={force:e}}e=e||{};if(this.s.state===V||this.s.state===Y){if(typeof t==="function"){t()}return}q(this,Y);drainWaitQueue(this[$],new C("Topology closed"));O(this.s.connectionTimers);if(this.s.srvPoller){this.s.srvPoller.stop();if(this.s.handleSrvPolling){this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling);delete this.s.handleSrvPolling}}if(this.s.detectTopologyDescriptionChange){this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange);delete this.s.detectTopologyDescriptionChange}this.s.sessions.forEach((e=>e.endSession()));this.s.sessionPool.endAllPooledSessions((()=>{w(Array.from(this.s.servers.values()),((t,r)=>destroyServer(t,this,e,r)),(e=>{this.s.servers.clear();this.emit("topologyClosed",new c.TopologyClosedEvent(this.s.id));q(this,V);if(typeof t==="function"){t(e)}}))}))}selectServer(e,t,r){if(typeof t==="function"){r=t;if(typeof e!=="function"){t=e;let r;if(e instanceof h){r=e}else if(typeof e==="string"){r=new h(e)}else{h.translate(t);r=t.readPreference||h.primary}e=L(r)}else{t={}}}t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const n=this.description.type===A.Sharded;const o=t.session;const s=o&&o.transaction;if(n&&s&&s.server){r(undefined,s.server);return}let i=e;if(typeof e==="object"){const t=e.readPreference?e.readPreference:h.primary;i=L(t)}const a={serverSelector:i,transaction:s,callback:r};const c=t.serverSelectionTimeoutMS;if(c){a.timer=setTimeout((()=>{a[z]=true;a.timer=undefined;const e=new I(`Server selection timed out after ${c} ms`,this.description);a.callback(e)}),c)}this[$].push(a);processWaitQueue(this)}shouldCheckForSessionSupport(){if(this.description.type===A.Single){return!this.description.hasKnownServers}return!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new m(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){if(!Array.isArray(e)){e=[e]}this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:true,serverApi:this.serverApi},(()=>{if(typeof t==="function")t()}))}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address)){return}if(isStaleServerDescription(this.s.description,e)){return}const t=this.s.description;const r=this.s.description.servers.get(e.address);const n=e.$clusterTime;if(n){y(this,n)}const o=r&&r.equals(e);this.s.description=this.s.description.update(e);if(this.s.description.compatibilityError){this.emit("error",new C(this.s.description.compatibilityError));return}if(!o){this.emit("serverDescriptionChanged",new c.ServerDescriptionChangedEvent(this.s.id,e.address,r,this.s.description.servers.get(e.address)))}updateServers(this,e);if(this[$].length>0){processWaitQueue(this)}if(!o){this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){if(typeof e==="function")t=e,e=null;if(typeof t==="function")t(null,true)}logout(e){if(typeof e==="function")e(null,true)}insert(e,t,r,n){executeWriteOperation({topology:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({topology:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({topology:this,op:"remove",ns:e,ops:t},r,n)}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}h.translate(r);const o=r.readPreference||h.primary;this.selectServer(L(o),r,((o,s)=>{if(o){n(o);return}const i=!r.retrying;const a=!!r.retryWrites;const A=!!r.session;const c=s.supportsRetryableWrites;const l=!A||!r.session.inTransaction();const u=i&&a&&A&&c&&l&&isWriteCommand(t);const cb=(o,s)=>{if(!o)return n(null,s);if(!shouldRetryOperation(o)){return n(o)}if(u){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}return n(o)};if(u){r.session.incrementTransactionNumber();r.willRetryWrite=u}s.command(e,t,r,cb)}))}cursor(e,t,r){r=r||{};const n=r.topology||this;const o=r.cursorFactory||this.s.Cursor;h.translate(r);return new o(n,e,t,r)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===J}isDestroyed(){return this.s.state===V}unref(){N("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(e.length===0)return{};const t=e.filter((e=>e.type!==i.Unknown))[0];const r=t||{maxWireVersion:this.description.commonWireVersion};return r}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(Topology.prototype,"clusterTime",{enumerable:true,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});Topology.prototype.destroy=g(Topology.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function isWriteCommand(e){return K.some((t=>e[t]))}function isStaleServerDescription(e,t){const r=e.servers.get(t.address);const n=r.topologyVersion;return D(n,t.topologyVersion)>0}function destroyServer(e,t,r,n){r=r||{};G.forEach((t=>e.removeAllListeners(t)));e.destroy(r,(()=>{t.emit("serverClosed",new c.ServerClosedEvent(t.s.id,e.description.address));P.forEach((t=>e.removeAllListeners(t)));if(typeof n==="function"){n()}}))}function parseStringSeedlist(e){return e.split(",").map((e=>({host:e.split(":")[0],port:e.split(":")[1]||27017})))}function topologyTypeFromSeedlist(e,t){if(t.directConnection){return A.Single}const r=t.replicaSet||t.setName||t.rs_name;if(r==null){return A.Unknown}return A.ReplicaSetNoPrimary}function randomSelection(e){return e[Math.floor(Math.random()*e.length)]}function createAndConnectServer(e,t,r){e.emit("serverOpening",new c.ServerOpeningEvent(e.s.id,t.address));const n=new l(t,e.s.options,e);u(n,e,P);n.on("descriptionReceived",e.serverUpdateHandler.bind(e));if(r){const t=setTimeout((()=>{_(t,e.s.connectionTimers);n.connect()}),r);e.s.connectionTimers.add(t);return n}n.connect();return n}function connectServers(e,t){e.s.servers=t.reduce(((t,r)=>{const n=createAndConnectServer(e,r);t.set(r.address,n);return t}),new Map)}function updateServers(e,t){if(t&&e.s.servers.has(t.address)){const r=e.s.servers.get(t.address);r.s.description=t}for(const t of e.description.servers.values()){if(!e.s.servers.has(t.address)){const r=createAndConnectServer(e,t);e.s.servers.set(t.address,r)}}for(const t of e.s.servers){const r=t[0];if(e.description.hasServer(r)){continue}const n=e.s.servers.get(r);e.s.servers.delete(r);destroyServer(n,e)}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.topology;const o=e.op;const s=e.ns;const i=e.ops;n.selectServer(F(),t,((n,a)=>{if(n){r(n,null);return}const A=!e.retrying;const c=!!t.retryWrites;const l=!!t.session;const u=a.supportsRetryableWrites;const h=!l||!t.session.inTransaction();const d=t.explain===undefined;const g=A&&c&&l&&u&&h&&d;const handler=(n,o)=>{if(!n)return r(null,o);if(!shouldRetryOperation(n)){n=Q(n);return r(n)}if(g){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}return r(n)};if(r.operationId){handler.operationId=r.operationId}if(g){t.session.incrementTransactionNumber();t.willRetryWrite=g}a[o](s,i,t,handler)}))}function shouldRetryOperation(e){return e instanceof C&&e.hasErrorLabel("RetryableWriteError")}function srvPollingHandler(e){return function handleSrvPolling(t){const r=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(t);if(e.s.description===r){return}updateServers(e);e.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(e.s.id,r,e.s.description))}}function drainWaitQueue(e,t){while(e.length){const r=e.shift();clearTimeout(r.timer);if(!r[z]){r.callback(t)}}}function processWaitQueue(e){if(e.s.state===V){drainWaitQueue(e[$],new C("Topology is closed, please connect"));return}const t=Array.from(e.description.servers.values());const r=e[$].length;for(let n=0;n0){e.s.servers.forEach((e=>process.nextTick((()=>e.requestCheck()))))}}e.exports={Topology:Topology}},7962:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(750).ServerDescription;const s=r(7161);const i=r(2291).TopologyType;const a=s.MIN_SUPPORTED_SERVER_VERSION;const A=s.MAX_SUPPORTED_SERVER_VERSION;const c=s.MIN_SUPPORTED_WIRE_VERSION;const l=s.MAX_SUPPORTED_WIRE_VERSION;class TopologyDescription{constructor(e,t,r,o,s,u,h){h=h||{};this.type=e||i.Unknown;this.setName=r||null;this.maxSetVersion=o||null;this.maxElectionId=s||null;this.servers=t||new Map;this.stale=false;this.compatible=true;this.compatibilityError=null;this.logicalSessionTimeoutMinutes=null;this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0;this.localThresholdMS=h.localThresholdMS||0;this.commonWireVersion=u||null;Object.defineProperty(this,"options",{value:h,enumberable:false});for(const e of this.servers.values()){if(e.type===n.Unknown)continue;if(e.minWireVersion>l){this.compatible=false;this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${A})`}if(e.maxWireVersion=0){u.delete(t)}if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){const t=updateRsNoPrimaryFromMember(u,s,e);r=t[0],s=t[1]}}if(r===i.ReplicaSetWithPrimary){if([n.Standalone,n.Mongos].indexOf(l)>=0){u.delete(t);r=checkHasPrimary(u)}else if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){r=updateRsWithPrimaryFromMember(u,s,e)}else{r=checkHasPrimary(u)}}return new TopologyDescription(r,u,s,a,A,c,this.options)}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));if(e.length>0){return e[0].error}return undefined}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==n.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}}function topologyTypeForServerType(e){if(e===n.Standalone){return i.Single}if(e===n.Mongos){return i.Sharded}if(e===n.RSPrimary){return i.ReplicaSetWithPrimary}if(e===n.RSGhost||e===n.Unknown){return i.Unknown}return i.ReplicaSetNoPrimary}function compareObjectId(e,t){if(e==null){return-1}if(t==null){return 1}if(e.id instanceof Buffer&&t.id instanceof Buffer){const r=e.id;const n=t.id;return r.compare(n)}const r=e.toString();const n=t.toString();return r.localeCompare(n)}function updateRsFromPrimary(e,t,r,s,i){t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[checkHasPrimary(e),t,s,i]}const a=r.electionId?r.electionId:null;if(r.setVersion&&a){if(s&&i){if(s>r.setVersion||compareObjectId(i,a)>0){e.set(r.address,new o(r.address));return[checkHasPrimary(e),t,s,i]}}i=r.electionId}if(r.setVersion!=null&&(s==null||r.setVersion>s)){s=r.setVersion}for(const t of e.keys()){const s=e.get(t);if(s.type===n.RSPrimary&&s.address!==r.address){e.set(t,new o(s.address));break}}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));const A=Array.from(e.keys());const c=r.allHosts;A.filter((e=>c.indexOf(e)===-1)).forEach((t=>{e.delete(t)}));return[checkHasPrimary(e),t,s,i]}function updateRsWithPrimaryFromMember(e,t,r){if(t==null){throw new TypeError("setName is required")}if(t!==r.setName||r.me&&r.address!==r.me){e.delete(r.address)}return checkHasPrimary(e)}function updateRsNoPrimaryFromMember(e,t,r){let n=i.ReplicaSetNoPrimary;t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[n,t]}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));if(r.me&&r.address!==r.me){e.delete(r.address)}return[n,t]}function checkHasPrimary(e){for(const t of e.keys()){if(e.get(t).type===n.RSPrimary){return i.ReplicaSetWithPrimary}}return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:TopologyDescription}},5474:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(2361);const s=n();const i=s.Binary;const a=r(1178).uuidV4;const A=r(3111).MongoError;const c=r(3111).isRetryableError;const l=r(3111).isRetryableEndTransactionError;const u=r(3111).MongoNetworkError;const h=r(3111).MongoWriteConcernError;const d=r(1707).Transaction;const g=r(1707).TxnState;const p=r(1178).isPromiseLike;const E=r(4485);const m=r(1371).maybePromise;const C=r(1707).isTransactionCommand;const I=r(2306).resolveClusterTime;const y=r(7272).isSharded;const B=r(1178).maxWireVersion;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;const w=8;function assertAlive(e,t){if(e.serverSession==null){const e=new A("Cannot use a session that has ended");if(typeof t==="function"){t(e,null);return false}throw e}return true}const S=Symbol("serverSession");class ClientSession extends o{constructor(e,t,r,n){super();if(e==null){throw new Error("ClientSession requires a topology")}if(t==null||!(t instanceof ServerSessionPool)){throw new Error("ClientSession requires a ServerSessionPool")}r=r||{};n=n||{};this.topology=e;this.sessionPool=t;this.hasEnded=false;this.clientOptions=n;this[S]=undefined;this.supports={causalConsistency:typeof r.causalConsistency!=="undefined"?r.causalConsistency:true};this.clusterTime=r.initialClusterTime;this.operationTime=null;this.explicit=!!r.explicit;this.owner=r.owner;this.defaultTransactionOptions=Object.assign({},r.defaultTransactionOptions);this.transaction=new d}get id(){return this.serverSession.id}get serverSession(){if(this[S]==null){this[S]=this.sessionPool.acquire()}return this[S]}endSession(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=this;return m(this,t,(e=>{if(r.hasEnded){return e()}function completeEndSession(){r.sessionPool.release(r.serverSession);r[S]=undefined;r.hasEnded=true;r.emit("ended",r);e()}if(r.serverSession&&r.inTransaction()){r.abortTransaction((t=>{if(t)return e(t);completeEndSession()}));return}completeEndSession()}))}advanceOperationTime(e){if(this.operationTime==null){this.operationTime=e;return}if(e.greaterThan(this.operationTime)){this.operationTime=e}}equals(e){if(!(e instanceof ClientSession)){return false}return this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){assertAlive(this);if(this.inTransaction()){throw new A("Transaction already in progress")}const t=B(this.topology);if(y(this.topology)&&t!=null&&tendTransaction(this,"commitTransaction",e)))}abortTransaction(e){return m(this,e,(e=>endTransaction(this,"abortTransaction",e)))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){const r=Q();return attemptTransaction(this,r,e,t)}}const v=12e4;const R=100;const k=79;const D=50;const N=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function hasNotTimedOut(e,t){return b(e){if(o instanceof A&&hasNotTimedOut(t,v)&&!isMaxTimeMSExpiredError(o)){if(o.hasErrorLabel("UnknownTransactionCommitResult")){return attemptTransactionCommit(e,t,r,n)}if(o.hasErrorLabel("TransientTransactionError")){return attemptTransaction(e,t,r,n)}}throw o}))}const T=new Set([g.NO_TRANSACTION,g.TRANSACTION_COMMITTED,g.TRANSACTION_ABORTED]);function userExplicitlyEndedTransaction(e){return T.has(e.transaction.state)}function attemptTransaction(e,t,r,n){e.startTransaction(n);let o;try{o=r(e)}catch(e){o=Promise.reject(e)}if(!p(o)){e.abortTransaction();throw new TypeError("Function provided to `withTransaction` must return a Promise")}return o.then((()=>{if(userExplicitlyEndedTransaction(e)){return}return attemptTransactionCommit(e,t,r,n)})).catch((o=>{function maybeRetryOrThrow(o){if(o instanceof A&&o.hasErrorLabel("TransientTransactionError")&&hasNotTimedOut(t,v)){return attemptTransaction(e,t,r,n)}if(isMaxTimeMSExpiredError(o)){o.addErrorLabel("UnknownTransactionCommitResult")}throw o}if(e.transaction.isActive){return e.abortTransaction().then((()=>maybeRetryOrThrow(o)))}return maybeRetryOrThrow(o)}))}function endTransaction(e,t,r){if(!assertAlive(e,r)){return}let n=e.transaction.state;if(n===g.NO_TRANSACTION){r(new A("No transaction started"));return}if(t==="commitTransaction"){if(n===g.STARTING_TRANSACTION||n===g.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(g.TRANSACTION_COMMITTED_EMPTY);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_ABORTED);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call abortTransaction twice"));return}if(n===g.TRANSACTION_COMMITTED||n===g.TRANSACTION_COMMITTED_EMPTY){r(new A("Cannot call abortTransaction after calling commitTransaction"));return}}const o={[t]:1};let s;if(e.transaction.options.writeConcern){s=Object.assign({},e.transaction.options.writeConcern)}else if(e.clientOptions&&e.clientOptions.w){s={w:e.clientOptions.w}}if(n===g.TRANSACTION_COMMITTED){s=Object.assign({wtimeout:1e4},s,{w:"majority"})}if(s){Object.assign(o,{writeConcern:s})}if(t==="commitTransaction"&&e.transaction.options.maxTimeMS){Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS})}function commandHandler(n,o){if(t==="commitTransaction"){e.transaction.transition(g.TRANSACTION_COMMITTED);if(n){if(n instanceof u||n instanceof h||c(n)||isMaxTimeMSExpiredError(n)){if(isUnknownTransactionCommitResult(n)){n.addErrorLabel("UnknownTransactionCommitResult");e.transaction.unpinServer()}}else if(n.hasErrorLabel("TransientTransactionError")){e.transaction.unpinServer()}}}else{e.transaction.transition(g.TRANSACTION_ABORTED)}r(n,o)}function transactionError(e){return t==="commitTransaction"?e:null}if(e.transaction.recoveryToken&&supportsRecoveryToken(e)){o.recoveryToken=e.transaction.recoveryToken}e.topology.command("admin.$cmd",o,{session:e},((t,r)=>{if(t&&l(t)){if(o.commitTransaction){e.transaction.unpinServer();o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})}return e.topology.command("admin.$cmd",o,{session:e},((e,t)=>commandHandler(transactionError(e),t)))}commandHandler(transactionError(t),r)}))}function supportsRecoveryToken(e){const t=e.topology;return!!t.s.options.useRecoveryToken}class ServerSession{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)};this.lastUse=Q();this.txnNumber=0;this.isDirty=false}hasTimedOut(e){const t=Math.round(b(this.lastUse)%864e5%36e5/6e4);return t>e-1}}class ServerSessionPool{constructor(e){if(e==null){throw new Error("ServerSessionPool requires a topology")}this.topology=e;this.sessions=[]}endAllPooledSessions(e){if(this.sessions.length){this.topology.endSessions(this.sessions.map((e=>e.id)),(()=>{this.sessions=[];if(typeof e==="function"){e()}}));return}if(typeof e==="function"){e()}}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const t=this.sessions.shift();if(!t.hasTimedOut(e)){return t}}return new ServerSession}release(e){const t=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const e=this.sessions[this.sessions.length-1];if(e.hasTimedOut(t)){this.sessions.pop()}else{break}}if(!e.hasTimedOut(t)){if(e.isDirty){return}this.sessions.unshift(e)}}}function commandSupportsReadConcern(e,t){if(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch){return true}if(e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline")){return true}return false}function applySession(e,t,r){if(e.hasEnded){return new A("Cannot use a session that has ended")}if(r&&r.writeConcern&&r.writeConcern.w===0){return}const n=e.serverSession;n.lastUse=Q();t.lsid=n.id;const o=e.inTransaction()||C(t);const i=r.willRetryWrite;const a=commandSupportsReadConcern(t,r);if(n.txnNumber&&(i||o)){t.txnNumber=s.Long.fromNumber(n.txnNumber)}if(!o){if(e.transaction.state!==g.NO_TRANSACTION){e.transaction.transition(g.NO_TRANSACTION)}if(e.supports.causalConsistency&&e.operationTime&&a){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}return}if(r.readPreference&&!r.readPreference.equals(E.primary)){return new A(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`)}t.autocommit=false;if(e.transaction.state===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_IN_PROGRESS);t.startTransaction=true;const r=e.transaction.options.readConcern||e.clientOptions.readConcern;if(r){t.readConcern=r}if(e.supports.causalConsistency&&e.operationTime){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}}}function updateSessionFromResponse(e,t){if(t.$clusterTime){I(e,t.$clusterTime)}if(t.operationTime&&e&&e.supports.causalConsistency){e.advanceOperationTime(t.operationTime)}if(t.recoveryToken&&e&&e.inTransaction()){e.transaction._recoveryToken=t.recoveryToken}}e.exports={ClientSession:ClientSession,ServerSession:ServerSession,ServerSessionPool:ServerSessionPool,TxnState:g,applySession:applySession,updateSessionFromResponse:updateSessionFromResponse,commandSupportsReadConcern:commandSupportsReadConcern}},8175:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4847).CoreCursor;const a=r(104);const A=r(7746).retrieveBSON;const c=r(3111).MongoError;const l=r(6495);const u=r(2306).diff;const h=r(2306).cloneOptions;const d=r(2306).SessionMixins;const g=r(2306).isRetryableWritesSupported;const p=r(1178).relayEvents;const E=A();const m=r(2306).getMMAPError;const C=r(1178).makeClientMetadata;const I=r(2306).legacyIsRetryableWriteError;var y="disconnected";var B="connecting";var Q="connected";var b="unreferenced";var w="destroying";var S="destroyed";function stateTransition(e,t){var r={disconnected:[B,w,S,y],connecting:[B,w,S,Q,y],connected:[Q,y,w,S,b],unreferenced:[b,w,S],destroyed:[S]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{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 v=1;var R=["connect","close","error","timeout","parseError"];var Mongos=function(e,t){t=t||{};this.id=v++;if(Array.isArray(e)){e=e.reduce(((e,t)=>{if(e.find((e=>e.host===t.host&&e.port===t.port))){return e}e.push(t);return e}),[])}this.s={options:Object.assign({metadata:C(t)},t),bson:t.bson||new E([E.Binary,E.Code,E.DBRef,E.Decimal128,E.Double,E.Int32,E.Long,E.Map,E.MaxKey,E.MinKey,E.ObjectId,E.BSONRegExp,E.Symbol,E.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false,localThresholdMS:t.localThresholdMS||15};if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0){e.emit(t,r)}}const k=["serverDescriptionChanged","error","close","timeout","parseError"];function destroyServer(e,t,r){t=t||{};k.forEach((t=>e.removeAllListeners(t)));e.destroy(t,r)}Mongos.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,B);var r=this.s.seedlist.map((function(r){const n=new l(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,parent:t}));p(n,t,["serverDescriptionChanged"]);return n}));emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectProxies(t,r)};Mongos.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};function handleEvent(e){return function(){if(e.state===S||e.state===w){return}moveServerFrom(e.connectedProxies,e.disconnectedProxies,this);emitTopologyDescriptionChanged(e);e.emit("left","mongos",this);e.emit("serverClosed",{topologyId:e.id,address:this.name})}}function handleInitialConnectEvent(e,t){return function(){var r=this;if(e.state===S){emitTopologyDescriptionChanged(e);moveServerFrom(e.connectingProxies,e.disconnectedProxies,this);return this.destroy()}if(t==="connect"){e.ismaster=r.lastIsMaster();if(e.ismaster.msg==="isdbgrid"){for(let t=0;t0&&e.state===B){stateTransition(e,Q);e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.disconnectedProxies.length===0){if(e.s.logger.isWarn()){e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset"))}return e.emit("error",new c("no mongos proxies found in seed list"))}topologyMonitor(e,{firstConnect:true})}}}function connectProxies(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function connect(t,r){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name});emitTopologyDescriptionChanged(e);t.once("close",handleInitialConnectEvent(e,"close"));t.once("timeout",handleInitialConnectEvent(e,"timeout"));t.once("parseError",handleInitialConnectEvent(e,"parseError"));t.once("error",handleInitialConnectEvent(e,"error"));t.once("connect",handleInitialConnectEvent(e,"connect"));p(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}t.forEach((e=>connect(e,r++)))}function pickProxy(e,t){const r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected()){return r.server}else{r.unpinServer()}}var n=e.connectedProxies.slice(0);var o=Number.MAX_VALUE;for(var s=0;s0&&e.state===B){e.emit("error",new c("no mongos proxy available"))}else{e.emit("close",e)}return reconnectProxies(e,e.disconnectedProxies,(function(){if(e.state===S||e.state===w||e.state===b){return}if(e.state===B&&t.firstConnect){e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.isConnected()){e.emit("reconnect",e)}else if(!e.isConnected()&&e.listeners("close").length>0){e.emit("close",e)}topologyMonitor(e)}))}for(var o=0;o{n--;if(n>0){return}emitTopologyDescriptionChanged(this);emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});stateTransition(this,S);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name});destroyServer(t,e,serverDestroyed);moveServerFrom(this.connectedProxies,this.disconnectedProxies,t)}))};Mongos.prototype.isConnected=function(){return this.connectedProxies.length>0};Mongos.prototype.isDestroyed=function(){return this.state===S};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const o=e.op;const s=e.ns;const i=e.ops;let a=pickProxy(n,t.session);if(!a)return r(new c("no mongos proxy available"));const A=!e.retrying&&!!t.retryWrites&&t.session&&g(n)&&!t.session.inTransaction()&&t.explain===undefined;const handler=(o,s)=>{if(!o)return r(null,s);if(!I(o,n)||!A){o=m(o);return r(o)}a=pickProxy(n,t.session);if(!a){return r(o)}const i=Object.assign({},e,{retrying:true});return executeWriteOperation(i,t,r)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}a[o](s,i,t,handler)}Mongos.prototype.insert=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("insert",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};Mongos.prototype.update=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("update",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};Mongos.prototype.remove=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("remove",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const D=["findAndModify","insert","update","delete"];function isWriteCommand(e){return D.some((t=>e[t]))}Mongos.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}var s=this;var i=pickProxy(s,r.session);if((i==null||!i.isConnected())&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}if(i==null){return n(new c("no mongos proxy available"))}var a=h(r);a.topology=s;const A=!r.retrying&&r.retryWrites&&r.session&&g(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(r,o)=>{if(!r)return n(null,o);if(!I(r,s)){return n(r)}if(A){const r=Object.assign({},a,{retrying:true});return this.command(e,t,r,n)}return n(r)};if(A){a.session.incrementTransactionNumber();a.willRetryWrite=A}i.command(e,t,a,cb)};Mongos.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Mongos.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;t=t||{};const n=pickProxy(this,t.session);if(n==null){r(new c("server selection failed"));return}if(this.s.debug)this.emit("pickedServer",null,n);r(null,n)};Mongos.prototype.connections=function(){var e=[];for(var t=0;t0){var t="Unknown";if(e.connectedProxies.length>0){t="Sharded"}var r={topologyType:t,servers:[]};var n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map((function(e){var t=e.getDescription();t.type="Unknown";return t})));r.servers=r.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();t.type="Mongos";return t})));var o=u(e.topologyDescription,r);var s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:o};if(o.servers.length>0){e.emit("topologyDescriptionChanged",s)}e.topologyDescription=r}}e.exports=Mongos},4485:(e,t,r)=>{"use strict";const n=r(1371).emitWarningOnce;const ReadPreference=function(e,t,r){if(!ReadPreference.isValid(e)){throw new TypeError(`Invalid read preference mode ${e}`)}if(t&&!Array.isArray(t)){n("ReadPreference tags must be an array, this will change in the next major version");const e=typeof t.maxStalenessSeconds!=="undefined";const o=typeof t.hedge!=="undefined";const s=e||o;if(s){r=t;t=undefined}else{t=[t]}}this.mode=e;this.tags=t;this.hedge=r&&r.hedge;r=r||{};if(r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0){throw new TypeError("maxStalenessSeconds must be a positive integer")}this.maxStalenessSeconds=r.maxStalenessSeconds;this.minWireVersion=5}if(this.mode===ReadPreference.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(ReadPreference.prototype,"preference",{enumerable:true,get:function(){return this.mode}});ReadPreference.PRIMARY="primary";ReadPreference.PRIMARY_PREFERRED="primaryPreferred";ReadPreference.SECONDARY="secondary";ReadPreference.SECONDARY_PREFERRED="secondaryPreferred";ReadPreference.NEAREST="nearest";const o=[ReadPreference.PRIMARY,ReadPreference.PRIMARY_PREFERRED,ReadPreference.SECONDARY,ReadPreference.SECONDARY_PREFERRED,ReadPreference.NEAREST,null];ReadPreference.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const r=e.readPreferenceTags;const n=e.maxStalenessSeconds;if(typeof t==="string"){return new ReadPreference(t,r)}else if(!(t instanceof ReadPreference)&&typeof t==="object"){const e=t.mode||t.preference;if(e&&typeof e==="string"){return new ReadPreference(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}}return t};ReadPreference.resolve=function(e,t){t=t||{};const r=t.session;const n=e&&e.readPreference;let o;if(t.readPreference){o=ReadPreference.fromOptions(t)}else if(r&&r.inTransaction()&&r.transaction.options.readPreference){o=r.transaction.options.readPreference}else if(n!=null){o=n}else{o=ReadPreference.primary}return typeof o==="string"?new ReadPreference(o):o};ReadPreference.translate=function(e){if(e.readPreference==null)return e;const t=e.readPreference;if(typeof t==="string"){e.readPreference=new ReadPreference(t)}else if(t&&!(t instanceof ReadPreference)&&typeof t==="object"){const r=t.mode||t.preference;if(r&&typeof r==="string"){e.readPreference=new ReadPreference(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds})}}else if(!(t instanceof ReadPreference)){throw new TypeError("Invalid read preference: "+t)}return e};ReadPreference.isValid=function(e){return o.indexOf(e)!==-1};ReadPreference.prototype.isValid=function(e){return ReadPreference.isValid(typeof e==="string"?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];ReadPreference.prototype.slaveOk=function(){return s.indexOf(this.mode)!==-1};ReadPreference.prototype.equals=function(e){return e.mode===this.mode};ReadPreference.prototype.toJSON=function(){const e={mode:this.mode};if(Array.isArray(this.tags))e.tags=this.tags;if(this.maxStalenessSeconds)e.maxStalenessSeconds=this.maxStalenessSeconds;if(this.hedge)e.hedge=this.hedge;return e};ReadPreference.primary=new ReadPreference("primary");ReadPreference.primaryPreferred=new ReadPreference("primaryPreferred");ReadPreference.secondary=new ReadPreference("secondary");ReadPreference.secondaryPreferred=new ReadPreference("secondaryPreferred");ReadPreference.nearest=new ReadPreference("nearest");e.exports=ReadPreference},1134:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4485);const a=r(4847).CoreCursor;const A=r(7746).retrieveBSON;const c=r(104);const l=r(3111).MongoError;const u=r(6495);const h=r(8742);const d=r(2306).Timeout;const g=r(2306).Interval;const p=r(2306).SessionMixins;const E=r(2306).isRetryableWritesSupported;const m=r(1178).relayEvents;const C=A();const I=r(2306).getMMAPError;const y=r(1178).makeClientMetadata;const B=r(2306).legacyIsRetryableWriteError;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;var w="disconnected";var S="connecting";var v="connected";var R="unreferenced";var k="destroyed";function stateTransition(e,t){var r={disconnected:[S,k,w],connecting:[S,k,v,w],connected:[v,w,k,R],unreferenced:[R,k],destroyed:[k]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}}var D=1;var N=["connect","close","error","timeout","parseError"];var ReplSet=function(e,t){var r=this;t=t||{};if(!Array.isArray(e))throw new l("seedlist must be an array");if(e.length===0)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if(typeof e.host!=="string"||typeof e.port!=="number")throw new l("seedlist entry must contain a host and port")}));s.call(this);this.id=D++;var n=t.localThresholdMS||15;if(t.acceptableLatency)n=t.acceptableLatency;var i=c("ReplSet",t);this.s={options:Object.assign({metadata:y(t)},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]),Cursor:t.cursorFactory||a,logger:i,seedlist:e,replicaSetState:new h({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false};this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){r.emit("topologyDescriptionChanged",e)}));if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoute.name===t));if(r>=0){const t=e.s.connectingServers[r];t.destroy({force:true});e.s.connectingServers.splice(r,1);return done()}var n=new u(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:false,monitoring:false,parent:e}));n.once("connect",_handleEvent(e,"connect"));n.once("close",_handleEvent(e,"close"));n.once("timeout",_handleEvent(e,"timeout"));n.once("error",_handleEvent(e,"error"));n.once("parseError",_handleEvent(e,"parseError"));n.on("serverOpening",(t=>e.emit("serverOpening",t)));n.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));n.on("serverClosed",(t=>e.emit("serverClosed",t)));m(n,e,["commandStarted","commandSucceeded","commandFailed"]);e.s.connectingServers.push(n);n.connect(e.s.connectOptions)}),r)}for(var s=0;se.emit("serverOpening",t)));t.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));t.on("serverClosed",(t=>e.emit("serverClosed",t)));m(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}while(t.length>0){connect(t.shift(),r++)}}function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}ReplSet.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,S);var r=this.s.seedlist.map((function(r){return new u(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,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)))}emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectServers(t,r)};ReplSet.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};ReplSet.prototype.destroy=function(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};let r=this.s.connectingServers.length+1;const serverDestroyed=()=>{r--;if(r>0){return}emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});if(typeof t==="function"){t(null,null)}};if(this.state===k){if(typeof t==="function")t(null,null);return}stateTransition(this,k);if(this.haTimeoutId)clearTimeout(this.haTimeoutId);for(var n=0;n{if(b(s)>=T){if(o!=null){r(o,null)}else{r(new l("Server selection timed out"))}return}const e=this.s.replicaSetState.pickServer(n);if(e==null){setTimeout(_selectServer,O);return}if(!(e instanceof u)){o=e;setTimeout(_selectServer,O);return}if(this.s.debug)this.emit("pickedServer",t.readPreference,e);r(null,e)};_selectServer()};ReplSet.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const s=e.op;const i=e.ns;const a=e.ops;if(n.state===k){return r(new l(o("topology was destroyed")))}const A=!e.retrying&&!!t.retryWrites&&t.session&&E(n)&&!t.session.inTransaction()&&t.explain===undefined;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler){return n.s.disconnectHandler.add(s,i,a,t,r)}else if(!A){return r(new l("no primary server found"))}}const handler=(o,s)=>{if(!o)return r(null,s);if(!B(o,n)){o=I(o);return r(o)}if(A){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}if(n.s.replicaSetState.primary){n.s.replicaSetState.primary.destroy();n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:true})}return r(o)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}n.s.replicaSetState.primary[s](i,a,t,handler)}ReplSet.prototype.insert=function(e,t,r,n){executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};ReplSet.prototype.update=function(e,t,r,n){executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};ReplSet.prototype.remove=function(e,t,r,n){executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const _=["findAndModify","insert","update","delete"];function isWriteCommand(e){return _.some((t=>e[t]))}ReplSet.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===k)return n(new l(o("topology was destroyed")));var s=this;var a=r.readPreference?r.readPreference:i.primary;if(a.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}var A=this.s.replicaSetState.pickServer(a);if(!(A instanceof u))return n(A);if(s.s.debug)s.emit("pickedServer",i.primary,A);if(A==null){return n(new l(o("no server found that matches the provided readPreference %s",a)))}const c=!r.retrying&&!!r.retryWrites&&r.session&&E(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(o,i)=>{if(!o)return n(null,i);if(!B(o,s)){return n(o)}if(c){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}if(this.s.replicaSetState.primary){this.s.replicaSetState.primary.destroy();this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:true})}return n(o)};if(c){r.session.incrementTransactionNumber();r.willRetryWrite=c}A.command(e,t,r,cb)};ReplSet.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};e.exports=ReplSet},8742:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2306).diff,i=r(2361).EventEmitter,a=r(104),A=r(4485),c=r(3111).MongoError,l=r(1867).Buffer;var u={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};var h={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};var ReplSetState=function(e){e=e||{};i.call(this);this.topologyType=e.setName?u.ReplicaSetNoPrimary:u.Unknown;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=undefined};n(ReplSetState,i);ReplSetState.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};ReplSetState.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};ReplSetState.prototype.hasPrimary=function(){return this.primary!=null};ReplSetState.prototype.hasSecondary=function(){return this.secondaries.length>0};ReplSetState.prototype.get=function(e){var t=this.allServers();for(var r=0;r{n--;if(n>0){return}this.secondaries=[];this.arbiters=[];this.passives=[];this.ghosts=[];this.unknownServers=[];this.set={};this.primary=null;emitTopologyDescriptionChanged(this);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>t.destroy(e,serverDestroyed)))};ReplSetState.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase();var n=this.primary?[this.primary]:[];n=n.concat(this.secondaries);n=n.concat(this.arbiters);n=n.concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;ReplSetState.prototype.update=function(e){var t=this;const r=e.lastIsMaster();if(r&&r.isWritablePrimary)r.ismaster=r.isWritablePrimary;var n=e.name.toLowerCase();if(r){var s=Array.isArray(r.hosts)?r.hosts:[];s=s.concat(Array.isArray(r.arbiters)?r.arbiters:[]);s=s.concat(Array.isArray(r.passives)?r.passives:[]);s=s.map((function(e){return e.toLowerCase()}));for(var i=0;il){return false}}else if(!p&&a&&l){if(l=5&&e.ismaster.secondary&&this.hasPrimary()){e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t}else if(e.ismaster.maxWireVersion>=5&&e.ismaster.secondary){e.staleness=r-e.lastWriteDate+t}};ReplSetState.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var o=pickNearest(this,e);if(o){return o}}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e);if(o){return o}}if(e.equals(A.secondaryPreferred)){return this.primary}return null}if(e.equals(A.primaryPreferred)){o=null;if(this.primary){return this.primary}if(n.length>0&&e.maxStalenessSeconds==null){o=pickNearest(this,e)}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e)}if(o)return o}return this.primary};var filterByTags=function(e,t){if(e.tags==null)return t;var r=[];var n=Array.isArray(e.tags)?e.tags:[e.tags];for(var o=0;o0?r[0].lastIsMasterMS:0;r=r.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}));if(r.length===0){return null}e.index=e.index%r.length;var s=r[e.index];e.index=e.index+1;return s}function inList(e,t,r){for(var n=0;n0){var t="Unknown";var r=e.setName;if(e.hasPrimaryAndSecondary()){t="ReplicaSetWithPrimary"}else if(!e.hasPrimary()&&e.hasSecondary()){t="ReplicaSetNoPrimary"}var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary";n.servers.push(o)}n.servers=n.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));n.servers=n.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();t.type="RSArbiter";return t})));n.servers=n.servers.concat(e.passives.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));var i=s(e.replicasetDescription,n);var a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:i};e.emit("topologyDescriptionChanged",a);e.replicasetDescription=n}}e.exports=ReplSetState},6495:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2361).EventEmitter,i=r(4485),a=r(104),A=r(7746).debugOptions,c=r(7746).retrieveBSON,l=r(5500),u=r(3111).MongoError,h=r(3111).MongoNetworkError,d=r(9206),g=r(4847).CoreCursor,p=r(2306),E=r(2306).createCompressionInfo,m=r(2306).resolveClusterTime,C=r(2306).SessionMixins,I=r(7703).extractCommand,y=r(1178).relayEvents;const B=r(1178).collationNotSupported;const Q=r(1178).makeClientMetadata;var b=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];var w=0;var S=false;var v={};var R=c();function topologyId(e){return e.s.parent==null?e.id:e.s.parent.id}var Server=function(e){e=e||{};s.call(this);this.id=w++;this.s={options:Object.assign({metadata:Q(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||g,bson:e.bson||new R([R.Binary,R.Code,R.DBRef,R.Decimal128,R.Double,R.Int32,R.Long,R.Map,R.MaxKey,R.MinKey,R.ObjectId,R.BSONRegExp,R.Symbol,R.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring==="boolean"?e.monitoring:true,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval==="number"?e.monitoringInterval:5e3,compression:{compressors:E(e)},parent:e.parent};if(!this.s.parent){this.s.clusterTime=null}this.ismaster=null;this.lastIsMasterMS=-1;this.monitoringProcessId=null;this.initialConnect=true;this._type="server";this.lastUpdateTime=0;this.lastWriteDate=0;this.staleness=0};n(Server,s);Object.assign(Server.prototype,C);Object.defineProperty(Server.prototype,"type",{enumerable:true,get:function(){return this._type}});Object.defineProperty(Server.prototype,"parserType",{enumerable:true,get:function(){return R.native?"c++":"js"}});Object.defineProperty(Server.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){if(!this.ismaster)return null;return this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(Server.prototype,"clientMetadata",{enumerable:true,get:function(){return this.s.options.metadata}});Object.defineProperty(Server.prototype,"clusterTime",{enumerable:true,set:function(e){const t=this.s.parent?this.s.parent:this.s;m(t,e)},get:function(){const e=this.s.parent?this.s.parent:this.s;return e.clusterTime||null}});Server.enableServerAccounting=function(){S=true;v={}};Server.disableServerAccounting=function(){S=false};Server.servers=function(){return v};Object.defineProperty(Server.prototype,"name",{enumerable:true,get:function(){return this.s.options.host+":"+this.s.options.port}});function disconnectHandler(e,t,r,n,s,i){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!s.monitoring){e.s.disconnectHandler.add(t,r,n,s,i);return true}if(!e.s.pool.isConnected()){i(new u(o("no connection available to server %s",e.name)));return true}}function monitoringProcess(e){return function(){if(e.s.pool.isDestroyed())return;e.emit("monitoring",e);var t=(new Date).getTime();e.command("admin.$cmd",{ismaster:true},{socketTimeout:typeof e.s.options.connectionTimeout!=="number"?2e3:e.s.options.connectionTimeout,monitoring:true},((r,n)=>{e.lastIsMasterMS=(new Date).getTime()-t;if(e.s.pool.isDestroyed())return;if(n){e.ismaster=n.result}e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}))}}var eventHandler=function(e,t){return function(r,n){if(e.s.logger.isInfo()){var s=r instanceof u?JSON.stringify(r):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,s))}if(t==="connect"){e.initialConnect=false;e.ismaster=n.ismaster;e.lastIsMasterMS=n.lastIsMasterMS;if(n.agreedCompressor){e.s.pool.options.agreedCompressor=n.agreedCompressor}if(n.zlibCompressionLevel){e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel}if(n.ismaster.$clusterTime){const t=n.ismaster.$clusterTime;e.clusterTime=t}if(e.ismaster.msg==="isdbgrid"){e._type="mongos"}if(e.s.monitoring){e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});if(!e.s.inTopology){p.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)}]})}if(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==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(S&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1){if(!e.s.inTopology){e.emit("topologyOpening",{topologyId:e.id})}delete v[e.id]}if(t==="close"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"})}if(t==="reconnectFailed"){e.emit("reconnectFailed",r);if(e.listeners("error").length>0){e.emit("error",r)}return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1){e.initialConnect=false;return e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,r)))}if(t==="reconnect"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});return e.emit(t,e)}e.emit(t,r)}}};Server.prototype.connect=function(e){var t=this;e=e||{};if(S)v[this.id]=this;if(t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed()){throw new u(o("server instance in invalid state %s",t.s.pool.state))}t.s.pool=new l(this,Object.assign(t.s.options,e,{bson:this.s.bson}));t.s.pool.on("close",eventHandler(t,"close"));t.s.pool.on("error",eventHandler(t,"error"));t.s.pool.on("timeout",eventHandler(t,"timeout"));t.s.pool.on("parseError",eventHandler(t,"parseError"));t.s.pool.on("connect",eventHandler(t,"connect"));t.s.pool.on("reconnect",eventHandler(t,"reconnect"));t.s.pool.on("reconnectFailed",eventHandler(t,"reconnectFailed"));y(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]);if(!t.s.inTopology){this.emit("topologyOpening",{topologyId:topologyId(t)})}t.emit("serverOpening",{topologyId:topologyId(t),address:t.name});t.s.pool.connect()};Server.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};Server.prototype.getDescription=function(){var e=this.ismaster||{};var t={type:p.getTopologyType(this),address:this.name};if(e.hosts)t.hosts=e.hosts;if(e.arbiters)t.arbiters=e.arbiters;if(e.passives)t.passives=e.passives;if(e.setName)t.setName=e.setName;return t};Server.prototype.lastIsMaster=function(){return this.ismaster};Server.prototype.unref=function(){this.s.pool.unref()};Server.prototype.isConnected=function(){if(!this.s.pool)return false;return this.s.pool.isConnected()};Server.prototype.isDestroyed=function(){if(!this.s.pool)return false;return this.s.pool.isDestroyed()};function basicWriteValidations(e){if(!e.s.pool)return new u("server instance is not connected");if(e.s.pool.isDestroyed())return new u("server instance pool was destroyed")}function basicReadValidations(e,t){basicWriteValidations(e,t);if(t.readPreference&&!(t.readPreference instanceof i)){throw new Error("readPreference must be an instance of ReadPreference")}}Server.prototype.command=function(e,t,r,n){var s=this;if(typeof r==="function"){n=r,r={},r=r||{}}var i=basicReadValidations(s,r);if(i)return n(i);r=Object.assign({},r,{wireProtocolCommand:false});if(s.s.logger.isDebug()){const n=I(t);s.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:A(b,r)}),s.name))}if(disconnectHandler(s,"command",e,t,r,n))return;if(B(this,t)){return n(new u(`server ${this.name} does not support collation`))}d.command(s,e,t,r,n)};Server.prototype.query=function(e,t,r,n,o){d.query(this,e,t,r,n,o)};Server.prototype.getMore=function(e,t,r,n,o){d.getMore(this,e,t,r,n,o)};Server.prototype.killCursors=function(e,t,r){d.killCursors(this,e,t,r)};Server.prototype.insert=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"insert",e,t,r,n))return;t=Array.isArray(t)?t:[t];return d.insert(o,e,t,r,n)};Server.prototype.update=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"update",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.update(o,e,t,r,n)};Server.prototype.remove=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"remove",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.remove(o,e,t,r,n)};Server.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Server.prototype.equals=function(e){if(typeof e==="string")return this.name.toLowerCase()===e.toLowerCase();if(e.name)return this.name.toLowerCase()===e.name.toLowerCase();return false};Server.prototype.connections=function(){return this.s.pool.allConnections()};Server.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;r(null,this)};var k=["close","error","timeout","parseError","connect"];Server.prototype.destroy=function(e,t){if(this._destroyed){if(typeof t==="function")t(null,null);return}if(typeof e==="function"){t=e;e={}}e=e||{};var r=this;if(S)delete v[this.id];if(this.monitoringProcessId){clearTimeout(this.monitoringProcessId)}if(!r.s.pool||this._destroyed){this._destroyed=true;if(typeof t==="function")t(null,null);return}this._destroyed=true;if(e.emitClose){r.emit("close",r)}if(e.emitDestroy){r.emit("destroy",r)}k.forEach((function(e){r.s.pool.removeAllListeners(e)}));if(r.listeners("serverClosed").length>0)r.emit("serverClosed",{topologyId:topologyId(r),address:r.name});if(r.listeners("topologyClosed").length>0&&!r.s.inTopology){r.emit("topologyClosed",{topologyId:topologyId(r)})}if(r.s.logger.isDebug()){r.s.logger.debug(o("destroy called on server %s",r.name))}this.s.pool.destroy(e.force,t)};e.exports=Server},2306:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(4485);const s=r(2291).TopologyType;const i=r(3111).MongoError;const a=r(3111).isRetryableWriteError;const A=r(1178).maxWireVersion;const c=r(3111).MongoNetworkError;const l=n.IllegalOperation;function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}function createCompressionInfo(e){if(!e.compression||!e.compression.compressors){return[]}e.compression.compressors.forEach((function(e){if(e!=="snappy"&&e!=="zlib"){throw new Error("compressors must be at least one of snappy or zlib")}}));return e.compression.compressors}function clone(e){return JSON.parse(JSON.stringify(e))}var getPreviousDescription=function(e){if(!e.s.serverDescription){e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}}return e.s.serverDescription};var emitServerDescriptionChanged=function(e,t){if(e.listeners("serverDescriptionChanged").length>0){e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousDescription(e),newDescription:t});e.s.serverDescription=t}};var getPreviousTopologyDescription=function(e){if(!e.s.topologyDescription){e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}}return e.s.topologyDescription};var emitTopologyDescriptionChanged=function(e,t){if(e.listeners("topologyDescriptionChanged").length>0){e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousTopologyDescription(e),newDescription:t});e.s.serverDescription=t}};var changedIsMaster=function(e,t,r){var n=getTopologyType(e,t);var o=getTopologyType(e,r);if(o!==n)return true;return false};var getTopologyType=function(e,t){if(!t){t=e.ismaster}if(!t)return"Unknown";if(t.ismaster&&t.msg==="isdbgrid")return"Mongos";if(t.ismaster&&!t.hosts)return"Standalone";if(t.ismaster)return"RSPrimary";if(t.secondary)return"RSSecondary";if(t.arbiterOnly)return"RSArbiter";return"Unknown"};var inquireServerState=function(e){return function(t){if(e.s.state==="destroyed")return;var r=(new Date).getTime();emitSDAMEvent(e,"serverHeartbeatStarted",{connectionId:e.name});e.command("admin.$cmd",{ismaster:true},{monitoring:true},(function(n,o){if(!n){e.emit("ismaster",o,e);var s=(new Date).getTime()-r;emitSDAMEvent(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name});if(changedIsMaster(e,e.s.ismaster,o.result)){emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:!e.s.inTopology?"Standalone":getTopologyType(e)})}e.s.ismaster=o.result;e.s.isMasterLatencyMS=s}else{emitSDAMEvent(e,"serverHeartbeatFailed",{durationMS:s,failure:n,connectionId:e.name})}if(typeof t==="function"){return t(n,o)}e.s.inquireServerStateTimeout=setTimeout(inquireServerState(e),e.s.haInterval)}))}};var cloneOptions=function(e){var t={};for(var r in e){t[r]=e[r]}return t};function Interval(e,t){var r=false;this.start=function(){if(!this.isRunning()){r=setInterval(e,t)}return this};this.stop=function(){clearInterval(r);r=false;return this};this.isRunning=function(){return r!==false}}function Timeout(e,t){var r=false;var func=()=>{if(r){clearTimeout(r);r=false;e()}};this.start=function(){if(!this.isRunning()){r=setTimeout(func,t)}return this};this.stop=function(){clearTimeout(r);r=false;return this};this.isRunning=function(){return r!==false}}function diff(e,t){var r={servers:[]};if(!e){e={servers:[]}}for(var n=0;n{if(typeof t==="function")t()}))}};function topologyType(e){if(e.description){return e.description.type}if(e.type==="mongos"){return s.Sharded}else if(e.type==="replset"){return s.ReplicaSetWithPrimary}return s.Single}const h=6;const isRetryableWritesSupported=function(e){const t=e.lastIsMaster().maxWireVersion;if(t{"use strict";const n=r(3111).MongoError;const o=r(4485);const s=r(7289);const i=r(2481);let a;let A;(()=>{const e="NO_TRANSACTION";const t="STARTING_TRANSACTION";const r="TRANSACTION_IN_PROGRESS";const n="TRANSACTION_COMMITTED";const o="TRANSACTION_COMMITTED_EMPTY";const s="TRANSACTION_ABORTED";a={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:o,TRANSACTION_ABORTED:s};A={[e]:[e,t],[t]:[r,n,o,s],[r]:[r,n,s],[n]:[n,o,t,e],[s]:[t,e],[o]:[o,e]}})();class Transaction{constructor(e){e=e||{};this.state=a.NO_TRANSACTION;this.options={};const t=i.fromOptions(e);if(t){if(t.w<=0){throw new n("Transactions do not support unacknowledged write concern")}this.options.writeConcern=t}if(e.readConcern){this.options.readConcern=s.fromOptions(e)}if(e.readPreference){this.options.readPreference=o.fromOptions(e)}if(e.maxCommitTimeMS){this.options.maxTimeMS=e.maxCommitTimeMS}this._pinnedServer=undefined;this._recoveryToken=undefined}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(e){const t=A[this.state];if(t&&t.indexOf(e)!==-1){this.state=e;if(this.state===a.NO_TRANSACTION||this.state===a.STARTING_TRANSACTION||this.state===a.TRANSACTION_ABORTED){this.unpinServer()}return}throw new n(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){if(this.isActive){this._pinnedServer=e}}unpinServer(){this._pinnedServer=undefined}}function isTransactionCommand(e){return!!(e.commitTransaction||e.abortTransaction)}e.exports={TxnState:a,Transaction:Transaction,isTransactionCommand:isTransactionCommand}},8767:(e,t,r)=>{"use strict";const n=r(7310);const o=r(3477);const s=r(7578);const i=r(3111).MongoParseError;const a=r(4485);const A=r(1371).emitWarningOnce;const c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;const l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map((e=>e.toLowerCase())));function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}function parseSrvConnectionString(e,t,r){const a=n.parse(e,true);if(t.directConnection||t.directconnection){return r(new i("directConnection not supported with SRV URI"))}if(a.hostname.split(".").length<3){return r(new i("URI does not have hostname, domain name and tld"))}a.domainLength=a.hostname.split(".").length;const A=e.substring("mongodb+srv://".length).split("/")[0];if(A.match(",")){return r(new i("Invalid URI, cannot contain multiple hostnames"))}if(a.port){return r(new i(`Ports not accepted with '${m}' URIs`))}const c=a.host;s.resolveSrv(`_mongodb._tcp.${c}`,((e,A)=>{if(e)return r(e);if(A.length===0){return r(new i("No addresses found at host"))}for(let e=0;e`${e.name}:${e.port}`)).join(",");if(!("ssl"in t)&&(!a.search||!("ssl"in a.query)||a.query.ssl===null)){a.query.ssl=true}s.resolveTxt(c,((e,s)=>{if(e){if(e.code!=="ENODATA"&&e.code!=="ENOTFOUND"){return r(e)}s=null}if(s){if(s.length>1){return r(new i("Multiple text records not allowed"))}s=o.parse(s[0].join(""));if(Object.keys(s).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(Object.keys(s).some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new i("Text record must only set `authSource` or `replicaSet`"))}a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);const A=n.format(a);parseConnectionString(A,t,((e,t)=>{if(e){r(e);return}r(null,Object.assign({},t,{srvHost:c}))}))}))}))}function parseQueryStringItemValue(e,t){if(Array.isArray(t)){t=t.filter(((e,r)=>t.indexOf(e)===r));if(t.length===1)t=t[0]}else if(t.indexOf(":")>0){t=t.split(",").reduce(((t,r)=>{const n=r.split(":");t[n[0]]=parseQueryStringItemValue(e,n[1]);return t}),{})}else if(t.indexOf(",")>0){t=t.split(",").map((t=>parseQueryStringItemValue(e,t)))}else if(t.toLowerCase()==="true"||t.toLowerCase()==="false"){t=t.toLowerCase()==="true"}else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);if(!Number.isNaN(e)){t=parseFloat(t)}}return t}const u=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]);const h=new Set(["authsource","replicaset"]);const d=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]);const g={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 applyConnectionStringOption(e,t,r,n){if(t==="journal"){t="j"}else if(t==="wtimeoutms"){t="wtimeout"}if(u.has(t)){r=r==="true"||r===true}else if(t==="appname"){r=decodeURIComponent(r)}else if(t==="readconcernlevel"){e["readConcernLevel"]=r;t="readconcern";r={level:r}}if(t==="compressors"){r=Array.isArray(r)?r:[r];if(!r.every((e=>e==="snappy"||e==="zlib"))){throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`")}}if(t==="authmechanism"&&!d.has(r)){throw new i(`Value for authMechanism must be one of: ${Array.from(d).join(", ")}, found: ${r}`)}if(t==="readpreference"&&!a.isValid(r)){throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`")}if(t==="zlibcompressionlevel"&&(r<-1||r>9)){throw new i("zlibCompressionLevel must be an integer between -1 and 9")}if(t==="compressors"||t==="zlibcompressionlevel"){e.compression=e.compression||{};e=e.compression}if(t==="authmechanismproperties"){if(typeof r.SERVICE_NAME==="string")e.gssapiServiceName=r.SERVICE_NAME;if(typeof r.SERVICE_REALM==="string")e.gssapiServiceRealm=r.SERVICE_REALM;if(typeof r.CANONICALIZE_HOST_NAME!=="undefined"){e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME}}if(t==="readpreferencetags"){r=Array.isArray(r)?splitArrayOfMultipleReadPreferenceTags(r):[r]}if(n.caseTranslate&&g[t]){e[g[t]]=r;return}e[t]=r}const p=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function splitArrayOfMultipleReadPreferenceTags(e){const t=[];for(let r=0;r{const n=e.split(":");t[r][n[0]]=n[1]}))}return t}function applyAuthExpectations(e){if(e.options==null){return}const t=e.options;const r=t.authsource||t.authSource;if(r!=null){e.auth=Object.assign({},e.auth,{db:r})}const n=t.authmechanism||t.authMechanism;if(n!=null){if(p.has(n)&&(!e.auth||e.auth.username==null)){throw new i(`Username required for mechanism \`${n}\``)}if(n==="GSSAPI"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null){throw new i(`Password not allowed for mechanism \`${n}\``)}if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="PLAIN"){if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"$external"})}}}if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"admin"})}return e}function parseQueryString(e,t){const r={};let n=o.parse(e);checkTLSOptions(n);for(const e in n){const o=n[e];if(o===""||o==null){throw new i("Incomplete key value pair for option")}const s=e.toLowerCase();if(s==="serverapi"){throw new i("URI cannot contain `serverApi`, it can only be passed to the client")}const a=l.has(s)?o:parseQueryStringItemValue(s,o);applyConnectionStringOption(r,s,a,t)}if(r.wtimeout&&r.wtimeoutms){delete r.wtimeout;A("Unsupported option `wtimeout` specified")}return Object.keys(r).length?r:null}function translateTLSOptions(e){if(e.tls){e.ssl=e.tls}if(e.tlsInsecure){e.checkServerIdentity=false;e.sslValidate=false}else{Object.assign(e,{checkServerIdentity:e.tlsAllowInvalidHostnames?false:true,sslValidate:e.tlsAllowInvalidCertificates?false:true})}if(e.tlsCAFile){e.ssl=true;e.sslCA=e.tlsCAFile}if(e.tlsCertificateKeyFile){e.ssl=true;if(e.tlsCertificateFile){e.sslCert=e.tlsCertificateFile;e.sslKey=e.tlsCertificateKeyFile}else{e.sslKey=e.tlsCertificateKeyFile;e.sslCert=e.tlsCertificateKeyFile}}if(e.tlsCertificateKeyFilePassword){e.ssl=true;e.sslPass=e.tlsCertificateKeyFilePassword}return e}function checkTLSOptions(e){const t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1)){throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.")}const r=assertTlsOptionsAreEqual("tls",e,t);const n=assertTlsOptionsAreEqual("ssl",e,t);if(r!=null&&n!=null){if(r!==n){throw new i("All values of `tls` and `ssl` must be the same.")}}}function assertTlsOptionsAreEqual(e,t,r){const n=r.indexOf(e)!==-1;let o;if(Array.isArray(t[e])){o=t[e][0]}else{o=t[e]}if(n){if(Array.isArray(t[e])){const r=t[e][0];t[e].forEach((t=>{if(t!==r){throw new i(`All values of ${e} must be the same.`)}}))}}return o}const E="mongodb";const m="mongodb+srv";const C=[E,m];function parseConnectionString(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},{caseTranslate:true},t);try{n.parse(e)}catch(e){return r(new i("URI malformed, cannot be parsed"))}const s=e.match(c);if(!s){return r(new i("Invalid connection string"))}const a=s[1];if(C.indexOf(a)===-1){return r(new i("Invalid protocol provided"))}const A=s[4].split("?");const l=A.length>0?A[0]:null;const u=A.length>1?A[1]:null;let h;try{h=parseQueryString(u,t)}catch(e){return r(e)}h=Object.assign({},h,t);if(Object.keys(h).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(a===m){return parseSrvConnectionString(e,h,r)}const d={username:null,password:null,db:l&&l!==""?o.unescape(l):null};if(h.auth){if(h.auth.username)d.username=h.auth.username;if(h.auth.user)d.username=h.auth.user;if(h.auth.password)d.password=h.auth.password}else{if(h.username)d.username=h.username;if(h.user)d.username=h.user;if(h.password)d.password=h.password}if(s[4].split("?")[0].indexOf("@")!==-1){return r(new i("Unescaped slash in userinfo section"))}const g=s[3].split("@");if(g.length>2){return r(new i("Unescaped at-sign in authority section"))}if(g[0]==null||g[0]===""){return r(new i("No username provided in authority section"))}if(g.length>1){const e=g.shift().split(":");if(e.length>2){return r(new i("Unescaped colon in authority section"))}if(e[0]===""){return r(new i("Invalid empty username provided"))}if(!d.username)d.username=o.unescape(e[0]);if(!d.password)d.password=e[1]?o.unescape(e[1]):null}let p=null;const E=g.shift().split(",").map((e=>{let t=n.parse(`mongodb://${e}`);if(t.path==="/:"){p=new i("Double colon in host identifier");return null}if(e.match(/\.sock/)){t.hostname=o.unescape(e);t.port=null}if(Number.isNaN(t.port)){p=new i("Invalid port (non-numeric string)");return}const r={host:t.hostname,port:t.port?parseInt(t.port):27017};if(r.port===0){p=new i("Invalid port (zero) with hostname");return}if(r.port>65535){p=new i("Invalid port (larger than 65535) with hostname");return}if(r.port<0){p=new i("Invalid port (negative number)");return}return r})).filter((e=>!!e));if(p){return r(p)}if(E.length===0||E[0].host===""||E[0].host===null){return r(new i("No hostname or hostnames provided in connection string"))}const I=!!h.directConnection;if(I&&E.length!==1){return r(new i("directConnection option requires exactly one host"))}if(h.directConnection==null&&E.length===1&&h.replicaSet==null){h.directConnection=true}const y={hosts:E,auth:d.db||d.username?d:null,options:Object.keys(h).length?h:null};if(y.auth&&y.auth.db){y.defaultDatabase=y.auth.db}else{y.defaultDatabase="test"}y.options=translateTLSOptions(y.options);try{applyAuthExpectations(y)}catch(e){return r(e)}r(null,y)}e.exports=parseConnectionString},1178:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6113);const s=r(3182)(require);const uuidV4=()=>{const e=o.randomBytes(16);e[6]=e[6]&15|64;e[8]=e[8]&63|128;return e};function relayEvents(e,t,r){r.forEach((r=>e.on(r,(e=>t.emit(r,e)))))}function retrieveKerberos(){let e;try{e=s("kerberos")}catch(e){if(e.code==="MODULE_NOT_FOUND"){throw new Error("The `kerberos` module was not found. Please install it and try again.")}throw e}return e}const noEJSONError=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function retrieveEJSON(){let e=s("mongodb-extjson");if(!e){e={parse:noEJSONError,deserialize:noEJSONError,serialize:noEJSONError,stringify:noEJSONError,setBSONModule:noEJSONError,BSON:noEJSONError}}return e}function maxWireVersion(e){if(e){if(e.ismaster){return e.ismaster.maxWireVersion}if(typeof e.lastIsMaster==="function"){const t=e.lastIsMaster();if(t){return t.maxWireVersion}}if(e.description){return e.description.maxWireVersion}}return 0}function collationNotSupported(e,t){return t&&t.collation&&maxWireVersion(e)<5}function isPromiseLike(e){return e&&typeof e.then==="function"}function eachAsync(e,t,r){e=e||[];let n=0;let o=0;for(n=0;ne===t[r]))}function tagsStrictEqual(e,t){const r=Object.keys(e);const n=Object.keys(t);return r.length===n.length&&r.every((r=>t[r]===e[r]))}function errorStrictEqual(e,t){if(e===t){return true}if(e==null&&t!=null||e!=null&&t==null){return false}if(e.constructor.name!==t.constructor.name){return false}if(e.message!==t.message){return false}return true}function makeStateMachine(e){return function stateTransition(t,r){const n=e[t.s.state];if(n&&n.indexOf(r)<0){throw new TypeError(`illegal state transition from [${t.s.state}] => [${r}], allowed: [${n}]`)}t.emit("stateChanged",t.s.state,r);t.s.state=r}}function makeClientMetadata(e){e=e||{};const t={driver:{name:"nodejs",version:r(1693).i8},os:{type:n.type(),name:process.platform,architecture:process.arch,version:n.release()},platform:`'Node.js ${process.version}, ${n.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo){if(e.driverInfo.name){t.driver.name=`${t.driver.name}|${e.driverInfo.name}`}if(e.driverInfo.version){t.version=`${t.driver.version}|${e.driverInfo.version}`}if(e.driverInfo.platform){t.platform=`${t.platform}|${e.driverInfo.platform}`}}if(e.appname){const r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}const noop=()=>{};e.exports={uuidV4:uuidV4,relayEvents:relayEvents,collationNotSupported:collationNotSupported,retrieveEJSON:retrieveEJSON,retrieveKerberos:retrieveKerberos,maxWireVersion:maxWireVersion,isPromiseLike:isPromiseLike,eachAsync:eachAsync,eachAsyncSeries:eachAsyncSeries,isUnifiedTopology:isUnifiedTopology,arrayStrictEqual:arrayStrictEqual,tagsStrictEqual:tagsStrictEqual,errorStrictEqual:errorStrictEqual,makeStateMachine:makeStateMachine,makeClientMetadata:makeClientMetadata,noop:noop}},7276:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(8988).Msg;const s=r(3111).MongoError;const i=r(7272).getReadPreference;const a=r(7272).isSharded;const A=r(7272).databaseNamespace;const c=r(1707).isTransactionCommand;const l=r(5474).applySession;const u=r(3111).MongoNetworkError;const h=r(1178).maxWireVersion;function isClientEncryptionEnabled(e){const t=h(e);return t&&e.autoEncrypter}function command(e,t,r,n,o){if(typeof n==="function")o=n,n={};n=n||{};if(r==null){return o(new s(`command ${JSON.stringify(r)} does not return a cursor`))}if(!isClientEncryptionEnabled(e)){_command(e,t,r,n,o);return}const i=h(e);if(typeof i!=="number"||i<8){o(new s("Auto-encryption requires a minimum MongoDB version of 4.2"));return}_cryptCommand(e,t,r,n,o)}function _command(e,t,r,h,d){const g=e.s.bson;const p=e.s.pool;const E=i(r,h);const m=supportsOpMsg(e);const C=h.session;const I=e.clusterTime;let y=I;let B=Object.assign({},r);const Q=h.serverApi;if(Q){B.apiVersion=Q.version||Q;if(Q.strict!=null){B.apiStrict=Q.strict}if(Q.deprecationErrors!=null){B.apiDeprecationErrors=Q.deprecationErrors}}if(hasSessionSupport(e)&&C){const e=C.clusterTime;if(I&&I.clusterTime&&e&&e.clusterTime&&e.clusterTime.greaterThan(I.clusterTime)){y=e}if(!C.transaction.isActive&&C.transaction.isPinned&&!B.startTransaction&&!B.commitTransaction){C.transaction.unpinServer()}const t=l(C,B,h);if(t){return d(t)}}if(y){B.$clusterTime=y}if(a(e)&&!m&&E&&E.mode!=="primary"){B={$query:B,$readPreference:E.toJSON()}}const b=Object.assign({command:true,numberToSkip:0,numberToReturn:-1,checkKeys:false},h);b.slaveOk=E.slaveOk();const w=`${A(t)}.$cmd`;const S=m?new o(g,w,B,b):new n(g,w,B,b);const v=C&&(C.inTransaction()||c(B));const R=v?function(e){if(e&&e instanceof u&&!e.hasErrorLabel("TransientTransactionError")){e.addErrorLabel("TransientTransactionError")}if(!r.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")){C.transaction.unpinServer()}return d.apply(null,arguments)}:d;try{p.write(S,b,R)}catch(e){R(e)}}function hasSessionSupport(e){if(e==null)return false;if(e.description){return e.description.maxWireVersion>=6}return e.ismaster==null?false:e.ismaster.maxWireVersion>=6}function supportsOpMsg(e){const t=e.ismaster?e.ismaster:e.description;if(t==null){return false}return t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}function _cryptCommand(e,t,r,n,o){const s=e.autoEncrypter;function commandResponseHandler(e,t){if(e||t==null){o(e,t);return}s.decrypt(t.result,n,((e,r)=>{if(e){o(e,null);return}t.result=r;t.message.documents=[r];o(null,t)}))}s.encrypt(t,r,n,((r,s)=>{if(r){o(r,null);return}_command(e,t,s,n,commandResponseHandler)}))}e.exports=command},7793:(e,t,r)=>{"use strict";const n=r(7746).retrieveSnappy();const o=r(9796);const s={snappy:1,zlib:2};const i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function compress(e,t,r){switch(e.options.agreedCompressor){case"snappy":n.compress(t,r);break;case"zlib":var s={};if(e.options.zlibCompressionLevel){s.level=e.options.zlibCompressionLevel}o.deflate(t,s,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}function decompress(e,t,r){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:n.uncompress(t,r);break;case s.zlib:o.inflate(t,r);break;default:r(null,t)}}e.exports={compressorIDs:s,uncompressibleCommands:i,compress:compress,decompress:decompress}},7161:e=>{"use strict";const t="2.6";const r="5.0";const n=2;const o=13;e.exports={MIN_SUPPORTED_SERVER_VERSION:t,MAX_SUPPORTED_SERVER_VERSION:r,MIN_SUPPORTED_WIRE_VERSION:n,MAX_SUPPORTED_WIRE_VERSION:o}},1971:(e,t,r)=>{"use strict";const n=r(9814).GetMore;const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=o();const A=a.Long;const c=r(7272).collectionNamespace;const l=r(1178).maxWireVersion;const u=r(7272).applyCommonQueryOptions;const h=r(7276);function getMore(e,t,r,o,a,d){a=a||{};const g=l(e);function queryCallback(e,t){if(e)return d(e);const n=t.message;if(n.cursorNotFound){return d(new i("cursor killed or timed out"),null)}if(g<4){const e=typeof n.cursorId==="number"?A.fromNumber(n.cursorId):n.cursorId;r.documents=n.documents;r.cursorId=e;d(null,null,n.connection);return}if(n.documents[0].ok===0){return d(new s(n.documents[0]))}const o=typeof n.documents[0].cursor.id==="number"?A.fromNumber(n.documents[0].cursor.id):n.documents[0].cursor.id;r.documents=n.documents[0].cursor.nextBatch;r.cursorId=o;d(null,n.documents[0],n.connection)}if(g<4){const s=e.s.bson;const i=new n(s,t,r.cursorId,{numberToReturn:o});const a=u({},r);e.s.pool.write(i,a,queryCallback);return}const p=r.cursorId instanceof A?r.cursorId:A.fromNumber(r.cursorId);const E={getMore:p,collection:c(t),batchSize:Math.abs(o)};if(r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS==="number"){E.maxTimeMS=r.cmd.maxAwaitTimeMS}const m=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},a);if(r.session){m.session=r.session}h(e,t,E,m,queryCallback)}e.exports=getMore},9206:(e,t,r)=>{"use strict";const n=r(779);e.exports={insert:function insert(e,t,r,o,s){n(e,"insert","documents",t,r,o,s)},update:function update(e,t,r,o,s){n(e,"update","updates",t,r,o,s)},remove:function remove(e,t,r,o,s){n(e,"delete","deletes",t,r,o,s)},killCursors:r(6044),getMore:r(1971),query:r(1820),command:r(7276)}},6044:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(3111).MongoError;const s=r(3111).MongoNetworkError;const i=r(7272).collectionNamespace;const a=r(1178).maxWireVersion;const A=r(1178).emitWarning;const c=r(7276);function killCursors(e,t,r,l,u){if(typeof l==="function"){u=l;l={}}u=typeof u==="function"?u:()=>{};const h=r.cursorId;if(a(e)<4){const o=e.s.bson;const s=e.s.pool;const i=new n(o,t,[h]);const a={immediateRelease:true,noResponse:true};if(typeof r.session==="object"){a.session=r.session}if(s&&s.isConnected()){try{s.write(i,a,u)}catch(e){if(typeof u==="function"){u(e,null)}else{A(e)}}}return}const d={killCursors:i(t),cursors:[h]};const g=l||{};if(typeof r.session==="object")g.session=r.session;c(e,t,d,g,((e,t)=>{if(e){return u(e)}const r=t.message;if(r.cursorNotFound){return u(new s("cursor killed or timed out"),null)}if(!Array.isArray(r.documents)||r.documents.length===0){return u(new o(`invalid killCursors result returned for cursor id ${h}`))}u(null,r.documents[0])}))}e.exports=killCursors},1820:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(3111).MongoError;const s=r(7272).getReadPreference;const i=r(7272).collectionNamespace;const a=r(7272).isSharded;const A=r(1178).maxWireVersion;const c=r(7272).applyCommonQueryOptions;const l=r(7276);const u=r(1371).decorateWithExplain;const h=r(5293).Explain;function query(e,t,r,n,i,a){i=i||{};if(n.cursorId!=null){return a()}if(r==null){return a(new o(`command ${JSON.stringify(r)} does not return a cursor`))}if(A(e)<4){const o=prepareLegacyFindQuery(e,t,r,n,i);const s=c({},n);if(typeof o.documentsReturnedIn==="string"){s.documentsReturnedIn=o.documentsReturnedIn}e.s.pool.write(o,s,a);return}const d=s(r,i);let g=prepareFindCommand(e,t,r,n,i);try{const e=h.fromOptions(i);if(e){g=u(g,e)}}catch(e){return a(e)}r.virtual=false;const p=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:d.slaveOk()},i);if(r.readPreference){p.readPreference=d}if(n.session){p.session=n.session}l(e,t,g,p,a)}function prepareFindCommand(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;const o={find:i(t)};if(r.query){if(r.query["$query"]){o.filter=r.query["$query"]}else{o.filter=r.query}}let s=r.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];if(t==="asc"){t=1}else if(t==="desc"){t=-1}e[s[0]]=t}else{for(let t=0;t0&&i.batchSize===0){u=i.limit}else{u=i.batchSize}const h=i.skip||0;const d={};if(a(e)&&l){d["$readPreference"]=l.toJSON()}if(r.sort)d["$orderby"]=r.sort;if(r.hint)d["$hint"]=r.hint;if(r.snapshot)d["$snapshot"]=r.snapshot;if(typeof r.returnKey!=="undefined")d["$returnKey"]=r.returnKey;if(r.maxScan)d["$maxScan"]=r.maxScan;if(r.min)d["$min"]=r.min;if(r.max)d["$max"]=r.max;if(typeof r.showDiskLoc!=="undefined")d["$showDiskLoc"]=r.showDiskLoc;if(r.comment)d["$comment"]=r.comment;if(r.maxTimeMS)d["$maxTimeMS"]=r.maxTimeMS;if(A.explain!==undefined){u=-Math.abs(r.limit||0);d["$explain"]=true}d["$query"]=r.query;if(r.readConcern&&r.readConcern.level!=="local"){throw new o(`server find command does not support a readConcern level of ${r.readConcern.level}`)}if(r.readConcern){r=Object.assign({},r);delete r["readConcern"]}const g=typeof A.serializeFunctions==="boolean"?A.serializeFunctions:false;const p=typeof A.ignoreUndefined==="boolean"?A.ignoreUndefined:false;const E=new n(c,t,d,{numberToSkip:h,numberToReturn:u,pre32Limit:typeof r.limit!=="undefined"?r.limit:undefined,checkKeys:false,returnFieldSelector:r.fields,serializeFunctions:g,ignoreUndefined:p});if(typeof r.tailable==="boolean")E.tailable=r.tailable;if(typeof r.oplogReplay==="boolean")E.oplogReplay=r.oplogReplay;if(typeof r.noCursorTimeout==="boolean")E.noCursorTimeout=r.noCursorTimeout;if(typeof r.awaitData==="boolean")E.awaitData=r.awaitData;if(typeof r.partial==="boolean")E.partial=r.partial;E.slaveOk=l.slaveOk();return E}e.exports=query},7272:(e,t,r)=>{"use strict";const n=r(4485);const o=r(3111).MongoError;const s=r(2291).ServerType;const i=r(7962).TopologyDescription;const a=16;const A=9;var c={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};var getReadPreference=function(e,t){var r=e.readPreference||new n("primary");if(t.readPreference){r=t.readPreference}if(typeof r==="string"){r=new n(r)}if(!(r instanceof n)){throw new o("read preference must be a ReadPreference instance")}return r};var parseHeader=function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}};function applyCommonQueryOptions(e,t){Object.assign(e,{raw:typeof t.raw==="boolean"?t.raw:false,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,monitoring:typeof t.monitoring==="boolean"?t.monitoring:false,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false});if(typeof t.socketTimeout==="number"){e.socketTimeout=t.socketTimeout}if(t.session){e.session=t.session}if(typeof t.documentsReturnedIn==="string"){e.documentsReturnedIn=t.documentsReturnedIn}return e}function isSharded(e){if(e.type==="mongos")return true;if(e.description&&e.description.type===s.Mongos){return true}if(e.description&&e.description instanceof i){const t=Array.from(e.description.servers.values());return t.some((e=>e.type===s.Mongos))}return false}function databaseNamespace(e){return e.split(".")[0]}function collectionNamespace(e){return e.split(".").slice(1).join(".")}e.exports={getReadPreference:getReadPreference,MESSAGE_HEADER_SIZE:a,COMPRESSION_DETAILS_SIZE:A,opcodes:c,parseHeader:parseHeader,applyCommonQueryOptions:applyCommonQueryOptions,isSharded:isSharded,databaseNamespace:databaseNamespace,collectionNamespace:collectionNamespace}},779:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(7272).collectionNamespace;const s=r(7276);const i=r(1371).decorateWithExplain;const a=r(5293).Explain;function writeCommand(e,t,r,A,c,l,u){if(c.length===0)throw new n(`${t} must contain at least one document`);if(typeof l==="function"){u=l;l={}}l=l||{};const h=typeof l.ordered==="boolean"?l.ordered:true;const d=l.writeConcern;let g={};g[t]=o(A);g[r]=c;g.ordered=h;if(d&&Object.keys(d).length>0){g.writeConcern=d}if(l.collation){for(let e=0;e{"use strict";const n=r(2781).Transform;const o=r(2781).PassThrough;const s=r(3837).deprecate;const i=r(1371).handleCallback;const a=r(3994).ReadPreference;const A=r(3994).MongoError;const c=r(4847).CoreCursor;const l=r(4847).CursorState;const u=r(3994).BSON.Map;const h=r(1371).maybePromise;const d=r(2548);const g=r(1371).formattedOrderClause;const p=r(5293).Explain;const E=r(1018).Aspect;const m=r(3554).each;const C=r(7885);const I=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];const y=["numberOfRetries","tailableRetryInterval"];class Cursor extends c{constructor(e,t,r,n){super(e,t,r,n);if(this.operation){n=this.operation.options}const o=n.numberOfRetries||5;const s=n.tailableRetryInterval||500;const i=o;const a=n.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!n.explicitlyIgnoreSession};if(!n.explicitlyIgnoreSession&&n.session){this.cursorState.session=n.session}if(this.options.noCursorTimeout===true){this.addCursorFlag("noCursorTimeout",true)}let A=1e3;if(this.cmd.cursor&&this.cmd.cursor.batchSize){A=this.cmd.cursor.batchSize}else if(n.cursor&&n.cursor.batchSize){A=n.cursor.batchSize}else if(typeof n.batchSize==="number"){A=n.batchSize}this.setCursorBatchSize(A)}get readPreference(){if(this.operation){return this.operation.readPreference}return this.options.readPreference}get sortValue(){return this.cmd.sort}set session(e){this.cursorState.session=e}_initializeCursor(e){if(this.operation&&this.operation.session!=null){this.cursorState.session=this.operation.session}else{if(!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()){this.cursorState.session=this.topology.startSession({owner:this});if(this.operation){this.operation.session=this.cursorState.session}}}super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}return h(this,e,(e=>{const t=this;if(t.isNotified()){return e(null,false)}t._next(((r,n)=>{if(r)return e(r);if(n==null||t.s.state===Cursor.CLOSED||t.isDead()){return e(null,false)}t.s.state=l.OPEN;t.cursorState.cursorIndex--;if(t.cursorState.limit>0){t.cursorState.currentLimit--}e(null,true)}))}))}next(e){return h(this,e,(e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead()){e(A.create({message:"Cursor is closed",driver:true}));return}if(t.s.state===l.INIT&&t.cmd.sort){try{t.cmd.sort=g(t.cmd.sort)}catch(t){return e(t)}}t._next(((r,n)=>{if(r)return e(r);t.s.state=l.OPEN;e(null,n)}))}))}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.query=e;return this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxScan=e;return this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.hint=e;return this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.min=e;return this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.max=e;return this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.returnKey=e;return this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.showDiskLoc=e;return this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.snapshot=e;return this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(y.indexOf(e)===-1){throw A.create({message:`option ${e} is not a supported option ${y}`,driver:true})}this.s[e]=t;if(e==="numberOfRetries")this.s.currentNumberOfRetries=t;return this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(I.indexOf(e)===-1){throw A.create({message:`flag ${e} is not a supported flag ${I}`,driver:true})}if(typeof t!=="boolean"){throw A.create({message:`flag ${e} must be a boolean value`,driver:true})}this.cmd[e]=t;return this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(e[0]!=="$"){throw A.create({message:`${e} is not a valid query modifier`,driver:true})}const r=e.substr(1);this.cmd[r]=t;if(r==="orderby")this.cmd.sort=this.cmd[r];return this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.comment=e;return this}maxAwaitTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxAwaitTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxAwaitTimeMS=e;return this}maxTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxTimeMS=e;return this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.fields=e;return this}sort(e,t){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support sorting",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}let r=e;if(Array.isArray(r)&&Array.isArray(r[0])){r=new u(r.map((e=>{const t=[e[0],null];if(e[1]==="asc"){t[1]=1}else if(e[1]==="desc"){t[1]=-1}else if(e[1]===1||e[1]===-1||e[1].$meta){t[1]=e[1]}else{throw new A("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}return t})))}if(t!=null){r=[[e,t]]}this.cmd.sort=r;return this}batchSize(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support batchSize",driver:true})}if(this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"batchSize requires an integer",driver:true})}this.cmd.batchSize=e;this.setCursorBatchSize(e);return this}collation(e){this.cmd.collation=e;return this}limit(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support limit",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"limit requires an integer",driver:true})}this.cmd.limit=e;this.setCursorLimit(e);return this}skip(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support skip",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"skip requires an integer",driver:true})}this.cmd.skip=e;this.setCursorSkip(e);return this}each(e){this.rewind();this.s.state=l.INIT;m(this,e)}forEach(e,t){this.rewind();this.s.state=l.INIT;if(typeof t==="function"){m(this,((r,n)=>{if(r){t(r);return false}if(n!=null){try{e(n)}catch(e){t(e);return false}return true}if(n==null&&t){const e=t;t=null;e(null);return false}}))}else{return new this.s.promiseLibrary(((t,r)=>{m(this,((n,o)=>{if(n){r(n);return false}else if(o==null){t(null);return false}else{try{e(o)}catch(e){r(e);return false}return true}}))}))}}setReadPreference(e){if(this.s.state!==l.INIT){throw A.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof a){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new a(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}toArray(e){if(this.options.tailable){throw A.create({message:"Tailable cursor cannot be converted to array",driver:true})}return h(this,e,(e=>{const t=this;const r=[];t.rewind();t.s.state=l.INIT;const fetchDocs=()=>{t._next(((n,o)=>{if(n){return i(e,n)}if(o==null){return t.close({skipKillCursors:true},(()=>i(e,null,r)))}r.push(o);if(t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(r,e)}fetchDocs()}))};fetchDocs()}))}count(e,t,r){if(this.cmd.query==null)throw A.create({message:"count can only be used with find command",driver:true});if(typeof t==="function")r=t,t={};t=t||{};if(typeof e==="function"){r=e;e=true}if(this.cursorState.session){t=Object.assign({},t,{session:this.cursorState.session})}const n=new C(this,e,t);return d(this.topology,n,r)}close(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{skipKillCursors:false},e);return h(this,t,(t=>{this.s.state=l.CLOSED;if(!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=r=>e(t(r))}else{this.cursorState.transforms={doc:e}}return this}isClosed(){return this.isDead()}destroy(e){if(e)this.emit("error",e);this.pause();this.close()}stream(e){this.cursorState.streamOptions=e||{};return this}transformStream(e){const t=e||{};if(typeof t.transform==="function"){const e=new n({objectMode:true,transform:function(e,r,n){this.push(t.transform(e));n()}});return this.pipe(e)}return this.pipe(new o({objectMode:true}))}explain(e,t){if(typeof e==="function")t=e,e=true;if(e===undefined)e=true;if(!this.operation||!this.operation.hasAspect(E.EXPLAINABLE)){throw new A("This command cannot be explained")}this.operation.explain=new p(e);return h(this,t,(e=>{c.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}Cursor.prototype.maxTimeMs=Cursor.prototype.maxTimeMS;s(Cursor.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");s(Cursor.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");s(Cursor.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");e.exports=Cursor},6662:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(3837).inherits;const s=r(1371).getSingleProperty;const i=r(538);const a=r(1371).handleCallback;const A=r(1371).filterOptions;const c=r(1371).toError;const l=r(3994).ReadPreference;const u=r(3994).MongoError;const h=r(3994).ObjectID;const d=r(3994).Logger;const g=r(5193);const p=r(1371).conditionallyMergeWriteConcern;const E=r(1371).executeLegacyOperation;const m=r(1117);const C=r(3837).deprecate;const I=r(1371).deprecateOptions;const y=r(1371).MongoDBNamespace;const B=r(147);const Q=r(2481);const b=r(7289);const w=r(7429);const S=r(2226).createListener;const v=r(2226).ensureIndex;const R=r(2226).evaluate;const k=r(2226).profilingInfo;const D=r(2226).validateDatabaseName;const N=r(1554);const T=r(7057);const O=r(286);const _=r(499);const M=r(1363);const L=r(5561);const F=r(6394);const U=r(2360).DropCollectionOperation;const P=r(2360).DropDatabaseOperation;const G=r(1681);const Y=r(4245);const V=r(840);const W=r(3969);const J=r(1969);const q=r(2808);const j=r(6301);const z=r(2548);const $=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function Db(e,t,r){r=r||{};if(!(this instanceof Db))return new Db(e,t,r);n.call(this);const o=r.promiseLibrary||Promise;r=A(r,$);r.promiseLibrary=o;this.s={dbCache:{},children:[],topology:t,options:r,logger:d("Db",r),bson:t?t.bson:null,readPreference:l.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||h,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:o,noListener:typeof r.noListener==="boolean"?r.noListener:false,readConcern:b.fromOptions(r),writeConcern:Q.fromOptions(r),namespace:new y(e)};D(e);s(this,"serverConfig",this.s.topology);s(this,"bufferMaxEntries",this.s.bufferMaxEntries);s(this,"databaseName",this.s.namespace.db);if(r.parentDb)return;if(this.s.noListener)return;t.on("error",S(this,"error",this));t.on("timeout",S(this,"timeout",this));t.on("close",S(this,"close",this));t.on("parseError",S(this,"parseError",this));t.once("open",S(this,"open",this));t.once("fullsetup",S(this,"fullsetup",this));t.once("all",S(this,"all",this));t.on("reconnect",S(this,"reconnect",this))}o(Db,n);Db.prototype.on=C((function(){return Db.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Db.prototype.once=C((function(){return Db.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(Db.prototype,"topology",{enumerable:true,get:function(){return this.s.topology}});Object.defineProperty(Db.prototype,"options",{enumerable:true,get:function(){return this.s.options}});Object.defineProperty(Db.prototype,"slaveOk",{enumerable:true,get:function(){if(this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")){return true}return false}});Object.defineProperty(Db.prototype,"readConcern",{enumerable:true,get:function(){return this.s.readConcern}});Object.defineProperty(Db.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return l.primary}return this.s.readPreference}});Object.defineProperty(Db.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(Db.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Db.prototype.command=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);const n=new M(this,e,t);return z(this.s.topology,n,r)};Db.prototype.aggregate=function(e,t,r){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}const n=new w(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Db.prototype.admin=function(){const e=r(3238);return new e(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];Db.prototype.collection=I({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t=Object.assign({},t);t.promiseLibrary=this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;if(this.s.options.ignoreUndefined){t.ignoreUndefined=this.s.options.ignoreUndefined}for(const e of K){if(!(e in t)&&this.s.options[e]!==undefined){t[e]=this.s.options[e]}}t=p(t,this.s.options);if(t==null||!t.strict){try{const n=new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);if(r)r(null,n);return n}catch(e){if(e instanceof u&&r)return r(e);throw e}}if(typeof r!=="function"){throw c(`A callback is required in strict mode. While getting collection ${e}`)}if(this.serverConfig&&this.serverConfig.isDestroyed()){return r(new u("topology was destroyed"))}const n=Object.assign({},t,{nameOnly:true});this.listCollections({name:e},n).toArray(((n,o)=>{if(n!=null)return a(r,n,null);if(o.length===0)return a(r,c(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(r,null,new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(n){return a(r,n,null)}}))}));Db.prototype.createCollection=I({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;const n=new L(this,e,t);return z(this.s.topology,n,r)}));Db.prototype.stats=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={dbStats:true};if(e["scale"]!=null)r["scale"]=e["scale"];if(e.readPreference==null&&this.s.readPreference){e.readPreference=this.s.readPreference}const n=new _(this,e,null,r);return z(this.s.topology,n,t)};Db.prototype.listCollections=function(e,t){e=e||{};t=t||{};return new i(this.s.topology,new V(this,e,t),t)};Db.prototype.eval=C((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():t;r=o.length?o.shift()||{}:{};return E(this.s.topology,R,[this,e,t,r,n])}),"Db.eval is deprecated as of MongoDB version 3.2");Db.prototype.renameCollection=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r,{readPreference:l.PRIMARY});r.new_collection=true;const o=new q(this.collection(e),t,r);return z(this.s.topology,o,n)};Db.prototype.dropCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new U(this,e,t);return z(this.s.topology,n,r)};Db.prototype.dropDatabase=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new P(this,e);return z(this.s.topology,r,t)};Db.prototype.collections=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new O(this,e);return z(this.s.topology,r,t)};Db.prototype.executeDbAdminCommand=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.readPreference=l.resolve(this,t);const n=new G(this,e,t);return z(this.s.topology,n,r)};Db.prototype.createIndex=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r?Object.assign({},r):{};const o=new F(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.ensureIndex=C((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return E(this.s.topology,v,[this,e,t,r,n])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");Db.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};Db.prototype.addUser=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}const o=new T(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.removeUser=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new J(this,e,t);return z(this.s.topology,n,r)};Db.prototype.setProfilingLevel=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new j(this,e,t);return z(this.s.topology,n,r)};Db.prototype.profilingInfo=C((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return E(this.s.topology,k,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly.");Db.prototype.profilingLevel=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new W(this,e);return z(this.s.topology,r,t)};Db.prototype.indexInformation=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new Y(this,e,t);return z(this.s.topology,n,r)};Db.prototype.unref=function(){this.s.topology.unref()};Db.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Db.prototype.getLogger=function(){return this.s.logger};Db.SYSTEM_NAMESPACE_COLLECTION=B.SYSTEM_NAMESPACE_COLLECTION;Db.SYSTEM_INDEX_COLLECTION=B.SYSTEM_INDEX_COLLECTION;Db.SYSTEM_PROFILE_COLLECTION=B.SYSTEM_PROFILE_COLLECTION;Db.SYSTEM_USER_COLLECTION=B.SYSTEM_USER_COLLECTION;Db.SYSTEM_COMMAND_COLLECTION=B.SYSTEM_COMMAND_COLLECTION;Db.SYSTEM_JS_COLLECTION=B.SYSTEM_JS_COLLECTION;e.exports=Db},8275:(e,t,r)=>{"use strict";let n;let o;let s;function loadCollection(){if(!n){n=r(5193)}return n}function loadCursor(){if(!o){o=r(7159)}return o}function loadDb(){if(!s){s=r(6662)}return s}e.exports={loadCollection:loadCollection,loadCursor:loadCursor,loadDb:loadDb}},3012:(e,t,r)=>{"use strict";const n=r(1545);const o=r(7746).retrieveBSON();const s=r(3111).MongoError;let i=undefined;try{i=r(5764)}catch(e){throw new s("Auto-encryption requested, but the module is not installed. "+"Please add `mongodb-client-encryption` as a dependency of your project")}if(i===undefined||typeof i.extension!=="function"){throw new s("loaded version of `mongodb-client-encryption` does not have property `extension`. "+"Please make sure you are loading the correct version of `mongodb-client-encryption`")}const a=i.extension(r(5517)).AutoEncrypter;const A=Symbol("internalClient");class Encrypter{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption;this.needsConnecting=false;if(t.maxPoolSize===0&&t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=e}else if(t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=this.getInternalClient(e)}if(this.bypassAutoEncryption){t.autoEncryption.metadataClient=undefined}else if(t.maxPoolSize===0){t.autoEncryption.metadataClient=e}else{t.autoEncryption.metadataClient=this.getInternalClient(e)}t.autoEncryption.bson=Encrypter.makeBSON(t);this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[A]){const t={};for(const r of Object.keys(e.s.options)){if(["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(r)!==-1)continue;t[r]=e.s.options[r]}t.minPoolSize=0;const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[A]=new n(e.s.url,t);for(const t of r){for(const r of e.listeners(t)){this[A].on(t,r)}}e.on("newListener",((e,t)=>{this[A].on(e,t)}));this.needsConnecting=true}return this[A]}connectInternalClient(e){if(this.needsConnecting){this.needsConnecting=false;return this[A].connect(e)}return e()}close(e,t,r){this.autoEncrypter.teardown((n=>{if(this[A]&&e!==this[A]){return this[A].close(t,r)}r(n)}))}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:Encrypter}},9386:(e,t,r)=>{"use strict";const n=r(3994).MongoNetworkError;const o=r(8072).MONGODB_ERROR_CODES;const s=new Set([o.HostUnreachable,o.HostNotFound,o.NetworkTimeout,o.ShutdownInProgress,o.PrimarySteppedDown,o.ExceededTimeLimit,o.SocketException,o.NotMaster,o.InterruptedAtShutdown,o.InterruptedDueToReplStateChange,o.NotMasterNoSlaveOk,o.NotMasterOrSecondary,o.StaleShardVersion,o.StaleEpoch,o.StaleConfig,o.RetryChangeStream,o.FailedToSatisfyReadPreference,o.CursorNotFound]);function isResumableError(e,t){if(e instanceof n){return true}if(t>=9){if(e.code===o.CursorNotFound){return true}return e.hasErrorLabel("ResumableChangeStreamError")}return s.has(e.code)}e.exports={GET_MORE_RESUMABLE_CODES:s,isResumableError:isResumableError,MONGODB_ERROR_CODES:o}},8072:e=>{"use strict";const t=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});e.exports=Object.freeze({MONGODB_ERROR_CODES:t})},5293:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class Explain{constructor(e){if(typeof e==="boolean"){this.verbosity=e?"allPlansExecution":"queryPlanner"}else{this.verbosity=e}}static fromOptions(e){if(e==null||e.explain===undefined){return}const t=e.explain;if(typeof t==="boolean"||typeof t==="string"){return new Explain(e.explain)}throw new n(`explain must be a string or a boolean`)}}e.exports={Explain:Explain}},4190:(e,t,r)=>{"use strict";var n=r(2781),o=r(3837);e.exports=GridFSBucketReadStream;function GridFSBucketReadStream(e,t,r,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:false,expectedEnd:0,file:null,options:s,readPreference:r};n.Readable.call(this)}o.inherits(GridFSBucketReadStream,n.Readable);GridFSBucketReadStream.prototype._read=function(){var e=this;if(this.destroyed){return}waitForFile(e,(function(){doRead(e)}))};GridFSBucketReadStream.prototype.start=function(e){throwIfInitialized(this);this.s.options.start=e;return this};GridFSBucketReadStream.prototype.end=function(e){throwIfInitialized(this);this.s.options.end=e;return this};GridFSBucketReadStream.prototype.abort=function(e){var t=this;this.push(null);this.destroyed=true;if(this.s.cursor){this.s.cursor.close((function(r){t.emit("close");e&&e(r)}))}else{if(!this.s.init){t.emit("close")}e&&e()}};function throwIfInitialized(e){if(e.s.init){throw new Error("You cannot change options after the stream has entered"+"flowing mode!")}}function doRead(e){if(e.destroyed){return}e.s.cursor.next((function(t,r){if(e.destroyed){return}if(t){return __handleError(e,t)}if(!r){e.push(null);process.nextTick((()=>{e.s.cursor.close((function(t){if(t){__handleError(e,t);return}e.emit("close")}))}));return}var n=e.s.file.length-e.s.bytesRead;var o=e.s.expected++;var s=Math.min(e.s.file.chunkSize,n);if(r.n>o){var i="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+o;return __handleError(e,new Error(i))}if(r.n0){i["n"]={$gte:a}}}e.s.cursor=e.s.chunks.find(i).sort({n:1});if(e.s.readPreference){e.s.cursor.setReadPreference(e.s.readPreference)}e.s.expectedEnd=Math.ceil(r.length/r.chunkSize);e.s.file=r;try{e.s.bytesToTrim=handleEndOption(e,r,e.s.cursor,e.s.options)}catch(t){return __handleError(e,t)}e.emit("file",r)}))}function waitForFile(e,t){if(e.s.file){return t()}if(!e.s.init){init(e);e.s.init=true}e.once("file",(function(){t()}))}function handleStartOption(e,t,r){if(r&&r.start!=null){if(r.start>t.length){throw new Error("Stream start ("+r.start+") must not be "+"more than the length of the file ("+t.length+")")}if(r.start<0){throw new Error("Stream start ("+r.start+") must not be "+"negative")}if(r.end!=null&&r.endt.length){throw new Error("Stream end ("+n.end+") must not be "+"more than the length of the file ("+t.length+")")}if(n.start<0){throw new Error("Stream end ("+n.end+") must not be "+"negative")}var o=n.start!=null?Math.floor(n.start/t.chunkSize):0;r.limit(Math.ceil(n.end/t.chunkSize)-o);e.s.expectedEnd=Math.ceil(n.end/t.chunkSize);return Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}function __handleError(e,t){e.emit("error",t)}},2573:(e,t,r)=>{"use strict";var n=r(2361).EventEmitter;var o=r(4190);var s=r(1413);var i=r(1371).shallowClone;var a=r(1371).toError;var A=r(3837);var c=r(1371).executeLegacyOperation;const l=r(1371).deprecateOptions;var u={bucketName:"fs",chunkSizeBytes:255*1024};e.exports=GridFSBucket;function GridFSBucket(e,t){n.apply(this);this.setMaxListeners(0);if(t&&typeof t==="object"){t=i(t);var r=Object.keys(u);for(var o=0;o=0){r={uploadDate:1};n=t.revision}else{n=-t.revision-1}}var s={filename:e};t={sort:r,skip:n,start:t&&t.start,end:t&&t.end};return new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)};GridFSBucket.prototype.rename=function(e,t,r){return c(this.s.db.s.topology,_rename,[this,e,t,r],{skipSessions:true})};function _rename(e,t,r,n){var o={_id:t};var s={$set:{filename:r}};e.s._filesCollection.updateOne(o,s,(function(e,r){if(e){return n(e)}if(!r.result.n){return n(a("File with id "+t+" not found"))}n()}))}GridFSBucket.prototype.drop=function(e){return c(this.s.db.s.topology,_drop,[this,e],{skipSessions:true})};GridFSBucket.prototype.getLogger=function(){return this.s.db.s.logger};function _drop(e,t){e.s._filesCollection.drop((function(r){if(r){return t(r)}e.s._chunksCollection.drop((function(e){if(e){return t(e)}return t()}))}))}},1413:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(3994);const s=r(6113);const i=r(2781);const a=r(3837);const A=r(1867).Buffer;const c=r(1371).deprecateOptions;const l=c({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},(function(e,t,r){r=r||{};i.Writable.call(this,r);this.bucket=e;this.chunks=e.s._chunksCollection;this.filename=t;this.files=e.s._filesCollection;this.options=r;this.done=false;this.id=r.id?r.id:o.BSON.ObjectId();this.chunkSizeBytes=this.options.chunkSizeBytes;this.bufToStore=A.alloc(this.chunkSizeBytes);this.length=0;this.md5=!r.disableMD5&&s.createHash("md5");this.n=0;this.pos=0;this.state={streamEnd:false,outstandingRequests:0,errored:false,aborted:false,promiseLibrary:this.bucket.s.promiseLibrary};if(!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=true;var n=this;checkIndexes(this,(function(){n.bucket.s.checkedIndexes=true;n.bucket.emit("index")}))}}));a.inherits(l,i.Writable);l.prototype.write=function(e,t,r){var n=this;return waitForIndexes(this,(function(){return doWrite(n,e,t,r)}))};l.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}if(this.state.aborted){t=new Error("Cannot call abort() on a stream twice");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}this.state.aborted=true;this.chunks.deleteMany({files_id:this.id},(function(t){if(typeof e==="function")e(t)}))};l.prototype.end=function(e,t,r){var n=this;if(typeof e==="function"){r=e,e=null,t=null}else if(typeof t==="function"){r=t,t=null}if(checkAborted(this,r)){return}this.state.streamEnd=true;if(r){this.once("finish",(function(e){r(null,e)}))}if(!e){waitForIndexes(this,(function(){writeRemnant(n)}));return}this.write(e,t,(function(){writeRemnant(n)}))};function __handleError(e,t,r){if(e.state.errored){return}e.state.errored=true;if(r){return r(t)}e.emit("error",t)}function createChunkDoc(e,t,r){return{_id:o.BSON.ObjectId(),files_id:e,n:t,data:r}}function checkChunksIndex(e,t){e.chunks.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={files_id:1,n:1};e.chunks.createIndex(s,{background:false,unique:true},(function(e){if(e){return t(e)}t()}));return}return t(r)}var i=false;o.forEach((function(e){if(e.key){var t=Object.keys(e.key);if(t.length===2&&e.key.files_id===1&&e.key.n===1){i=true}}}));if(i){t()}else{s={files_id:1,n:1};var a=getWriteOptions(e);a.background=false;a.unique=true;e.chunks.createIndex(s,a,(function(e){if(e){return t(e)}t()}))}}))}function checkDone(e,t){if(e.done)return true;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=true;var r=createFilesDoc(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);if(checkAborted(e,t)){return false}e.files.insertOne(r,getWriteOptions(e),(function(n){if(n){return __handleError(e,n,t)}e.emit("finish",r);e.emit("close")}));return true}return false}function checkIndexes(e,t){e.files.findOne({},{_id:1},(function(r,o){if(r){return t(r)}if(o){return t()}e.files.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={filename:1,uploadDate:1};e.files.createIndex(s,{background:false},(function(r){if(r){return t(r)}checkChunksIndex(e,t)}));return}return t(r)}var i=false;o.forEach((function(e){var t=Object.keys(e.key);if(t.length===2&&e.key.filename===1&&e.key.uploadDate===1){i=true}}));if(i){checkChunksIndex(e,t)}else{s={filename:1,uploadDate:1};var a=getWriteOptions(e);a.background=false;e.files.createIndex(s,a,(function(r){if(r){return t(r)}checkChunksIndex(e,t)}))}}))}))}function createFilesDoc(e,t,r,n,o,s,i,a){var A={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:o};if(n){A.md5=n}if(s){A.contentType=s}if(i){A.aliases=i}if(a){A.metadata=a}return A}function doWrite(e,t,r,n){if(checkAborted(e,n)){return false}var o=A.isBuffer(t)?t:A.from(t,r);e.length+=o.length;if(e.pos+o.length0){var l=o.length-s;o.copy(e.bufToStore,e.pos,l,l+a);e.pos+=a;i-=a;if(i===0){if(e.md5){e.md5.update(e.bufToStore)}var u=createChunkDoc(e.id,e.n,A.from(e.bufToStore));++e.state.outstandingRequests;++c;if(checkAborted(e,n)){return false}e.chunks.insertOne(u,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;--c;if(!c){e.emit("drain",u);n&&n();checkDone(e)}}));i=e.chunkSizeBytes;e.pos=0;++e.n}s-=a;a=Math.min(i,s)}return false}function getWriteOptions(e){var t={};if(e.options.writeConcern){t.w=e.options.writeConcern.w;t.wtimeout=e.options.writeConcern.wtimeout;t.j=e.options.writeConcern.j}return t}function waitForIndexes(e,t){if(e.bucket.s.checkedIndexes){return t(false)}e.bucket.once("index",(function(){t(true)}));return true}function writeRemnant(e,t){if(e.pos===0){return checkDone(e,t)}++e.state.outstandingRequests;var r=A.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);if(e.md5){e.md5.update(r)}var n=createChunkDoc(e.id,e.n,r);if(checkAborted(e,t)){return false}e.chunks.insertOne(n,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;checkDone(e)}))}function checkAborted(e,t){if(e.state.aborted){if(typeof t==="function"){t(new Error("this stream has been aborted"))}return true}return false}e.exports=l},3890:(e,t,r)=>{"use strict";var n=r(3994).BSON.Binary,o=r(3994).BSON.ObjectID;var s=r(1867).Buffer;var Chunk=function(e,t,r){if(!(this instanceof Chunk))return new Chunk(e,t);this.file=e;var i=t==null?{}:t;this.writeConcern=r||{w:1};this.objectId=i._id==null?new o:i._id;this.chunkNumber=i.n==null?0:i.n;this.data=new n;if(typeof i.data==="string"){var a=s.alloc(i.data.length);a.write(i.data,0,i.data.length,"binary");this.data=new n(a)}else if(Array.isArray(i.data)){a=s.alloc(i.data.length);var A=i.data.join("");a.write(A,0,A.length,"binary");this.data=new n(a)}else if(i.data&&i.data._bsontype==="Binary"){this.data=i.data}else if(!s.isBuffer(i.data)&&!(i.data==null)){throw Error("Illegal chunk format")}this.internalPosition=0};Chunk.prototype.write=function(e,t){this.data.write(e,this.internalPosition,e.length,"binary");this.internalPosition=this.data.length();if(t!=null)return t(null,this);return this};Chunk.prototype.read=function(e){e=e==null||e===0?this.length():e;if(this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);this.internalPosition=this.internalPosition+e;return t}else{return""}};Chunk.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;if(this.data.buffer!=null){t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e)}else{t=s.alloc(e);e=this.data.readInto(t,this.internalPosition)}this.internalPosition=this.internalPosition+e;return t}else{return null}};Chunk.prototype.eof=function(){return this.internalPosition===this.length()?true:false};Chunk.prototype.getc=function(){return this.read(1)};Chunk.prototype.rewind=function(){this.internalPosition=0;this.data=new n};Chunk.prototype.save=function(e,t){var r=this;if(typeof e==="function"){t=e;e={}}r.file.chunkCollection((function(n,o){if(n)return t(n);var s={upsert:true};for(var i in e)s[i]=e[i];for(i in r.writeConcern)s[i]=r.writeConcern[i];if(r.data.length()>0){r.buildMongoObject((function(e){var n={forceServerObjectId:true};for(var i in r.writeConcern){n[i]=r.writeConcern[i]}o.replaceOne({_id:r.objectId},e,s,(function(e){t(e,r)}))}))}else{t(null,r)}}))};Chunk.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};if(this.objectId!=null)t._id=this.objectId;e(t)};Chunk.prototype.length=function(){return this.data.length()};Object.defineProperty(Chunk.prototype,"position",{enumerable:true,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Chunk.DEFAULT_CHUNK_SIZE=1024*255;e.exports=Chunk},9406:(e,t,r)=>{"use strict";const n=r(3890);const o=r(3994).BSON.ObjectID;const s=r(3994).ReadPreference;const i=r(1867).Buffer;const a=r(7147);const A=r(3837).format;const c=r(3837);const l=r(3994).MongoError;const u=c.inherits;const h=r(2781).Duplex;const d=r(1371).shallowClone;const g=r(1371).executeLegacyOperation;const p=r(3837).deprecate;var E=0,m=1;const C=p((()=>{}),"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var I=function GridStore(e,t,r,i,a){C();if(!(this instanceof GridStore))return new GridStore(e,t,r,i,a);this.db=e;if(typeof a==="undefined")a={};if(typeof i==="undefined"){i=r;r=undefined}else if(typeof i==="object"){a=i;i=r;r=undefined}if(t&&t._bsontype==="ObjectID"){this.referenceBy=m;this.fileId=t;this.filename=r}else if(typeof r==="undefined"){this.referenceBy=E;this.filename=t;if(i.indexOf("w")!=null){this.fileId=new o}}else{this.referenceBy=m;this.fileId=t;this.filename=r}this.mode=i==null?"r":i;this.options=a||{};this.isOpen=false;this.root=this.options["root"]==null?GridStore.DEFAULT_ROOT_COLLECTION:this.options["root"];this.position=0;this.readPreference=this.options.readPreference||e.options.readPreference||s.primary;this.writeConcern=_getWriteConcern(e,this.options);this.internalChunkSize=this.options["chunkSize"]==null?n.DEFAULT_CHUNK_SIZE:this.options["chunkSize"];var A=this.options.promiseLibrary||Promise;this.promiseLibrary=A;Object.defineProperty(this,"chunkSize",{enumerable:true,get:function(){return this.internalChunkSize},set:function(e){if(!(this.mode[0]==="w"&&this.position===0&&this.uploadDate==null)){this.internalChunkSize=this.internalChunkSize}else{this.internalChunkSize=e}}});Object.defineProperty(this,"md5",{enumerable:true,get:function(){return this.internalMd5}});Object.defineProperty(this,"chunkNumber",{enumerable:true,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};I.prototype.open=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r"){throw l.create({message:"Illegal mode "+this.mode,driver:true})}return g(this.db.s.topology,open,[this,e,t],{skipSessions:true})};var open=function(e,t,r){var n=_getWriteConcern(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var o=e.collection();o.ensureIndex([["filename",1]],n,(function(){var t=e.chunkCollection();var o=d(n);o.unique=true;t.ensureIndex([["files_id",1],["n",1]],o,(function(){_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}))}))}else{_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}};I.prototype.eof=function(){return this.position===this.length?true:false};I.prototype.getc=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,getc,[this,e,t],{skipSessions:true})};var getc=function(e,t,r){if(e.eof()){r(null,null)}else if(e.currentChunk.eof()){nthChunk(e,e.currentChunk.chunkNumber+1,(function(t,n){e.currentChunk=n;e.position=e.position+1;r(t,e.currentChunk.getc())}))}else{e.position=e.position+1;r(null,e.currentChunk.getc())}};I.prototype.puts=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};var n=e.match(/\n$/)==null?e+"\n":e;return g(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:true})};I.prototype.stream=function(){return new GridStoreStream(this)};I.prototype.write=function write(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return g(this.db.s.topology,_writeNormal,[this,e,t,r,n],{skipSessions:true})};I.prototype.destroy=function destroy(){if(!this.writable)return;this.readable=false;if(this.writable){this.writable=false;this._q.length=0;this.emit("close")}};I.prototype.writeFile=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return g(this.db.s.topology,writeFile,[this,e,t,r],{skipSessions:true})};var writeFile=function(e,t,r,o){if(typeof t==="string"){a.open(t,"r",(function(t,r){if(t)return o(t);e.writeFile(r,o)}));return}e.open((function(e,r){if(e)return o(e,r);a.fstat(t,(function(e,s){if(e)return o(e,r);var A=0;var c=0;var writeChunk=function(){var e=i.alloc(r.chunkSize);a.read(t,e,0,e.length,A,(function(e,i,l){if(e)return o(e,r);A=A+i;var u=new n(r,{n:c++},r.writeConcern);u.write(l.slice(0,i),(function(e,n){if(e)return o(e,r);n.save({},(function(e){if(e)return o(e,r);r.position=r.position+i;r.currentChunk=n;if(A>=s.size){a.close(t,(function(e){if(e)return o(e);r.close((function(e){if(e)return o(e,r);return o(null,r)}))}))}else{return process.nextTick(writeChunk)}}))}))}))};process.nextTick(writeChunk)}))}))};I.prototype.close=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,close,[this,e,t],{skipSessions:true})};var close=function(e,t,r){if(e.mode[0]==="w"){t=Object.assign({},e.writeConcern,t);if(e.currentChunk!=null&&e.currentChunk.position>0){e.currentChunk.save({},(function(n){if(n&&typeof r==="function")return r(n);e.collection((function(n,o){if(n&&typeof r==="function")return r(n);if(e.uploadDate!=null){buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}else{e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}}))}))}else{e.collection((function(n,o){if(n&&typeof r==="function")return r(n);e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}))}}else if(e.mode[0]==="r"){if(typeof r==="function")r(null,null)}else{if(typeof r==="function")r(l.create({message:A("Illegal mode %s",e.mode),driver:true}))}};I.prototype.chunkCollection=function(e){if(typeof e==="function")return this.db.collection(this.root+".chunks",e);return this.db.collection(this.root+".chunks")};I.prototype.unlink=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,unlink,[this,e,t],{skipSessions:true})};var unlink=function(e,t,r){deleteChunks(e,(function(t){if(t!==null){t.message="at deleteChunks: "+t.message;return r(t)}e.collection((function(t,n){if(t!==null){t.message="at collection: "+t.message;return r(t)}n.remove({_id:e.fileId},e.writeConcern,(function(t){r(t,e)}))}))}))};I.prototype.collection=function(e){if(typeof e==="function")this.db.collection(this.root+".files",e);return this.db.collection(this.root+".files")};I.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift():"\n";e=e||"\n";t=n.length?n.shift():{};return g(this.db.s.topology,readlines,[this,e,t,r],{skipSessions:true})};var readlines=function(e,t,r,n){e.read((function(e,r){if(e)return n(e);var o=r.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var A=e.currentChunk.readSlice(s-a._index);A.copy(a,a._index);e.position=e.position+a.length;if(s===0&&a.length===0)return o(l.create({message:"File does not exist",driver:true}),null);return o(null,a)}A=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position);A.copy(a,a._index);a._index+=A.length;nthChunk(e,e.currentChunk.chunkNumber+1,(function(r,n){if(r)return o(r);if(n.length()>0){e.currentChunk=n;e.read(t,a,o)}else{if(a._index>0){o(null,a)}else{o(l.create({message:"no chunks found for file, possibly corrupt",driver:true}),null)}}}))};I.prototype.tell=function(e){var t=this;if(typeof e==="function")return e(null,this.position);return new t.promiseLibrary((function(e){e(t.position)}))};I.prototype.seek=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():null;r=o.length?o.shift():{};return g(this.db.s.topology,seek,[this,e,t,r,n],{skipSessions:true})};var seek=function(e,t,r,n,o){if(e.mode!=="r"){return o(l.create({message:"seek is only supported for mode r",driver:true}))}var s=r==null?I.IO_SEEK_SET:r;var i=t;var a=0;if(s===I.IO_SEEK_CUR){a=e.position+i}else if(s===I.IO_SEEK_END){a=e.length+i}else{a=i}var A=Math.floor(a/e.chunkSize);var seekChunk=function(){nthChunk(e,A,(function(t,r){if(t)return o(t,null);if(r==null)return o(new Error("no chunk found"));e.currentChunk=r;e.position=a;e.currentChunk.position=e.position%e.chunkSize;o(t,e)}))};seekChunk()};var _open=function(e,t,r){var s=e.collection();var i=e.referenceBy===m?{_id:e.fileId}:{filename:e.filename};i=null==e.fileId&&e.filename==null?null:i;t.readPreference=e.readPreference;if(i!=null){s.findOne(i,t,(function(s,i){if(s){return error(s)}if(i!=null){e.fileId=i._id;e.filename=e.mode==="r"||e.filename===undefined?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(e.mode!=="r"){e.fileId=e.fileId==null?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0}else{e.length=0;var a=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return error(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?a:e.filename),driver:true}),e)}if(e.mode==="r"){nthChunk(e,0,t,(function(t,n){if(t)return error(t);e.currentChunk=n;e.position=0;r(null,e)}))}else if(e.mode==="w"&&i){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w"){e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}))}else{e.fileId=null==e.fileId?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0;if(e.mode==="w"){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}function error(e){if(error.err)return;r(error.err=e)}};var writeBuffer=function(e,t,r,o){if(typeof r==="function"){o=r;r=null}var s=typeof r==="boolean"?r:false;if(e.mode!=="w"){o(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?e.referenceBy:e.filename),driver:true}),null)}else{if(e.currentChunk.position+t.length>=e.chunkSize){var i=e.currentChunk.chunkNumber;var a=e.chunkSize-e.currentChunk.position;var c=t.slice(0,a);var u=t.slice(a);var h=[e.currentChunk.write(c)];while(u.length>=e.chunkSize){var d=new n(e,{n:i+1},e.writeConcern);c=u.slice(0,e.chunkSize);u=u.slice(e.chunkSize);i=i+1;d.write(c);h.push(d)}e.currentChunk=new n(e,{n:i+1},e.writeConcern);if(u.length>0)e.currentChunk.write(u);e.position=e.position+t.length;var g=h.length;for(var p=0;p=t.length)return s("offset larger than size of file",null);if(r&&r>t.length)return s("length is larger than the size of the file",null);if(n&&r&&n+r>t.length)return s("offset and length is larger than the size of the file",null);if(n!=null){t.seek(n,(function(e,t){if(e)return s(e);t.read(r,s)}))}else{t.read(r,s)}}))};I.readlines=function(e,t,r,n,o){var s=Array.prototype.slice.call(arguments,2);o=typeof s[s.length-1]==="function"?s.pop():undefined;r=s.length?s.shift():null;n=s.length?s.shift():null;n=n||{};return g(e.s.topology,readlinesStatic,[e,t,r,n,o],{skipSessions:true})};var readlinesStatic=function(e,t,r,n,o){var s=r==null?"\n":r;new I(e,t,"r",n).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};I.unlink=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift():{};r=r||{};return g(e.s.topology,unlinkStatic,[this,e,t,r,n],{skipSessions:true})};var unlinkStatic=function(e,t,r,n,o){var s=_getWriteConcern(t,n);if(r.constructor===Array){var i=0;for(var a=0;ae.totalBytesToRead){e.totalBytesToRead=e.totalBytesToRead-r._index;e.push(r.slice(0,r._index))}if(e.totalBytesToRead<=0){e.endCalled=true}}))};var t=e.gs.length{"use strict";const n=r(1117);const o=r(6662);const s=r(2361).EventEmitter;const i=r(3837).inherits;const a=r(3994).MongoError;const A=r(3994).ValidServerApiVersions;const c=r(3837).deprecate;const l=r(2481);const u=r(1371).MongoDBNamespace;const h=r(4485);const d=r(1371).maybePromise;const g=r(2632);const p=r(5210).connect;const E=r(5210).validOptions;function MongoClient(e,t){t=t||{};if(!(this instanceof MongoClient))return new MongoClient(e,t);s.call(this);if(t.autoEncryption)r(3012);if(t.serverApi){const e=typeof t.serverApi==="string"?{version:t.serverApi}:t.serverApi;const r=e&&e.version;if(!r){throw new a(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${A.join('", "')}"]`)}if(!A.some((e=>e===r))){throw new a(`Invalid server API version=${r}; must be in the following enum: ["${A.join('", "')}"]`)}t.serverApi=e}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:l.fromOptions(t),readPreference:h.fromOptions(t)||h.primary,namespace:new u("admin")}}i(MongoClient,s);Object.defineProperty(MongoClient.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(MongoClient.prototype,"readPreference",{enumerable:true,get:function(){return this.s.readPreference}});MongoClient.prototype.connect=function(e){if(typeof e==="string"){throw new TypeError("`connect` only accepts a callback")}const t=this;return d(this,e,(e=>{const r=E(t.s.options);if(r)return e(r);p(t,t.s.url,t.s.options,(r=>{if(r)return e(r);e(null,t)}))}))};MongoClient.prototype.logout=c((function(e,t){if(typeof e==="function")t=e,e={};if(typeof t==="function")t(null,true)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");MongoClient.prototype.close=function(e,t){if(typeof e==="function"){t=e;e=false}const r=this;return d(this,t,(t=>{const completeClose=e=>{r.emit("close",r);if(!(r.topology instanceof g)){for(const e of r.s.dbCache){e[1].emit("close",r)}}r.removeAllListeners("close");t(e)};if(r.topology==null){completeClose();return}r.topology.close(e,(t=>{const n=r.topology.s.options.encrypter;if(n){return n.close(r,e,(e=>{completeClose(t||e)}))}completeClose(t)}))}))};MongoClient.prototype.db=function(e,t){t=t||{};if(!e){e=this.s.options.dbName}const r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==true){return this.s.dbCache.get(e)}r.promiseLibrary=this.s.promiseLibrary;if(!this.topology){throw new a("MongoClient must be connected before calling MongoClient.prototype.db")}const n=new o(e,this.topology,r);this.s.dbCache.set(e,n);return n};MongoClient.prototype.isConnected=c((function(e){e=e||{};if(!this.topology)return false;return this.topology.isConnected(e)}),"isConnected is deprecated and will be removed in the next major version");MongoClient.connect=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():null;t=t||{};const o=new MongoClient(e,t);return o.connect(r)};MongoClient.prototype.startSession=function(e){e=Object.assign({explicit:true},e);if(!this.topology){throw new a("Must connect to a server before calling this method")}return this.topology.startSession(e,this.s.options)};MongoClient.prototype.withSession=function(e,t){if(typeof e==="function")t=e,e=undefined;const r=this.startSession(e);let cleanupHandler=(e,t,n)=>{cleanupHandler=()=>{throw new ReferenceError("cleanupHandler was called too many times")};n=Object.assign({throw:true},n);r.endSession();if(e){if(n.throw)throw e;return Promise.reject(e)}};try{const e=t(r);return Promise.resolve(e).then((e=>cleanupHandler(null,e))).catch((e=>cleanupHandler(e,null,{throw:true})))}catch(e){return cleanupHandler(e,null,{throw:false})}};MongoClient.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new n(this,e,t)};MongoClient.prototype.getLogger=function(){return this.s.options.logger};e.exports=MongoClient},7057:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(6113);const a=r(1371).handleCallback;const A=r(1371).toError;const c=r(1371).emitWarning;class AddUserOperation extends o{constructor(e,t,r,n){super(e,n);this.username=t;this.password=r}_buildCommand(){const e=this.db;const t=this.username;const r=this.password;const n=this.options;let o=[];if(Array.isArray(n.roles))o=n.roles;if(typeof n.roles==="string")o=[n.roles];if(o.length===0){c("Creating a user without roles is deprecated in MongoDB >= 2.6")}if((e.databaseName.toLowerCase()==="admin"||n.dbName==="admin")&&!Array.isArray(n.roles)){o=["root"]}else if(!Array.isArray(n.roles)){o=["dbOwner"]}const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=r;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+r);a=e.digest("hex")}const A={createUser:t,customData:n.customData||{},roles:o,digestPassword:s};if(typeof r==="string"){A.pwd=a}return A}execute(e){const t=this.options;if(t.digestPassword!=null){return e(A("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."))}super.execute(((t,r)=>{if(!t){return a(e,t,r)}return a(e,t,null)}))}}s(AddUserOperation,n.WRITE_OPERATION);e.exports=AddUserOperation},1554:(e,t,r)=>{"use strict";const n=r(1189);const o=r(3994).MongoError;const s=r(1178).maxWireVersion;const i=r(3994).ReadPreference;const a=r(1018).Aspect;const A=r(1018).defineAspects;const c=1;const l=8;class AggregateOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:c;this.pipeline=t;this.hasWriteStage=false;if(typeof r.out==="string"){this.pipeline=this.pipeline.concat({$out:r.out});this.hasWriteStage=true}else if(t.length>0){const e=t[t.length-1];if(e.$out||e.$merge){this.hasWriteStage=true}}if(this.hasWriteStage){this.readPreference=i.primary}if(this.explain&&this.writeConcern){throw new o('"explain" cannot be used on an aggregate call with writeConcern')}if(r.cursor!=null&&typeof r.cursor!=="object"){throw new o("cursor options must be an object")}}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const r=this.options;const n=s(e);const o={aggregate:this.target,pipeline:this.pipeline};if(this.hasWriteStage&&n=5){if(this.hasWriteStage&&this.writeConcern){Object.assign(o,{writeConcern:this.writeConcern})}}if(r.bypassDocumentValidation===true){o.bypassDocumentValidation=r.bypassDocumentValidation}if(typeof r.allowDiskUse==="boolean"){o.allowDiskUse=r.allowDiskUse}if(r.hint){o.hint=r.hint}if(this.explain){r.full=false}o.cursor=r.cursor||{};if(r.batchSize&&!this.hasWriteStage){o.cursor.batchSize=r.batchSize}super.executeCommand(e,o,t)}}A(AggregateOperation,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]);e.exports=AggregateOperation},6976:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(3994).MongoError;const i=r(1018).OperationBase;class BulkWriteOperation extends i{constructor(e,t,r){super(r);this.collection=e;this.operations=t}execute(e){const t=this.collection;const r=this.operations;let i=this.options;if(t.s.options.ignoreUndefined){i=Object.assign({},i);i.ignoreUndefined=t.s.options.ignoreUndefined}const a=i.ordered===true||i.ordered==null?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let A=false;try{for(let e=0;e{if(!r&&t){return e(t,null)}e(null,r)}))}}e.exports=BulkWriteOperation},6716:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(2226).createIndex;const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(2226).ensureIndex;const c=r(2226).evaluate;const l=r(2226).executeCommand;const u=r(1371).handleCallback;const h=r(2226).indexInformation;const d=r(3994).BSON.Long;const g=r(3994).MongoError;const p=r(3994).ReadPreference;const E=r(2296).insertDocuments;const m=r(2296).updateDocuments;const C='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}';function createIndex(e,t,r,n){s(e.s.db,e.collectionName,t,r,n)}function createIndexes(e,t,r,n){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}));h.group.key=e}d=Object.assign({},d);d.readPreference=p.resolve(e,d);a(h,e,d);try{i(h,e,d)}catch(e){return g(e,null)}l(e.s.db,h,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.retval)}))}else{const i=s!=null&&s._bsontype==="Code"?s.scope:{};i.ns=e.collectionName;i.keys=t;i.condition=r;i.initial=n;const a=C.replace(/ reduce;/,s.toString()+";");c(e.s.db,new o(a,i),null,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.result||t)}))}}function indexes(e,t,r){t=Object.assign({},{full:true},t);h(e.s.db,e.collectionName,t,r)}function indexExists(e,t,r,n){indexInformation(e,r,((e,r)=>{if(e!=null)return u(n,e,null);if(!Array.isArray(t))return u(n,null,r[t]!=null);for(let e=0;e{if(n)return u(r,n,null);if(s==null)return u(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:true},t);const i=[];if(o)t.raw=o;for(let r=0;r{if(o==null)return;if(t==null)return u(o,null,null);if(e)return u(o,e,null);u(o,null,r)}))}e.exports={createIndex:createIndex,createIndexes:createIndexes,ensureIndex:ensureIndex,group:group,indexes:indexes,indexExists:indexExists,indexInformation:indexInformation,parallelCollectionScan:parallelCollectionScan,save:save}},286:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;let s;function loadCollection(){if(!s){s=r(5193)}return s}class CollectionsOperation extends n{constructor(e,t){super(t);this.db=e}execute(e){const t=this.db;let r=this.options;let n=loadCollection();r=Object.assign({},r,{nameOnly:true});t.listCollections({},r).toArray(((r,s)=>{if(r!=null)return o(e,r,null);s=s.filter((e=>e.name.indexOf("$")===-1));o(e,null,s.map((e=>new n(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options))))}))}}e.exports=CollectionsOperation},499:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(1371).applyWriteConcern;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=r(1371).MongoDBNamespace;const u=r(7703).extractCommand;const h=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];class CommandOperation extends o{constructor(e,t,r,o){super(t);if(!this.hasAspect(n.WRITE_OPERATION)){if(r!=null){this.options.readPreference=c.resolve(r,t)}else{this.options.readPreference=c.resolve(e,t)}}else{if(r!=null){s(this.options,{db:e,coll:r},this.options)}else{s(this.options,{db:e},this.options)}this.options.readPreference=c.primary}this.db=e;if(o!=null){this.command=o}if(r!=null){this.collection=r}}_buildCommand(){if(this.command!=null){return this.command}}execute(e){const t=this.db;const r=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new A("topology was destroyed"))}let o;try{o=this._buildCommand()}catch(t){return e(t)}const s=r.dbName||r.authdb||t.databaseName;if(this.hasAspect(n.WRITE_OPERATION)){if(r.writeConcern&&(!r.session||!r.session.inTransaction())){o.writeConcern=r.writeConcern}}if(t.s.logger.isDebug()){const e=u(o);t.s.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:o)} against ${s}.$cmd with options [${JSON.stringify(i(h,r))}]`)}const c=this.namespace!=null?this.namespace:new l(s,"$cmd");t.s.topology.command(c,o,r,((t,n)=>{if(t)return a(e,t);if(r.full)return a(e,null,n);a(e,null,n.result)}))}}e.exports=CommandOperation},1189:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(3994).ReadPreference;const i=r(7289);const a=r(2481);const A=r(1178).maxWireVersion;const c=r(1371).decorateWithExplain;const l=r(5474).commandSupportsReadConcern;const u=r(3111).MongoError;const h=r(7703).extractCommand;const d=5;class CommandOperationV2 extends o{constructor(e,t,r){super(t);this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(n.NO_INHERIT_OPTIONS)?undefined:e;this.readPreference=this.hasAspect(n.WRITE_OPERATION)?s.primary:s.resolve(o,this.options);this.readConcern=resolveReadConcern(o,this.options);this.writeConcern=resolveWriteConcern(o,this.options);if(r&&typeof r.fullResponse==="boolean"){this.fullResponse=true}this.options.readPreference=this.readPreference;if(e.s.logger){this.logger=e.s.logger}else if(e.s.db&&e.s.db.logger){this.logger=e.s.db.logger}}executeCommand(e,t,r){this.server=e;const o=this.options;const s=A(e);const i=this.session&&this.session.inTransaction();if(this.readConcern&&l(t)&&!i){Object.assign(t,{readConcern:this.readConcern})}if(o.collation&&s=d){if(this.writeConcern&&this.hasAspect(n.WRITE_OPERATION)){Object.assign(t,{writeConcern:this.writeConcern})}if(o.collation&&typeof o.collation==="object"){Object.assign(t,{collation:o.collation})}}if(typeof o.maxTimeMS==="number"){t.maxTimeMS=o.maxTimeMS}if(typeof o.comment==="string"){t.comment=o.comment}if(this.hasAspect(n.EXPLAINABLE)&&this.explain){if(s<6&&t.aggregate){t.explain=true}else{t=c(t,this.explain)}}if(this.logger&&this.logger.isDebug()){const e=h(t);this.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:t)} against ${this.ns}`)}e.command(this.ns.toString(),t,this.options,((e,t)=>{if(e){r(e,null);return}if(this.fullResponse){r(null,t);return}r(null,t.result)}))}}function resolveWriteConcern(e,t){return a.fromOptions(t)||e&&e.writeConcern}function resolveReadConcern(e,t){return i.fromOptions(t)||e&&e.readConcern}e.exports=CommandOperationV2},2296:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).MongoError;const u=r(3994).ReadPreference;const h=r(1371).toError;const d=r(4847).CursorState;const g=r(1178).maxWireVersion;function buildCountCommand(e,t,r){const n=r.skip;const o=r.limit;let a=r.hint;const A=r.maxTimeMS;t=t||{};const c={count:r.collectionName,query:t};if(e.s.numberOfRetries){if(e.options.hint){a=e.options.hint}else if(e.cmd.hint){a=e.cmd.hint}s(c,e,e.cmd)}else{s(c,e,r)}if(typeof n==="number")c.skip=n;if(typeof o==="number")c.limit=o;if(typeof A==="number")c.maxTimeMS=A;if(a)c.hint=a;i(c,e);return c}function findAndModify(e,t,r,i,l,h){const d={findAndModify:e.collectionName,query:t};r=A(r);if(r){d.sort=r}d.new=l.new?true:false;d.remove=l.remove?true:false;d.upsert=l.upsert?true:false;const g=l.projection||l.fields;if(g){d.fields=g}if(l.arrayFilters){d.arrayFilters=l.arrayFilters;delete l.arrayFilters}if(i&&!l.remove){d.update=i}if(l.maxTimeMS)d.maxTimeMS=l.maxTimeMS;l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions;l.checkKeys=false;let p=Object.assign({},l);p=n(p,e.s.db);p=o(p,{db:e.s.db,collection:e},l);if(p.writeConcern){d.writeConcern=p.writeConcern}if(p.bypassDocumentValidation===true){d.bypassDocumentValidation=p.bypassDocumentValidation}p.readPreference=u.primary;try{s(d,e,p)}catch(e){return h(e,null)}a(e.s.db,d,p,((e,t)=>{if(e)return c(h,e,null);return c(h,null,t)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new l("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(h(e));if(!Array.isArray(t))return c(n,null,[]);if(o)return c(n,null,t);c(n,null,processResults(t))}))}function prepareDocs(e,t,r){const n=typeof r.forceServerObjectId==="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;if(n===true){return t}return t.map((t=>{if(n!==true&&t._id==null){t._id=e.s.pkFactory.createPk()}return t}))}function nextObject(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead()){return c(t,l.create({message:"Cursor is closed",driver:true}))}if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort){try{e.cmd.sort=A(e.cmd.sort)}catch(e){return c(t,e)}}e._next(((r,n)=>{e.s.state=d.OPEN;if(r)return c(t,r);c(t,null,n)}))}function insertDocuments(e,t,r,s){if(typeof r==="function")s=r,r={};r=r||{};t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=n(i,e.s.db);i=o(i,{db:e.s.db,collection:e},r);if(i.keepGoing===true)i.ordered=false;i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions;t=prepareDocs(e,t,r);e.s.topology.insert(e.s.namespace,t,i,((e,r)=>{if(s==null)return;if(e)return c(s,e);if(r==null)return c(s,null,null);if(r.result.code)return c(s,h(r.result));if(r.result.writeErrors)return c(s,h(r.result.writeErrors[0]));r.ops=t;c(s,null,r)}))}function removeDocuments(e,t,r,i){if(typeof r==="function"){i=r,r={}}else if(typeof t==="function"){i=t;r={};t={}}r=r||{};let a=Object.assign({},r);a=n(a,e.s.db);a=o(a,{db:e.s.db,collection:e},r);if(t==null)t={};const A={q:t,limit:0};if(r.single){A.limit=1}else if(a.retryWrites){a.retryWrites=false}if(r.hint){A.hint=r.hint}try{s(a,e,r)}catch(e){return i(e,null)}if(r.explain!==undefined&&g(e.s.topology)<3){return i?i(new l(`server does not support explain on remove`)):undefined}e.s.topology.remove(e.s.namespace,[A],a,((e,t)=>{if(i==null)return;if(e)return c(i,e,null);if(t==null)return c(i,null,null);if(t.result.code)return c(i,h(t.result));if(t.result.writeErrors){return c(i,h(t.result.writeErrors[0]))}c(i,null,t)}))}function updateDocuments(e,t,r,i,a){if("function"===typeof i)a=i,i=null;if(i==null)i={};if(!("function"===typeof a))a=null;if(t==null||typeof t!=="object")return a(h("selector must be a valid JavaScript object"));if(r==null||typeof r!=="object")return a(h("document must be a valid JavaScript object"));let A=Object.assign({},i);A=n(A,e.s.db);A=o(A,{db:e.s.db,collection:e},i);A.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const u={q:t,u:r};u.upsert=i.upsert!==void 0?!!i.upsert:false;u.multi=i.multi!==void 0?!!i.multi:false;if(i.hint){u.hint=i.hint}if(A.arrayFilters){u.arrayFilters=A.arrayFilters;delete A.arrayFilters}if(A.retryWrites&&u.multi){A.retryWrites=false}try{s(A,e,i)}catch(e){return a(e,null)}if(i.explain!==undefined&&g(e.s.topology)<3){return a?a(new l(`server does not support explain on update`)):undefined}e.s.topology.update(e.s.namespace,[u],A,((e,t)=>{if(a==null)return;if(e)return c(a,e,null);if(t==null)return c(a,null,null);if(t.result.code)return c(a,h(t.result));if(t.result.writeErrors)return c(a,h(t.result.writeErrors[0]));c(a,null,t)}))}e.exports={buildCountCommand:buildCountCommand,findAndModify:findAndModify,indexInformation:indexInformation,nextObject:nextObject,prepareDocs:prepareDocs,insertDocuments:insertDocuments,removeDocuments:removeDocuments,updateDocuments:updateDocuments}},5210:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(3994).Logger;const s=r(3994).MongoCredentials;const i=r(3994).MongoError;const a=r(2048);const A=r(2632);const c=r(3994).parseConnectionString;const l=r(7289);const u=r(3994).ReadPreference;const h=r(382);const d=r(8421);const g=r(3994).Sessions.ServerSessionPool;const p=r(1371).emitDeprecationWarning;const E=r(1371).emitWarningOnce;const m=r(7147);const C=r(2481);const I=r(897).CMAP_EVENT_NAMES;let y;function loadClient(){if(!y){y=r(1545)}return y}const B=n(r(8729),"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.");const Q={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"};const b=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"];const w=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]);const S=["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","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","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"];const v=["native_parser"];const R=["server","replset","replSet","mongos","db"];function validOptions(e){const t=S.concat(R);for(const r in e){if(v.indexOf(r)!==-1){continue}if(t.indexOf(r)===-1){if(e.validateOptions){return new i(`option ${r} is not supported`)}else{E(`the options [${r}] is not supported`)}}if(R.indexOf(r)!==-1){E(`the server/replset/mongos/db options are deprecated, `+`all their options are supported at the top level of the options object [${S}]`)}}}const k=S.reduce(((e,t)=>{e[t.toLowerCase()]=t;return e}),{});function addListeners(e,t){t.on("authenticated",createListener(e,"authenticated"));t.on("error",createListener(e,"error"));t.on("timeout",createListener(e,"timeout"));t.on("close",createListener(e,"close"));t.on("parseError",createListener(e,"parseError"));t.once("open",createListener(e,"open"));t.once("fullsetup",createListener(e,"fullsetup"));t.once("all",createListener(e,"all"));t.on("reconnect",createListener(e,"reconnect"))}function assignTopology(e,t){e.topology=t;if(!(t instanceof A)){t.s.sessionPool=new g(t.s.coreTopology)}}function clearAllEvents(e){b.forEach((t=>e.removeAllListeners(t)))}function collectEvents(e,t){let r=loadClient();const n=[];if(e instanceof r){b.forEach((r=>{t.on(r,((t,o)=>{if(r==="open"){n.push({event:r,object1:e})}else{n.push({event:r,object1:t,object2:o})}}))}))}return n}function resolveTLSOptions(e){if(e.tls==null){return}["sslCA","sslKey","sslCert"].forEach((t=>{if(e[t]){e[t]=m.readFileSync(e[t])}}))}function connect(e,t,r,n){r=Object.assign({},r);if(n==null){throw new Error("no callback function provided")}let s=false;const A=o("MongoClient",r);if(t instanceof d||t instanceof h||t instanceof a){return connectWithUrl(e,t,r,connectCallback)}const l=r.useNewUrlParser!==false;const g=l?c:B;const p=l?transformUrlOptions:legacyTransformUrlOptions;g(t,r,((t,o)=>{if(t)return n(t);const i=p(o);const a=createUnifiedOptions(i,r);if(a.socketTimeoutMS==null)a.socketTimeoutMS=0;if(a.connectTimeoutMS==null)a.connectTimeoutMS=1e4;if(a.retryWrites==null)a.retryWrites=true;if(a.useRecoveryToken==null)a.useRecoveryToken=true;if(a.readPreference==null)a.readPreference="primary";if(a.db_options&&a.db_options.auth){delete a.db_options.auth}resolveTLSOptions(a);e.s.options=a;e.s.readPreference=u.fromOptions(a);e.s.writeConcern=C.fromOptions(a);if(i.servers.length===0){return n(new Error("connection string must contain at least one seed host"))}if(a.auth&&!a.credentials){try{s=true;a.credentials=generateCredentials(e,a.auth.user,a.auth.password,a)}catch(t){return n(t)}}if(a.useUnifiedTopology){return createTopology(e,"unified",a,connectCallback)}E("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.");if(a.replicaSet||a.rs_name){return createTopology(e,"replicaset",a,connectCallback)}else if(i.servers.length>1){return createTopology(e,"mongos",a,connectCallback)}else{return createServer(e,a,connectCallback)}}));function connectCallback(t,r){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&&t.message==="no mongos proxies found in seed list"){if(A.isWarn()){A.warn(o)}return n(new i(o))}if(s){e.emit("authenticated",null,true)}n(t,r)}}function connectWithUrl(e,t,r,n){assignTopology(e,t);addListeners(e,t);relayEvents(e,t);let o=Object.assign({},r);if(typeof r.readPreference==="string"||typeof r.read_preference==="string"){o.readPreference=new u(r.readPreference||r.read_preference)}const s=o.user||o.password||o.authMechanism;if(s&&!o.credentials){try{o.credentials=generateCredentials(e,o.user,o.password,o)}catch(e){return n(e,t)}}return t.connect(o,n)}function createListener(e,t){const r=new Set(["all","fullsetup","open","reconnect"]);return(n,o)=>{if(r.has(t)){return e.emit(t,e)}e.emit(t,n,o)}}function createServer(e,t,r){t.promiseLibrary=e.s.promiseLibrary;const n=translateOptions(t);const o=n[0];const s=collectEvents(e,o);o.connect(t,((n,i)=>{if(n){o.close(true);return r(n)}clearAllEvents(o);relayEvents(e,o);addListeners(e,o);const a=i.lastIsMaster();assignTopology(e,i);if(a&&a.msg==="isdbgrid"){i.close();return createTopology(e,"mongos",t,r)}replayEvents(e,s);r(n,i)}))}const D=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function registerDeprecatedEventNotifiers(e){e.on("newListener",(e=>{if(D.has(e)){p(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}))}function createTopology(e,t,n,o){n.promiseLibrary=e.s.promiseLibrary;const s={};if(t==="unified")s.createServers=false;const i=translateOptions(n,s);if(n.autoEncryption!=null){const t=r(3012).Encrypter;n.encrypter=new t(e,n);n.autoEncrypter=n.encrypter.autoEncrypter}let c;if(t==="mongos"){c=new a(i,n)}else if(t==="replicaset"){c=new h(i,n)}else if(t==="unified"){c=new A(n.servers,n);registerDeprecatedEventNotifiers(e)}addListeners(e,c);relayEvents(e,c);assignTopology(e,c);if(n.autoEncrypter){n.autoEncrypter.init((e=>{if(e){o(e);return}c.connect(n,(e=>{if(e){c.close(true);o(e);return}n.encrypter.connectInternalClient((e=>{if(e)return o(e);o(undefined,c)}))}))}));return}c.connect(n,(e=>{if(e){c.close(true);return o(e)}o(undefined,c);return}))}function createUnifiedOptions(e,t){const r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"];const n=["readconcern","compression","autoencryption"];const o=["w","wtimeout","j","journal","fsync","writeconcern"];for(const s in t){if(o.indexOf(s.toLowerCase())!==-1){continue}else if(n.indexOf(s.toLowerCase())!==-1){e[s]=t[s]}else if(r.indexOf(s.toLowerCase())!==-1){e=mergeOptions(e,t[s],false)}else{if(t[s]&&typeof t[s]==="object"&&!Buffer.isBuffer(t[s])&&!Array.isArray(t[s])){e=mergeOptions(e,t[s],true)}else{e[s]=t[s]}}}const s=C.fromOptions(t);if(s){e.writeConcern=Object.assign({},e.writeConcern,s)}return e}function generateCredentials(e,t,r,n){n=Object.assign({},n);const o=n.authSource||n.authdb||n.dbName;const a=n.authMechanism||"DEFAULT";const A=a.toUpperCase();const c=n.authMechanismProperties;if(!w.has(A)){throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:true})}return new s({mechanism:Q[A],mechanismProperties:c,source:o,username:t,password:r})}function legacyTransformUrlOptions(e){return mergeOptions(createUnifiedOptions({},e),e,false)}function mergeOptions(e,t,r){for(const n in t){if(t[n]&&typeof t[n]==="object"&&r){e=mergeOptions(e,t[n],r)}else{e[n]=t[n]}}return e}function relayEvents(e,t){const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(I);r.forEach((r=>{t.on(r,((t,n)=>{e.emit(r,t,n)}))}))}function replayEvents(e,t){for(let r=0;rt.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e)))}e.exports={validOptions:validOptions,connect:connect}},7885:(e,t,r)=>{"use strict";const n=r(2296).buildCountCommand;const o=r(1018).OperationBase;class CountOperation extends o{constructor(e,t,r){super(r);this.cursor=e;this.applySkipLimit=t}execute(e){const t=this.cursor;const r=this.applySkipLimit;const o=this.options;if(r){if(typeof t.cursorSkip()==="number")o.skip=t.cursorSkip();if(typeof t.cursorLimit()==="number")o.limit=t.cursorLimit()}if(o.readPreference){t.setReadPreference(o.readPreference)}if(typeof o.maxTimeMS!=="number"&&t.cmd&&typeof t.cmd.maxTimeMS==="number"){o.maxTimeMS=t.cmd.maxTimeMS}let s={};s.skip=o.skip;s.limit=o.limit;s.hint=o.hint;s.maxTimeMS=o.maxTimeMS;s.collectionName=t.namespace.collection;let i;try{i=n(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology;t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,((t,r)=>{e(t,r?r.result.n:null)}))}}e.exports=CountOperation},5131:(e,t,r)=>{"use strict";const n=r(1554);class CountDocumentsOperation extends n{constructor(e,t,r){const n=[{$match:t}];if(typeof r.skip==="number"){n.push({$skip:r.skip})}if(typeof r.limit==="number"){n.push({$limit:r.limit})}n.push({$group:{_id:1,n:{$sum:1}}});super(e,n,r)}execute(e,t){super.execute(e,((e,r)=>{if(e){t(e,null);return}const n=r.result;if(n.cursor==null||n.cursor.firstBatch==null){t(null,0);return}const o=n.cursor.firstBatch;t(null,o.length?o[0].n:0)}))}}e.exports=CountDocumentsOperation},5561:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(8275).loadCollection;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class CreateCollectionOperation extends s{constructor(e,t,r){super(e,r);this.name=t}_buildCommand(){const e=this.name;const t=this.options;const r={create:e};for(let e in t){if(t[e]!=null&&typeof t[e]!=="function"&&!l.has(e)){r[e]=t[e]}}return r}execute(e){const t=this.db;const r=this.name;const n=this.options;const o=a();let s=Object.assign({nameOnly:true,strict:false},n);s=i(s,{db:t},s);function done(s){if(s){return e(s)}try{e(null,new o(t,t.s.topology,t.databaseName,r,t.s.pkFactory,n))}catch(s){e(s)}}const l=s.strict;if(l){t.listCollections({name:r},s).setReadPreference(c.PRIMARY).toArray(((t,n)=>{if(t){return e(t)}if(n.length>0){return e(new A(`Collection ${r} already exists. Currently in strict mode.`))}super.execute(done)}));return}super.execute(done)}}o(CreateCollectionOperation,n.WRITE_OPERATION);e.exports=CreateCollectionOperation},6394:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(3994).MongoError;const a=r(1371).parseIndexOptions;const A=r(1178).maxWireVersion;const c=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class CreateIndexesOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=t;if(!Array.isArray(r)||Array.isArray(r[0])){this.onlyReturnNameOfCreatedIndex=true;const e=a(r);const t=typeof n.name==="string"?n.name:e.name;const o={name:t,key:e.fieldHash};for(let e in n){if(c.has(e)){o[e]=n[e]}}this.indexes=[o];return}this.indexes=r}execute(e,t){const r=this.options;const n=this.indexes;const o=A(e);for(let r=0;r{if(e){t(e);return}t(null,this.onlyReturnNameOfCreatedIndex?n[0].name:r)}))}}o(CreateIndexesOperation,[n.WRITE_OPERATION,n.EXECUTE_WITH_SELECTION]);e.exports=CreateIndexesOperation},3554:(e,t,r)=>{"use strict";const n=r(6716).buildCountCommand;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=Array.prototype.push;const a=r(4847).CursorState;function count(e,t,r,o){if(t){if(typeof e.cursorSkip()==="number")r.skip=e.cursorSkip();if(typeof e.cursorLimit()==="number")r.limit=e.cursorLimit()}if(r.readPreference){e.setReadPreference(r.readPreference)}if(typeof r.maxTimeMS!=="number"&&e.cmd&&typeof e.cmd.maxTimeMS==="number"){r.maxTimeMS=e.cmd.maxTimeMS}let s={};s.skip=r.skip;s.limit=r.limit;s.hint=r.hint;s.maxTimeMS=r.maxTimeMS;s.collectionName=e.namespace.collection;let i;try{i=n(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology;e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,((e,t)=>{o(e,t?t.result.n:null)}))}function each(e,t){if(!t)throw s.create({message:"callback is mandatory",driver:true});if(e.isNotified())return;if(e.s.state===a.CLOSED||e.isDead()){return o(t,s.create({message:"Cursor is closed",driver:true}))}if(e.s.state===a.INIT){e.s.state=a.OPEN}let r=null;if(e.bufferedCount()>0){while(r=loop(e,t))r(e,t);each(e,t)}else{e.next(((r,n)=>{if(r)return o(t,r);if(n==null){return e.close({skipKillCursors:true},(()=>o(t,null,null)))}if(o(t,null,n)===false)return;each(e,t)}))}}function loop(e,t){if(e.bufferedCount()===0)return;e._next(t);return loop}function toArray(e,t){const r=[];e.rewind();e.s.state=a.INIT;const fetchDocs=()=>{e._next(((n,s)=>{if(n){return o(t,n)}if(s==null){return e.close({skipKillCursors:true},(()=>o(t,null,r)))}r.push(s);if(e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());if(e.s.transforms&&typeof e.s.transforms.doc==="function"){t=t.map(e.s.transforms.doc)}i.apply(r,t)}fetchDocs()}))};fetchDocs()}e.exports={count:count,each:each,toArray:toArray}},2226:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1371).applyWriteConcern;const s=r(3994).BSON.Code;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(1371).parseIndexOptions;const l=r(3994).ReadPreference;const u=r(1371).toError;const h=r(7703).extractCommand;const d=r(147);const g=r(1371).MongoDBNamespace;const p=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function createIndex(e,t,r,s,i){let c=Object.assign({},{readPreference:l.PRIMARY},s);c=o(c,{db:e},s);if(c.writeConcern&&typeof i!=="function"){throw A.create({message:"Cannot use a writeConcern without a provided callback",driver:true})}if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new A("topology was destroyed"));createIndexUsingCreateIndexes(e,t,r,c,((o,l)=>{if(o==null)return a(i,o,l);if(o.code===n.CannotCreateIndex||o.code===n.DuplicateKey||o.code===n.IndexOptionsConflict||o.code===n.IndexKeySpecsConflict||o.code===n.InterruptedAtShutdown||o.code===n.InvalidIndexSpecificationOption){return a(i,o,l)}const u=createCreateIndexCommand(e,t,r,s);c.checkKeys=false;e.s.topology.insert(e.s.namespace.withCollection(d.SYSTEM_INDEX_COLLECTION),u,c,((e,t)=>{if(i==null)return;if(e)return a(i,e);if(t==null)return a(i,null,null);if(t.result.writeErrors)return a(i,A.create(t.result.writeErrors[0]),null);a(i,null,u.name)}))}))}function createListener(e,t,r){function listener(n){if(r.listeners(t).length>0){r.emit(t,n,e);for(let r=0;r{if(o!=null&&o.code!==n.NamespaceNotFound){return a(i,o,null)}if(A==null||!A[h]){createIndex(e,t,r,s,i)}else{if(typeof i==="function")return a(i,null,h)}}))}function evaluate(e,t,r,n,o){let i=t;let c=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return o(new A("topology was destroyed"));if(!(i&&i._bsontype==="Code"))i=new s(i);if(r!=null&&!Array.isArray(r)&&typeof r!=="function"){c=[r]}else if(r!=null&&Array.isArray(r)&&typeof r!=="function"){c=r}let u={$eval:i,args:c};if(n["nolock"]){u["nolock"]=n["nolock"]}n.readPreference=new l(l.PRIMARY);executeCommand(e,u,n,((e,t)=>{if(e)return a(o,e,null);if(t&&t.ok===1)return a(o,null,t.retval);if(t)return a(o,A.create({message:`eval failed: ${t.errmsg}`,driver:true}),null);a(o,e,t)}))}function executeCommand(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));const o=r.dbName||r.authdb||e.databaseName;r.readPreference=l.resolve(e,r);if(e.s.logger.isDebug()){const n=h(t);e.s.logger.debug(`executing command ${JSON.stringify(n.shouldRedact?`${n.name} details REDACTED`:t)} against ${o}.$cmd with options [${JSON.stringify(i(p,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,((e,t)=>{if(e)return a(n,e);if(r.full)return a(n,null,t);a(n,null,t.result)}))}function executeDbAdminCommand(e,t,r,n){const o=new g("admin","$cmd");e.s.topology.command(o,t,r,((t,r)=>{if(e.serverConfig&&e.serverConfig.isDestroyed()){return n(new A("topology was destroyed"))}if(t)return a(n,t);a(n,null,r.result)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(u(e));if(!Array.isArray(t))return a(n,null,[]);if(o)return a(n,null,t);a(n,null,processResults(t))}))}function profilingInfo(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(e){return r(e,null)}}function validateDatabaseName(e){if(typeof e!=="string")throw A.create({message:"database name must be a string",driver:true});if(e.length===0)throw A.create({message:"database name cannot be the empty string",driver:true});if(e==="$external")return;const t=[" ",".","$","/","\\"];for(let r=0;r{if(e)return a(s,e,null);if(t.ok===0)return a(s,u(t),null);a(s,null,h)}))}e.exports={createListener:createListener,createIndex:createIndex,ensureIndex:ensureIndex,evaluate:evaluate,executeCommand:executeCommand,executeDbAdminCommand:executeDbAdminCommand,indexInformation:indexInformation,profilingInfo:profilingInfo,validateDatabaseName:validateDatabaseName}},323:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=false;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteManyOperation,[s.EXPLAINABLE]);e.exports=DeleteManyOperation},6352:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteOneOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=true;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteOneOperation,[s.EXPLAINABLE]);e.exports=DeleteOneOperation},6469:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(1178).maxWireVersion;const c=r(9386).MongoError;class DistinctOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=e;this.key=t;this.query=r}execute(e,t){const r=this.collection;const n=this.key;const o=this.query;const s=this.options;const l={distinct:r.collectionName,key:n,query:o};if(typeof s.maxTimeMS==="number"){l.maxTimeMS=s.maxTimeMS}a(l,r,s);try{i(l,r,s)}catch(e){return t(e,null)}if(this.explain&&A(e)<4){t(new c(`server does not support explain on distinct`));return}super.executeCommand(e,l,((e,r)=>{if(e){t(e);return}t(null,this.options.full||this.explain?r:r.values)}))}}o(DistinctOperation,[n.READ_OPERATION,n.RETRYABLE,n.EXECUTE_WITH_SELECTION,n.EXPLAINABLE]);e.exports=DistinctOperation},2360:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;class DropOperation extends o{constructor(e,t){const r=Object.assign({},t,e.s.options);if(t.session){r.session=t.session}super(e,r)}execute(e){super.execute(((t,r)=>{if(t)return i(e,t);if(r.ok)return i(e,null,true);i(e,null,false)}))}}s(DropOperation,n.WRITE_OPERATION);class DropCollectionOperation extends DropOperation{constructor(e,t,r){super(e,r);this.name=t;this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}}class DropDatabaseOperation extends DropOperation{_buildCommand(){return{dropDatabase:1}}}e.exports={DropOperation:DropOperation,DropCollectionOperation:DropCollectionOperation,DropDatabaseOperation:DropDatabaseOperation}},3560:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(1371).handleCallback;class DropIndexOperation extends s{constructor(e,t,r){super(e.s.db,r,e);this.collection=e;this.indexName=t}_buildCommand(){const e=this.collection;const t=this.indexName;const r=this.options;let n={dropIndexes:e.collectionName,index:t};n=i(n,{db:e.s.db,collection:e},r);return n}execute(e){super.execute(((t,r)=>{if(typeof e!=="function")return;if(t)return a(e,t,null);a(e,null,r)}))}}o(DropIndexOperation,n.WRITE_OPERATION);e.exports=DropIndexOperation},5328:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(3560);const i=r(1371).handleCallback;class DropIndexesOperation extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute((t=>{if(t)return i(e,t,false);i(e,null,true)}))}}o(DropIndexesOperation,n.WRITE_OPERATION);e.exports=DropIndexesOperation},4451:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1189);const a=r(1178).maxWireVersion;const A=r(5131);class EstimatedDocumentCountOperation extends i{constructor(e,t){super(e,t);this.collection=e;this.collectionName=e.s.namespace.collection}execute(e,t){if(a(e)<12){return this.executeLegacy(e,t)}if(this.options.query){const r=new A(this.collection,this.options.query,this.options);return r.execute(e,t)}const r=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}];const o={aggregate:this.collectionName,pipeline:r,cursor:{}};if(typeof this.options.maxTimeMS==="number"){o.maxTimeMS=this.options.maxTimeMS}super.executeCommand(e,o,((e,r)=>{if(e&&e.code!==n.NamespaceNotFound){t(e);return}t(undefined,r&&r.cursor&&r.cursor.firstBatch&&r.cursor.firstBatch[0].n||0)}))}executeLegacy(e,t){const r={count:this.collectionName};const n=this.options;if(n.query){r.query=n.query}if(n.hint){r.hint=n.hint}if(typeof n.maxTimeMS==="number"){r.maxTimeMS=n.maxTimeMS}if(typeof n.skip==="number"){r.skip=n.skip}if(typeof n.limit==="number"){r.limit=n.limit}super.executeCommand(e,r,((e,r)=>{if(e){t(e);return}t(null,r.n)}))}}s(EstimatedDocumentCountOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=EstimatedDocumentCountOperation},1681:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=r(1371).MongoDBNamespace;class ExecuteDbAdminCommandOperation extends n{constructor(e,t,r){super(r);this.db=e;this.selector=t}execute(e){const t=this.db;const r=this.selector;const n=this.options;const a=new i("admin","$cmd");t.s.topology.command(a,r,n,((r,n)=>{if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new s("topology was destroyed"))}if(r)return o(e,r);o(e,null,n.result)}))}}e.exports=ExecuteDbAdminCommandOperation},2548:(e,t,r)=>{"use strict";const n=r(1371).maybePromise;const o=r(3111).MongoError;const s=r(1018).Aspect;const i=r(1018).OperationBase;const a=r(4485);const A=r(3111).isRetryableError;const c=r(1178).maxWireVersion;const l=r(1178).isUnifiedTopology;function executeOperation(e,t,r){if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!(t instanceof i)){throw new TypeError("This method requires a valid operation instance")}return n(e,r,(r=>{if(l(e)&&e.shouldCheckForSessionSupport()){return selectServerForSessionSupport(e,t,r)}let n,i;if(e.hasSessionSupport()){if(t.session==null){i=Symbol();n=e.startSession({owner:i});t.session=n}else if(t.session.hasEnded){return r(new o("Use of expired sessions is not permitted"))}}else if(t.session){return r(new o("Current topology does not support sessions"))}function executeCallback(e,o){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e,o)}try{if(t.hasAspect(s.EXECUTE_WITH_SELECTION)){executeWithServerSelection(e,t,executeCallback)}else{t.execute(executeCallback)}}catch(e){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e)}}))}function supportsRetryableReads(e){return c(e)>=6}function executeWithServerSelection(e,t,r){const n=t.readPreference||a.primary;const i=t.session&&t.session.inTransaction();if(i&&!n.equals(a.primary)){r(new o(`Read preference in a transaction must be primary, not: ${n.mode}`));return}const c={readPreference:n,session:t.session};function callbackWithRetry(n,o){if(n==null){return r(null,o)}if(!A(n)){return r(n)}e.selectServer(c,((e,n)=>{if(e||!supportsRetryableReads(n)){r(e,null);return}t.execute(n,r)}))}e.selectServer(c,((n,o)=>{if(n){r(n,null);return}const a=e.s.options.retryReads!==false&&t.session&&!i&&supportsRetryableReads(o)&&t.canRetryRead;if(t.hasAspect(s.RETRYABLE)&&a){t.execute(o,callbackWithRetry);return}t.execute(o,r)}))}function selectServerForSessionSupport(e,t,r){e.selectServer(a.primaryPreferred,(n=>{if(n){return r(n)}executeOperation(e,t,r)}))}e.exports=executeOperation},9961:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(3994).ReadPreference;const a=r(1178).maxWireVersion;const A=r(3111).MongoError;class FindOperation extends n{constructor(e,t,r,n){super(n);this.ns=t;this.cmd=r;this.readPreference=i.resolve(e,this.options)}execute(e,t){this.server=e;this.readPreference=i.resolve(this,this.options);if(typeof this.cmd.allowDiskUse!=="undefined"&&a(e)<4){t(new A("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}if(this.explain){this.options.explain=this.explain.verbosity}const r=this.cursorState||{};e.query(this.ns.toString(),this.cmd,r,this.options,t)}}s(FindOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]);e.exports=FindOperation},711:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyRetryableWrites;const s=r(1371).applyWriteConcern;const i=r(1371).decorateWithCollation;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1178).maxWireVersion;const h=r(9386).MongoError;const d=r(1018).Aspect;const g=r(1018).defineAspects;const p=r(1371).decorateWithExplain;class FindAndModifyOperation extends n{constructor(e,t,r,n,o){super(o);this.collection=e;this.query=t;this.sort=r;this.doc=n}execute(e){const t=this.collection;const r=this.query;const n=A(this.sort);const d=this.doc;let g=this.options;let E={findAndModify:t.collectionName,query:r};if(n){E.sort=n}E.new=g.new?true:false;E.remove=g.remove?true:false;E.upsert=g.upsert?true:false;const m=g.projection||g.fields;if(m){E.fields=m}if(g.arrayFilters){E.arrayFilters=g.arrayFilters}if(d&&!g.remove){E.update=d}if(g.maxTimeMS)E.maxTimeMS=g.maxTimeMS;g.serializeFunctions=g.serializeFunctions||t.s.serializeFunctions;g.checkKeys=false;g=o(g,t.s.db);g=s(g,{db:t.s.db,collection:t},g);if(g.writeConcern){E.writeConcern=g.writeConcern}if(g.bypassDocumentValidation===true){E.bypassDocumentValidation=g.bypassDocumentValidation}g.readPreference=l.primary;try{i(E,t,g)}catch(t){return e(t,null)}if(g.hint){const r=g.writeConcern&&g.writeConcern.w===0;if(r||u(t.s.topology)<8){e(new h("The current topology does not support a hint on findAndModify commands"));return}E.hint=g.hint}if(this.explain){if(u(t.s.topology)<4){e(new h(`server does not support explain on findAndModify`));return}E=p(E,this.explain)}a(t.s.db,E,g,((t,r)=>{if(t)return c(e,t,null);return c(e,null,r)}))}}g(FindAndModifyOperation,[d.EXPLAINABLE]);e.exports=FindAndModifyOperation},4497:(e,t,r)=>{"use strict";const n=r(1371).handleCallback;const o=r(1018).OperationBase;const s=r(1371).toError;const i=r(1018).Aspect;const a=r(1018).defineAspects;class FindOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.query=t}execute(e){const t=this.collection;const r=this.query;const o=this.options;try{const i=t.find(r,o).limit(-1).batchSize(1);i.next(((t,r)=>{if(t!=null)return n(e,s(t),null);n(e,null,r)}))}catch(t){e(t)}}}a(FindOneOperation,[i.EXPLAINABLE]);e.exports=FindOneOperation},5841:(e,t,r)=>{"use strict";const n=r(711);class FindOneAndDeleteOperation extends n{constructor(e,t,r){const n=Object.assign({},r);n.fields=r.projection;n.remove=true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}super(e,t,n.sort,null,n)}}e.exports=FindOneAndDeleteOperation},4316:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndReplaceOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Replacement parameter must be an object")}if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndReplaceOperation},1925:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndUpdateOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Update parameter must be an object")}if(!s(r)){throw new TypeError("Update document requires atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndUpdateOperation},8169:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1018).OperationBase;const i=r(1371).decorateCommand;const a=r(1371).decorateWithReadConcern;const A=r(2226).executeCommand;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1371).toError;class GeoHaystackSearchOperation extends s{constructor(e,t,r,n){super(n);this.collection=e;this.x=t;this.y=r}execute(e){const t=this.collection;const r=this.x;const n=this.y;let o=this.options;let s={geoSearch:t.collectionName,near:[r,n]};s=i(s,o,["readPreference","session"]);o=Object.assign({},o);o.readPreference=l.resolve(t,o);a(s,t,o);A(t.s.db,s,o,((t,r)=>{if(t)return c(e,t);if(r.err||r.errmsg)c(e,u(r));c(e,null,r)}))}}o(GeoHaystackSearchOperation,n.READ_OPERATION);e.exports=GeoHaystackSearchOperation},7809:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(2226).indexInformation;class IndexExistsOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.indexes=t}execute(e){const t=this.collection;const r=this.indexes;const n=this.options;s(t.s.db,t.collectionName,n,((t,n)=>{if(t!=null)return o(e,t,null);if(!Array.isArray(r))return o(e,null,n[r]!=null);for(let t=0;t{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexInformationOperation extends n{constructor(e,t,r){super(r);this.db=e;this.name=t}execute(e){const t=this.db;const r=this.name;const n=this.options;o(t,r,n,e)}}e.exports=IndexInformationOperation},4218:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexesOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;let r=this.options;r=Object.assign({},{full:true},r);o(t.s.db,t.collectionName,r,e)}}e.exports=IndexesOperation},3592:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(6976);const s=r(3994).MongoError;const i=r(2296).prepareDocs;class InsertManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.docs=t}execute(e){const t=this.collection;let r=this.docs;const n=this.options;if(!Array.isArray(r)){return e(s.create({message:"docs parameter must be an array of documents",driver:true}))}n["serializeFunctions"]=n["serializeFunctions"]||t.s.serializeFunctions;r=i(t,r,n);const a=r.map((e=>({insertOne:{document:e}})));const A=new o(t,a,n);A.execute(((t,n)=>{if(t)return e(t,null);e(null,mapInsertManyResults(r,n))}))}}function mapInsertManyResults(e,t){const r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};if(t.getLastOp()){r.result.opTime=t.getLastOp()}return r}e.exports=InsertManyOperation},9915:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(1018).OperationBase;const s=r(2296).insertDocuments;class InsertOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.doc=t}execute(e){const t=this.collection;const r=this.doc;const o=this.options;if(Array.isArray(r)){return e(n.create({message:"doc parameter must be an object",driver:true}))}s(t,[r],o,((t,n)=>{if(e==null)return;if(t&&e)return e(t);if(n==null)return e(null,{result:{ok:1}});n.insertedCount=n.result.n;n.insertedId=r._id;if(e)e(null,n)}))}}e.exports=InsertOneOperation},4956:(e,t,r)=>{"use strict";const n=r(43);const o=r(1371).handleCallback;class IsCappedOperation extends n{constructor(e,t){super(e,t)}execute(e){super.execute(((t,r)=>{if(t)return o(e,t);o(e,null,!!(r&&r.capped))}))}}e.exports=IsCappedOperation},840:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=r(147);const A=3;function listCollectionsTransforms(e){const t=`${e}.`;return{doc:e=>{const r=e.name.indexOf(t);if(e.name&&r===0){e.name=e.name.substr(r+t.length)}return e}}}class ListCollectionsOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.db=e;this.filter=t;this.nameOnly=!!this.options.nameOnly;if(typeof this.options.batchSize==="number"){this.batchSize=this.options.batchSize}}execute(e,t){if(i(e){if(r&&r.message&&r.message.documents&&Array.isArray(r.message.documents)){r.message.documents=r.message.documents.map(o.doc)}t(e,r)}));return}const r={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,r,t)}}s(ListCollectionsOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListCollectionsOperation},9929:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1371).MongoDBNamespace;class ListDatabasesOperation extends n{constructor(e,t){super(e,t);this.ns=new i("admin","$cmd")}execute(e,t){const r={listDatabases:1};if(this.options.nameOnly){r.nameOnly=Number(r.nameOnly)}if(this.options.filter){r.filter=this.options.filter}if(typeof this.options.authorizedDatabases==="boolean"){r.authorizedDatabases=this.options.authorizedDatabases}super.executeCommand(e,r,t)}}s(ListDatabasesOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListDatabasesOperation},28:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=3;class ListIndexesOperation extends n{constructor(e,t){super(e,t,{fullResponse:true});this.collectionNamespace=e.s.namespace}execute(e,t){const r=i(e);if(r{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).handleCallback;const c=r(1371).isObject;const l=r(8275).loadDb;const u=r(1018).OperationBase;const h=r(3994).ReadPreference;const d=r(1371).toError;const g=r(1018).Aspect;const p=r(1018).defineAspects;const E=r(1371).decorateWithExplain;const m=r(1178).maxWireVersion;const C=r(9386).MongoError;const I=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class MapReduceOperation extends u{constructor(e,t,r,n){super(n);this.collection=e;this.map=t;this.reduce=r}execute(e){const t=this.collection;const r=this.map;const o=this.reduce;let c=this.options;let u={mapReduce:t.collectionName,map:r,reduce:o};for(let e in c){if("scope"===e){u[e]=processScope(c[e])}else{if(I.indexOf(e)===-1){u[e]=c[e]}}}c=Object.assign({},c);c.readPreference=h.resolve(t,c);if(c.readPreference!==false&&c.readPreference!=="primary"&&c["out"]&&c["out"].inline!==1&&c["out"]!=="inline"){c.readPreference="primary";n(u,{db:t.s.db,collection:t},c)}else{i(u,t,c)}if(c.bypassDocumentValidation===true){u.bypassDocumentValidation=c.bypassDocumentValidation}try{s(u,t,c)}catch(t){return e(t,null)}if(this.explain){if(m(t.s.topology)<9){e(new C(`server does not support explain on mapReduce`));return}u=E(u,this.explain)}a(t.s.db,u,c,((r,n)=>{if(r)return A(e,r);if(1!==n.ok||n.err||n.errmsg){return A(e,d(n))}if(this.explain)return e(undefined,n);const o={};if(n.timeMillis)o["processtime"]=n.timeMillis;if(n.counts)o["counts"]=n.counts;if(n.timing)o["timing"]=n.timing;if(n.results){if(c["verbose"]==null||!c["verbose"]){return A(e,null,n.results)}return A(e,null,{results:n.results,stats:o})}let s=null;if(n.result!=null&&typeof n.result==="object"){const e=n.result;let r=l();s=new r(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else{s=t.s.db.collection(n.result)}if(c["verbose"]==null||!c["verbose"]){return A(e,r,s)}A(e,r,{collection:s,stats:o})}))}}function processScope(e){if(!c(e)||e._bsontype==="ObjectID"){return e}const t=Object.keys(e);let r;const n={};for(let s=t.length-1;s>=0;s--){r=t[s];if("function"===typeof e[r]){n[r]=new o(String(e[r]))}else{n[r]=processScope(e[r])}}return n}p(MapReduceOperation,[g.EXPLAINABLE]);e.exports=MapReduceOperation},1018:(e,t,r)=>{"use strict";const n=r(5293).Explain;const o=r(3111).MongoError;const s={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"),EXPLAINABLE:Symbol("EXPLAINABLE")};class OperationBase{constructor(e){this.options=Object.assign({},e);if(this.hasAspect(s.EXPLAINABLE)){this.explain=n.fromOptions(e)}else if(this.options.explain!==undefined){throw new o(`explain is not supported on this command`)}}hasAspect(e){if(this.constructor.aspects==null){return false}return 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 true}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}function defineAspects(e,t){if(!Array.isArray(t)&&!(t instanceof Set)){t=[t]}t=new Set(t);Object.defineProperty(e,"aspects",{value:t,writable:false});return t}e.exports={Aspect:s,defineAspects:defineAspects,OperationBase:OperationBase}},43:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;class OptionsOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;const r=this.options;t.s.db.listCollections({name:t.collectionName},r).toArray(((r,n)=>{if(r)return o(e,r);if(n.length===0){return o(e,s.create({message:`collection ${t.namespace} not found`,driver:true}))}o(e,r,n[0].options||null)}))}}e.exports=OptionsOperation},3969:(e,t,r)=>{"use strict";const n=r(499);class ProfilingLevelOperation extends n{constructor(e,t,r){super(e,r)}_buildCommand(){const e={profile:-1};return e}execute(e){super.execute(((t,r)=>{if(t==null&&r.ok===1){const t=r.was;if(t===0)return e(null,"off");if(t===1)return e(null,"slow_only");if(t===2)return e(null,"all");return e(new Error("Error: illegal profiling level value "+t),null)}else{t!=null?e(t,null):e(new Error("Error with profile command"),null)}}))}}e.exports=ProfilingLevelOperation},6331:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(2291).serverType;const a=r(2291).ServerType;const A=r(3994).MongoError;class ReIndexOperation extends s{constructor(e,t){super(e,t);this.collectionName=e.collectionName}execute(e,t){if(i(e)!==a.Standalone){t(new A(`reIndex can only be executed on standalone servers.`));return}super.executeCommand(e,{reIndex:this.collectionName},((e,r)=>{if(e){t(e);return}t(null,!!r.ok)}))}}o(ReIndexOperation,[n.EXECUTE_WITH_SELECTION]);e.exports=ReIndexOperation},1969:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;const a=r(2481);class RemoveUserOperation extends o{constructor(e,t,r){const n={};const o=a.fromOptions(r);if(o!=null){n.writeConcern=o}if(r.dbName){n.dbName=r.dbName}if(typeof r.maxTimeMS==="number"){n.maxTimeMS=r.maxTimeMS}super(e,n);this.username=t}_buildCommand(){const e=this.username;const t={dropUser:e};return t}execute(e){super.execute(((t,r)=>{if(t)return i(e,t,null);i(e,t,r.ok?true:false)}))}}s(RemoveUserOperation,n.WRITE_OPERATION);e.exports=RemoveUserOperation},2808:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyWriteConcern;const s=r(1371).checkCollectionName;const i=r(2226).executeDbAdminCommand;const a=r(1371).handleCallback;const A=r(8275).loadCollection;const c=r(1371).toError;class RenameOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.newName=t}execute(e){const t=this.collection;const r=this.newName;const n=this.options;let l=A();s(r);const u=t.namespace;const h=t.s.namespace.withCollection(r).toString();const d=typeof n.dropTarget==="boolean"?n.dropTarget:false;const g={renameCollection:u,to:h,dropTarget:d};o(g,{db:t.s.db,collection:t},n);i(t.s.db.admin().s.db,g,n,((n,o)=>{if(n)return a(e,n,null);if(o.errmsg)return a(e,c(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,r,t.s.pkFactory,t.s.options))}catch(n){return a(e,c(n),null)}}))}}e.exports=RenameOperation},2508:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;class ReplaceOneOperation extends n{constructor(e,t,r,n){super(n);if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}this.collection=e;this.filter=t;this.replacement=r}execute(e){const t=this.collection;const r=this.filter;const n=this.replacement;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>replaceCallback(t,r,n,e)))}}function replaceCallback(e,t,r,n){if(n==null)return;if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?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=[r];if(n)n(null,t)}e.exports=ReplaceOneOperation},1363:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).defineAspects;const s=r(1018).Aspect;class RunCommandOperation extends n{constructor(e,t,r){super(e,r);this.command=t}execute(e,t){const r=this.command;this.executeCommand(e,r,t)}}o(RunCommandOperation,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]);e.exports=RunCommandOperation},6301:(e,t,r)=>{"use strict";const n=r(499);const o=new Set(["off","slow_only","all"]);class SetProfilingLevelOperation extends n{constructor(e,t,r){let n=0;if(t==="off"){n=0}else if(t==="slow_only"){n=1}else if(t==="all"){n=2}super(e,r);this.level=t;this.profile=n}_buildCommand(){const e=this.profile;const t={profile:e};return t}execute(e){const t=this.level;if(!o.has(t)){return e(new Error("Error: illegal profiling level value "+t))}super.execute(((r,n)=>{if(r==null&&n.ok===1)return e(null,t);return r!=null?e(r,null):e(new Error("Error with profile command"),null)}))}}e.exports=SetProfilingLevelOperation},968:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;class StatsOperation extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection;const t=this.options;const r={collStats:e.collectionName};if(t["scale"]!=null){r["scale"]=t["scale"]}return r}}s(StatsOperation,n.READ_OPERATION);e.exports=StatsOperation},9350:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateManyOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=true;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateManyOperation,[i.EXPLAINABLE]);e.exports=UpdateManyOperation},9068:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateOneOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateOneOperation,[i.EXPLAINABLE]);e.exports=UpdateOneOperation},9263:(e,t,r)=>{"use strict";const n=r(499);class ValidateCollectionOperation extends n{constructor(e,t,r){let n={validate:t};const o=Object.keys(r);for(let e=0;e{if(r!=null)return e(r,null);if(n.ok===0)return e(new Error("Error with validate command"),null);if(n.result!=null&&n.result.constructor!==String)return e(new Error("Error with validation data"),null);if(n.result!=null&&n.result.match(/exception|corrupt/)!=null)return e(new Error("Error: invalid collection "+t),null);if(n.valid!=null&&!n.valid)return e(new Error("Error: invalid collection "+t),null);return e(null,n)}))}}e.exports=ValidateCollectionOperation},7289:e=>{"use strict";class ReadConcern{constructor(e){if(e!=null){this.level=e}}static fromOptions(e){if(e==null){return}if(e.readConcern){if(e.readConcern instanceof ReadConcern){return e.readConcern}return new ReadConcern(e.readConcern.level)}if(e.level){return new ReadConcern(e.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=ReadConcern},2048:(e,t,r)=>{"use strict";const n=r(8589).oF;const o=r(3994).MongoError;const s=r(3994).Mongos;const i=r(7159);const a=r(8421);const A=r(8589).yh;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"];class Mongos extends n{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var n=0;n0?t.socketOptions:t;C=l(C,I);this.s={coreTopology:new s(E,C),sCapabilities:null,debug:C.debug,storeOptions:g,clonedOptions:C,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var n=["timeout","error","close"];n.forEach((function(e){r.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.close(true);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect");r.s.store.execute()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){var e=["timeout","error","close","fullsetup"];e.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.on("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r)}));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("joined",relay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.connect(e)}}Object.defineProperty(Mongos.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=Mongos},2632:(e,t,r)=>{"use strict";const n=r(3994).Topology;const o=r(8589).ug;const s=r(7159);const i=r(1371).translateOptions;class NativeTopology extends n{constructor(e,t){t=t||{};let r=Object.assign({},{cursorFactory:s,reconnect:false,emitError:typeof t.emitError==="boolean"?t.emitError:true,maxPoolSize:typeof t.maxPoolSize==="number"?t.maxPoolSize:typeof t.poolSize==="number"?t.poolSize:10,minPoolSize:typeof t.minPoolSize==="number"?t.minPoolSize:typeof t.minSize==="number"?t.minSize:0,monitorCommands:typeof t.monitorCommands==="boolean"?t.monitorCommands:false});r=i(r,t);var n=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;r=i(r,n);r.serverApi=t.serverApi;r.useUnifiedTopology=t.useUnifiedTopology;super(e,r)}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.lastIsMaster()==null)return null;this.s.sCapabilities=new o(this.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){super.command(e.toString(),t,r,n)}insert(e,t,r,n){super.insert(e.toString(),t,r,n)}update(e,t,r,n){super.update(e.toString(),t,r,n)}remove(e,t,r,n){super.remove(e.toString(),t,r,n)}}e.exports=NativeTopology},382:(e,t,r)=>{"use strict";const n=r(8421);const o=r(7159);const s=r(3994).MongoError;const i=r(8589).oF;const a=r(8589).yh;const A=r(3994).ReplSet;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class ReplSet extends i{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var i=0;i0?t.socketOptions:t;m=l(m,C);var I=new A(E,m);I.on("reconnect",(function(){r.emit("reconnect");p.execute()}));this.s={coreTopology:I,sCapabilities:null,tag:t.tag,storeOptions:g,clonedOptions:m,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise};if(m.debug){Object.defineProperty(this,"replset",{enumerable:true,get:function(){return I}})}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));var relay=function(e){return function(t,n){r.emit(e,t,n)}};var replsetRelay=function(e){return function(t,n){r.emit(e,t,n.lastIsMaster(),n)}};var relayHa=function(e,t){r.emit("ha",e,t);if(e==="start"){r.emit("ha_connect",e,t)}else if(e==="end"){r.emit("ha_ismaster",e,t)}};r.s.coreTopology.on("joined",replsetRelay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("ping",relay("ping"));r.s.coreTopology.on("ha",relayHa);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r,r)}));r.s.coreTopology.on("all",(function(){r.emit("all",null,r)}));var connectHandler=function(){r.s.coreTopology.once("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.once("close",errorHandler("close"));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var connectErrorHandler=function(){return function(e){["timeout","error","close"].forEach((function(e){r.s.coreTopology.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.s.coreTopology.destroy();try{t(e)}catch(e){if(!r.s.coreTopology.isConnected())process.nextTick((function(){throw e}))}}};r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach((e=>this.removeAllListeners(e)));super.close(e,t)}}Object.defineProperty(ReplSet.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=ReplSet},8421:(e,t,r)=>{"use strict";const n=r(3994).Server;const o=r(7159);const s=r(8589).oF;const i=r(8589).yh;const a=r(3994).MongoError;const A=r(1371).MAX_JS_INT;const c=r(1371).translateOptions;const l=r(1371).filterOptions;const u=r(1371).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","bsonRegExp","compression","promiseLibrary","monitorCommands"];class Server extends s{constructor(e,t,r){super();var s=this;r=l(r,h);const d=r.promiseLibrary;var g={force:false,bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:A};var p=r.store||new i(s,g);if(e.indexOf("/")!==-1){if(t!=null&&typeof t==="object"){r=t;t=null}}else if(t==null){throw a.create({message:"port must be specified",driver:true})}var E=typeof r.auto_reconnect==="boolean"?r.auto_reconnect:true;E=typeof r.autoReconnect==="boolean"?r.autoReconnect:E;var m=u({},{host:e,port:t,disconnectHandler:p,cursorFactory:o,reconnect:E,emitError:typeof r.emitError==="boolean"?r.emitError:true,size:typeof r.poolSize==="number"?r.poolSize:5,monitorCommands:typeof r.monitorCommands==="boolean"?r.monitorCommands:false});m=c(m,r);var C=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;m=c(m,C);this.s={coreTopology:new n(m),sCapabilities:null,clonedOptions:m,reconnect:m.reconnect,emitError:m.emitError,poolSize:m.size,storeOptions:g,store:p,host:e,port:t,options:r,sessionPool:null,sessions:new Set,promiseLibrary:d||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e=this.s.clonedOptions;if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var o=["timeout","error","close"];o.forEach((function(e){r.s.coreTopology.removeListener(e,n[e])}));r.s.coreTopology.removeListener("connect",connectErrorHandler);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect",r);r.s.store.execute()};var reconnectFailedHandler=function(e){r.emit("reconnectFailed",e);r.s.store.flush(e)};var destroyHandler=function(){r.s.store.flush()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){["timeout","error","close","destroy"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("destroy",destroyHandler);r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n={timeout:connectErrorHandler("timeout"),error:connectErrorHandler("error"),close:connectErrorHandler("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.once("timeout",n.timeout);r.s.coreTopology.once("error",n.error);r.s.coreTopology.once("close",n.close);r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.on("reconnectFailed",reconnectFailedHandler);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("attemptReconnect",relay("attemptReconnect"));r.s.coreTopology.on("monitoring",relay("monitoring"));r.s.coreTopology.connect(e)}}Object.defineProperty(Server.prototype,"poolSize",{enumerable:true,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(Server.prototype,"autoReconnect",{enumerable:true,get:function(){return this.s.reconnect}});Object.defineProperty(Server.prototype,"host",{enumerable:true,get:function(){return this.s.host}});Object.defineProperty(Server.prototype,"port",{enumerable:true,get:function(){return this.s.port}});e.exports=Server},8589:(e,t,r)=>{"use strict";const n=r(2361),o=r(3994).MongoError,s=r(3837).format,i=r(3994).ReadPreference,a=r(3994).Sessions.ClientSession;var Store=function(e,t){var r=this;var n=[];t=t||{force:false,bufferMaxEntries:-1};this.s={storedOps:n,storeOptions:t,topology:e};Object.defineProperty(this,"length",{enumerable:true,get:function(){return r.s.storedOps.length}})};Store.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};Store.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};Store.prototype.flush=function(e){while(this.s.storedOps.length>0){this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:true}))}};var A=["primary","primaryPreferred","nearest","secondaryPreferred"];var c=["secondary","secondaryPreferred"];Store.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];var r=typeof e.executePrimary==="boolean"?e.executePrimary:true;var n=typeof e.executeSecondary==="boolean"?e.executeSecondary:true;while(t.length>0){var o=t.shift();if(o.t==="cursor"){if(r&&n){o.o[o.m].apply(o.o,o.p)}else if(r&&o.o.options&&o.o.options.readPreference&&A.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}else if(!r&&n&&o.o.options&&o.o.options.readPreference&&c.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}}else if(o.t==="auth"){this.s.topology[o.t].apply(this.s.topology,o.o)}else{if(r&&n){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(r&&o.op&&o.op.readPreference&&A.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(!r&&n&&o.op&&o.op.readPreference&&c.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}}}};Store.prototype.all=function(){return this.s.storedOps};var ServerCapabilities=function(e){var setup_get_property=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var t=false;var r=false;var n=false;var o=false;var s=false;var i=false;var a=e.maxWriteBatchSize||1e3;var A=false;var c=false;if(e.minWireVersion>=0){n=true}if(e.maxWireVersion>=1){t=true;o=true}if(e.maxWireVersion>=2){r=true}if(e.maxWireVersion>=3){s=true;i=true}if(e.maxWireVersion>=5){A=true;c=true}if(e.minWireVersion==null){e.minWireVersion=0}if(e.maxWireVersion==null){e.maxWireVersion=0}setup_get_property(this,"hasAggregationCursor",t);setup_get_property(this,"hasWriteCommands",r);setup_get_property(this,"hasTextSearch",n);setup_get_property(this,"hasAuthCommands",o);setup_get_property(this,"hasListCollectionsCommand",s);setup_get_property(this,"hasListIndexesCommand",i);setup_get_property(this,"minWireVersion",e.minWireVersion);setup_get_property(this,"maxWireVersion",e.maxWireVersion);setup_get_property(this,"maxNumberOfDocsInBatch",a);setup_get_property(this,"commandsTakeWriteConcern",A);setup_get_property(this,"commandsTakeCollation",c)};class TopologyBase extends n{constructor(){super();this.setMaxListeners(Infinity)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new a(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.s.coreTopology.lastIsMaster()==null)return null;this.s.sCapabilities=new ServerCapabilities(this.s.coreTopology.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){this.s.coreTopology.command(e.toString(),t,i.translate(r),n)}insert(e,t,r,n){this.s.coreTopology.insert(e.toString(),t,r,n)}update(e,t,r,n){this.s.coreTopology.update(e.toString(),t,r,n)}remove(e,t,r,n){this.s.coreTopology.remove(e.toString(),t,r,n)}isConnected(e){e=e||{};e=i.translate(e);return this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,r){r=r||{};r=i.translate(r);r.disconnectHandler=this.s.store;r.topology=this;return this.s.coreTopology.cursor(e,t,r)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,r){return this.s.coreTopology.selectServer(e,t,r)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach((e=>e.endSession()));if(this.s.sessionPool){this.s.sessionPool.endAllPooledSessions()}if(e===true){this.s.storeOptions.force=e;this.s.store.flush()}this.s.coreTopology.destroy({force:typeof e==="boolean"?e:false},t)}}Object.defineProperty(TopologyBase.prototype,"bson",{enumerable:true,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(TopologyBase.prototype,"parserType",{enumerable:true,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(TopologyBase.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(TopologyBase.prototype,"type",{enumerable:true,get:function(){return this.s.coreTopology.type}});t.yh=Store;t.ug=ServerCapabilities;t.oF=TopologyBase},8729:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(7310);const s=r(3837).format;const i=r(3994).Logger;const a=r(7578);const A=r(7289);const c=r(3477);const l=r(3111).MongoParseError;e.exports=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};let n;try{n=o.parse(e,true)}catch(e){return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:"){return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"))}if(n.protocol==="mongodb:"){return parseHandler(e,t,r)}if(n.hostname.split(".").length<3){return r(new Error("URI does not have hostname, domain name and tld"))}n.domainLength=n.hostname.split(".").length;const s=e.substring("mongodb+srv://".length).split("/")[0];if(s.match(",")){return r(new Error("Invalid URI, cannot contain multiple hostnames"))}if(n.port){return r(new Error("Ports not accepted with `mongodb+srv` URIs"))}let i=`_mongodb._tcp.${n.host}`;a.resolveSrv(i,(function(e,o){if(e)return r(e);if(o.length===0){return r(new Error("No addresses found at host"))}for(let e=0;e1){return r(new l("Multiple text records not allowed"))}n=n[0].join("");const e=c.parse(n);const t=Object.keys(e);if(Object.keys(t).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new l("Load balancer mode requires driver version 4+"))}if(t.some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new l("Text record must only set `authSource` or `replicaSet`"))}if(t.length>0){u.push(n)}}if(u.length){A+=`?${u.join("&")}`}parseHandler(A,t,r)}))}))};function matchesParentDomain(e,t){let r=/^.*?\./;let n=`.${e.replace(r,"")}`;let o=`.${t.replace(r,"")}`;if(n.endsWith(o))return true;else return false}function parseHandler(e,t,r){let n,o;try{n=parseConnectionString(e,t)}catch(e){o=e}return o?r(o,null):r(null,n)}function parseConnectionString(e,t){let r="";let a="";let c="";let u="admin";let h=o.parse(e,true);if((h.hostname==null||h.hostname==="")&&e.indexOf(".sock")===-1){throw new Error("No hostname or hostnames provided in connection string")}if(h.port==="0"){throw new Error("Invalid port (zero) with hostname")}if(!isNaN(parseInt(h.port,10))&&parseInt(h.port,10)>65535){throw new Error("Invalid port (larger than 65535) with hostname")}if(h.path&&h.path.length>0&&h.path[0]!=="/"&&e.indexOf(".sock")===-1){throw new Error("Missing delimiting slash between hosts and options")}if(h.query){for(let e in h.query){if(e.indexOf("::")!==-1){throw new Error("Double colon in host identifier")}if(h.query[e]===""){throw new Error("Query parameter "+e+" is an incomplete value pair")}}}if(h.auth){let t=h.auth.split(":");if(e.indexOf(h.auth)!==-1&&t.length>2){throw new Error("Username with password containing an unescaped colon")}if(e.indexOf(h.auth)!==-1&&h.auth.indexOf("@")!==-1){throw new Error("Username containing an unescaped at-sign")}}let d=e.split("?").shift();let g=d.split(",");let p=[];for(let e=0;e1&&t.path.indexOf("::")===-1){throw new Error("Slash in host identifier")}else{throw new Error("Double colon in host identifier")}}}if(e.indexOf("?")!==-1){c=e.substr(e.indexOf("?")+1);r=e.substring("mongodb://".length,e.indexOf("?"))}else{r=e.substring("mongodb://".length)}if(r.indexOf("@")!==-1){a=r.split("@")[0];r=r.split("@")[1]}if(r.split("/").length>2){throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash")}if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){u=r.split(".sock/")[1];if(u.indexOf("/")!==-1){if(u.split("/").length===2&&u.split("/")[1].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}r=r.split("/",r.indexOf(".sock")+".sock".length)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2){if(r.split("/")[2].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}u=r.split("/")[1];r=r.split("/")[0]}r=decodeURIComponent(r);let E={};let m=a||"";let C=m.split(":",2);let I=decodeURIComponent(C[0]);if(C[0]!==encodeURIComponent(I)){throw new Error("Username contains an illegal unescaped character")}C[0]=I;if(C[1]){let e=decodeURIComponent(C[1]);if(C[1]!==encodeURIComponent(e)){throw new Error("Password contains an illegal unescaped character")}C[1]=e}if(C.length===2)E.auth={user:C[0],password:C[1]};if(t&&t.auth!=null)E.auth=t.auth;let y;let B;let Q;let b;let w={socketOptions:{}};let S={read_preference_tags:[]};let v={socketOptions:{}};let R={socketOptions:{}};E.server_options=w;E.db_options=S;E.rs_options=v;E.mongos_options=R;if(e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);if(t.indexOf("@")!==-1)t=t.split("@")[1];t=decodeURIComponent(t);Q=[{domain_socket:t}]}else{y=r;let e={};Q=y.split(",").map((function(t){let r,n,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t)){r=o[1];n=parseInt(o[2],10)||27017}else{let e=t.split(":",2);r=e[0]||"localhost";n=e[1]!=null?parseInt(e[1],10):27017;if(r.indexOf("?")!==-1)r=r.split(/\?/)[0]}if(e[r+"_"+n])return null;e[r+"_"+n]=1;return{host:r,port:n}})).filter((function(e){return e!=null}))}E.dbName=u||"admin";B=(c||"").split(/[&;]/);if(B.some((e=>e.toLowerCase()==="loadbalanced"))){throw new l("Load balancer mode requires driver version 4+")}B.forEach((function(e){if(!e)return;var t=e.split("="),r=t[0],o=t[1];switch(r){case"slaveOk":case"slave_ok":w.slave_ok=o==="true";S.slaveOk=o==="true";break;case"maxPoolSize":case"poolSize":w.poolSize=parseInt(o,10);v.poolSize=parseInt(o,10);break;case"appname":E.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":w.auto_reconnect=o==="true";break;case"ssl":if(o==="prefer"){w.ssl=o;v.ssl=o;R.ssl=o;break}w.ssl=o==="true";v.ssl=o==="true";R.ssl=o==="true";break;case"sslValidate":w.sslValidate=o==="true";v.sslValidate=o==="true";R.sslValidate=o==="true";break;case"replicaSet":case"rs_name":v.rs_name=o;break;case"reconnectWait":v.reconnectWait=parseInt(o,10);break;case"retries":v.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":v.read_secondary=o==="true";break;case"fsync":S.fsync=o==="true";break;case"journal":S.j=o==="true";break;case"safe":S.safe=o==="true";break;case"nativeParser":case"native_parser":S.native_parser=o==="true";break;case"readConcernLevel":S.readConcern=new A(o);break;case"connectTimeoutMS":w.socketOptions.connectTimeoutMS=parseInt(o,10);v.socketOptions.connectTimeoutMS=parseInt(o,10);R.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":w.socketOptions.socketTimeoutMS=parseInt(o,10);v.socketOptions.socketTimeoutMS=parseInt(o,10);R.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":S.w=parseInt(o,10);if(isNaN(S.w))S.w=o;break;case"authSource":S.authSource=o;break;case"gssapiServiceName":S.gssapiServiceName=o;break;case"authMechanism":if(o==="GSSAPI"){if(E.auth==null){let e=decodeURIComponent(m);if(e.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");E.auth={user:e,password:null}}else{E.auth.user=decodeURIComponent(E.auth.user)}}else if(o==="MONGODB-X509"){E.auth={user:decodeURIComponent(m)}}if(o!=="GSSAPI"&&o!=="MONGODB-X509"&&o!=="MONGODB-CR"&&o!=="DEFAULT"&&o!=="SCRAM-SHA-1"&&o!=="SCRAM-SHA-256"&&o!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");S.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(",");let t={};e.forEach((function(e){let r=e.split(":");t[r[0]]=r[1]}));S.authMechanismProperties=t;if(typeof t.SERVICE_NAME==="string")S.gssapiServiceName=t.SERVICE_NAME;if(typeof t.SERVICE_REALM==="string")S.gssapiServiceRealm=t.SERVICE_REALM;if(typeof t.CANONICALIZE_HOST_NAME==="string")S.gssapiCanonicalizeHostName=t.CANONICALIZE_HOST_NAME==="true"?true:false}break;case"wtimeoutMS":S.wtimeout=parseInt(o,10);break;case"readPreference":if(!n.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");S.readPreference=o;break;case"maxStalenessSeconds":S.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{o=decodeURIComponent(o);let e={};if(o==null||o===""){S.read_preference_tags.push(e);break}let t=o.split(/,/);for(let r=0;r9){throw new Error("zlibCompressionLevel must be an integer between -1 and 9")}b.zlibCompressionLevel=e;w.compression=b}break;case"retryWrites":S.retryWrites=o==="true";break;case"minSize":S.minSize=parseInt(o,10);break;default:{let e=i("URL Parser");e.warn(`${r} is not supported as a connection string option`)}break}}));if(S.read_preference_tags.length===0){S.read_preference_tags=null}if((S.w===-1||S.w===0)&&(S.journal===true||S.fsync===true||S.safe===true))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");if(!S.readPreference){S.readPreference="primary"}S=Object.assign(S,t);E.servers=Q;return E}},1371:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(2481);var shallowClone=function(e){var t={};for(var r in e)t[r]=e[r];return t};var getSingleProperty=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var s=t.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){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)']]")}};var i=t.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0){return null}for(var r=0;r{if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!Array.isArray(r)){throw new TypeError("This method requires an array of arguments to apply")}o=o||{};const s=e.s.promiseLibrary;let i=r[r.length-1];let a,A,c;if(!o.skipSessions&&e.hasSessionSupport()){A=r[r.length-2];if(A==null||A.session==null){c=Symbol();a=e.startSession({owner:c});const t=r.length-2;r[t]=Object.assign({},r[t],{session:a})}else if(A.session&&A.session.hasEnded){throw new n("Use of expired sessions is not permitted")}}const makeExecuteCallback=(e,t)=>function executeCallback(r,n){if(a&&a.owner===c&&!o.returnsCursor){a.endSession((()=>{delete A.session;if(r)return t(r);e(n)}))}else{if(r)return t(r);e(n)}};if(typeof i==="function"){i=r.pop();const e=makeExecuteCallback((e=>i(null,e)),(e=>i(e,null)));r.push(e);try{return t.apply(null,r)}catch(t){e(t);throw t}}if(r[r.length-1]!=null){throw new TypeError("final argument to `executeLegacyOperation` must be a callback")}return new s((function(e,n){const o=makeExecuteCallback(e,n);r[r.length-1]=o;try{return t.apply(null,r)}catch(e){o(e)}}))};function applyRetryableWrites(e,t){if(t&&t.s.options.retryWrites){e.retryWrites=true}return e}function applyWriteConcern(e,t,r){r=r||{};const n=t.db;const s=t.collection;if(r.session&&r.session.inTransaction()){if(e.writeConcern){delete e.writeConcern}return e}const i=o.fromOptions(r);if(i){return Object.assign(e,{writeConcern:i})}if(s&&s.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)})}if(n&&n.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)})}return e}function isPromiseLike(e){return e&&typeof e.then==="function"}function decorateWithCollation(e,t,r){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(r.collation&&typeof r.collation==="object"){if(s&&s.commandsTakeCollation){e.collation=r.collation}else{throw new n(`Current topology does not support collation`)}}}function decorateWithReadConcern(e,t,r){if(r&&r.session&&r.session.inTransaction()){return}let n=Object.assign({},e.readConcern||{});if(t.s.readConcern){Object.assign(n,t.s.readConcern)}if(Object.keys(n).length>0){Object.assign(e,{readConcern:n})}}function decorateWithExplain(e,t){if(e.explain){return e}return{explain:e,verbosity:t.verbosity}}const u=+process.version.split(".")[0].substring(1);const emitProcessWarning=e=>u<=6?process.emitWarning(e,"DeprecationWarning",g):process.emitWarning(e,{type:"DeprecationWarning",code:g});const emitConsoleWarning=e=>console.error(e);const h=process.emitWarning?emitProcessWarning:emitConsoleWarning;function defaultMsgHandler(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}function deprecateOptions(e,t){if(process.noDeprecation===true){return t}const r=e.msgHandler?e.msgHandler:defaultMsgHandler;const n=new Set;function deprecated(){const o=arguments[e.optionsIndex];if(!c(o)||Object.keys(o).length===0){return t.apply(this,arguments)}e.deprecatedOptions.forEach((t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!n.has(t)){n.add(t);const o=r(e.name,t);h(o);if(this&&this.getLogger){const e=this.getLogger();if(e){e.warn(o)}}}}));return t.apply(this,arguments)}Object.setPrototypeOf(deprecated,t);if(t.prototype){deprecated.prototype=t.prototype}return deprecated}const d={};try{r(1749);d.ASYNC_ITERATOR=true}catch(e){d.ASYNC_ITERATOR=false}class MongoDBNamespace{constructor(e,t){this.db=e;this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new MongoDBNamespace(this.db,e)}static fromString(e){if(!e){throw new Error(`Cannot parse namespace from "${e}"`)}const t=e.indexOf(".");return new MongoDBNamespace(e.substring(0,t),e.substring(t+1))}}function*makeCounter(e){let t=e||0;while(true){const e=t;t+=1;yield e}}function maybePromise(e,t,r){const n=e&&e.s&&e.s.promiseLibrary||Promise;let o;if(typeof t!=="function"){o=new n(((e,r)=>{t=(t,n)=>{if(t)return r(t);e(n)}}))}r((function(e,r){if(e!=null){try{t(e)}catch(e){return process.nextTick((()=>{throw e}))}return}t(e,r)}));return o}function now(){const e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}function calculateDurationInMs(e){if(typeof e!=="number"){throw TypeError("numeric value required to calculate duration")}const t=now()-e;return t<0?0:t}function makeInterruptableAsyncInterval(e,t){let r;let n;let o;let s=false;t=t||{};const i=t.interval||1e3;const a=t.minInterval||500;const A=typeof t.immediate==="boolean"?t.immediate:false;const c=typeof t.clock==="function"?t.clock:now;function wake(){const e=c();const t=e-o;const r=e-n;const s=i-r;o=e;if(ta){reschedule(a)}if(s<0){executeAndReschedule()}}function stop(){s=true;if(r){clearTimeout(r);r=null}n=0;o=0}function reschedule(e){if(s)return;clearTimeout(r);r=setTimeout(executeAndReschedule,e||i)}function executeAndReschedule(){o=0;n=c();e((e=>{if(e)throw e;reschedule(i)}))}if(A){executeAndReschedule()}else{n=c();reschedule()}return{wake:wake,stop:stop}}function hasAtomicOperators(e){if(Array.isArray(e)){return e.reduce(((e,t)=>e||hasAtomicOperators(t)),null)}return Object.keys(typeof e.toBSON!=="function"?e:e.toBSON()).map((e=>e[0])).indexOf("$")>=0}const g="MONGODB DRIVER";function emitWarning(e){if(process.emitWarning){return u<=6?process.emitWarning(e,undefined,g):process.emitWarning(e,{code:g})}else{return console.error(`[${g}] Warning:`,e)}}const p=new Set;function emitWarningOnce(e){if(!p.has(e)){p.add(e);return emitWarning(e)}}function isSuperset(e,t){e=Array.isArray(e)?new Set(e):e;t=Array.isArray(t)?new Set(t):t;for(const r of t){if(!e.has(r)){return false}}return true}function isRecord(e,t){const r=Object.prototype.toString;const n=Object.prototype.hasOwnProperty;const isObject=e=>r.call(e)==="[object Object]";if(!isObject(e)){return false}const o=e.constructor;if(o&&o.prototype){if(!isObject(o.prototype)){return false}if(!n.call(o.prototype,"isPrototypeOf")){return false}}if(t){const r=Object.keys(e);return isSuperset(r,t)}return true}function deepCopy(e){if(e==null){return e}else if(Array.isArray(e)){return e.map((e=>deepCopy(e)))}else if(isRecord(e)){const t={};for(const r in e){t[r]=deepCopy(e[r])}return t}const t=e.constructor;if(t){switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}}return e}function parsePackageVersion(e){const t=e.version.split(".").map((e=>Number.parseInt(e,10)));return{major:t[0],minor:t[1],patch:t[2]}}e.exports={filterOptions:filterOptions,mergeOptions:mergeOptions,translateOptions:translateOptions,shallowClone:shallowClone,getSingleProperty:getSingleProperty,checkCollectionName:a,toError:toError,formattedOrderClause:i,parseIndexOptions:parseIndexOptions,normalizeHintField:A,handleCallback:handleCallback,decorateCommand:decorateCommand,isObject:c,debugOptions:debugOptions,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:conditionallyMergeWriteConcern,executeLegacyOperation:executeLegacyOperation,applyRetryableWrites:applyRetryableWrites,applyWriteConcern:applyWriteConcern,isPromiseLike:isPromiseLike,decorateWithCollation:decorateWithCollation,decorateWithReadConcern:decorateWithReadConcern,decorateWithExplain:decorateWithExplain,deprecateOptions:deprecateOptions,SUPPORTS:d,MongoDBNamespace:MongoDBNamespace,emitDeprecationWarning:h,makeCounter:makeCounter,maybePromise:maybePromise,now:now,calculateDurationInMs:calculateDurationInMs,makeInterruptableAsyncInterval:makeInterruptableAsyncInterval,hasAtomicOperators:hasAtomicOperators,MONGODB_WARNING_CODE:g,emitWarning:emitWarning,emitWarningOnce:emitWarningOnce,deepCopy:deepCopy,parsePackageVersion:parsePackageVersion}},2481:(e,t,r)=>{"use strict";const n=new Set(["w","wtimeout","j","journal","fsync"]);let o;class WriteConcern{constructor(e,t,r,n){if(e!=null){this.w=e}if(t!=null){this.wtimeout=t}if(r!=null){this.j=r}if(n!=null){this.fsync=n}}static fromOptions(e){if(e==null||e.writeConcern==null&&e.w==null&&e.wtimeout==null&&e.j==null&&e.journal==null&&e.fsync==null){return}if(e.writeConcern){if(typeof e.writeConcern==="string"){return new WriteConcern(e.writeConcern)}if(!Object.keys(e.writeConcern).some((e=>n.has(e)))){return}return new WriteConcern(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}if(!o)o=r(1371);o.emitWarningOnce(`Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.`);return new WriteConcern(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}e.exports=WriteConcern},900:e=>{var t=1e3;var r=t*60;var n=r*60;var o=n*24;var s=o*7;var i=o*365.25;e.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0){return parse(e)}else if(r==="number"&&isFinite(e)){return t.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a){return}var A=parseFloat(a[1]);var c=(a[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return A*i;case"weeks":case"week":case"w":return A*s;case"days":case"day":case"d":return A*o;case"hours":case"hour":case"hrs":case"hr":case"h":return A*n;case"minutes":case"minute":case"mins":case"min":case"m":return A*r;case"seconds":case"second":case"secs":case"sec":case"s":return A*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return undefined}}function fmtShort(e){var s=Math.abs(e);if(s>=o){return Math.round(e/o)+"d"}if(s>=n){return Math.round(e/n)+"h"}if(s>=r){return Math.round(e/r)+"m"}if(s>=t){return Math.round(e/t)+"s"}return e+"ms"}function fmtLong(e){var s=Math.abs(e);if(s>=o){return plural(e,s,o,"day")}if(s>=n){return plural(e,s,n,"hour")}if(s>=r){return plural(e,s,r,"minute")}if(s>=t){return plural(e,s,t,"second")}return e+" ms"}function plural(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}},1156:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.findSync=t.find=t.findAsync=void 0;const n=r(4351);const o=r(1017);const s=r(7147);const i=r(8237);const a=i("new-find-package-json:main");function findAsync(e,t,r){return n.__asyncGenerator(this,arguments,(function*findAsync_1(){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const s=!!r?r:"package.json";const i=!!t||o.isAbsolute(t)?t:process.cwd();let A=o.resolve(i,e);let c=false;while(A){if(A===o.parse(A).root){c=true}const e=o.resolve(A,s);a(`findSync: testing path "${e}"`);const t=yield n.__await(statPathAsync(e));if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield yield n.__await(e);a(`findSync: after yield`)}if(c){break}A=o.resolve(A,"..")}}))}t.findAsync=findAsync;t.find=findAsync;function*findSync(e,t,r){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const n=!!r?r:"package.json";const s=!!t||o.isAbsolute(t)?t:process.cwd();let i=o.resolve(s,e);let A=false;while(i){if(i===o.parse(i).root){A=true}const e=o.resolve(i,n);a(`findSync: testing path "${e}"`);const t=statPathSync(e);if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield e;a(`findSync: after yield`)}if(A){break}i=o.resolve(i,"..")}}t.findSync=findSync;function statPathSync(e){try{return s.statSync(e)}catch(e){if(e.code==="ENOENT"){return undefined}throw e}}function statPathAsync(e){return n.__awaiter(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(e.code==="ENOENT"){return undefined}throw e}))}))}},1223:(e,t,r)=>{var n=r(2940);e.exports=n(once);e.exports.strict=n(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})}));function once(e){var f=function(){if(f.called)return f.value;f.called=true;return f.value=e.apply(this,arguments)};f.called=false;return f}function onceStrict(e){var f=function(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=e.apply(this,arguments)};var t=e.name||"Function wrapped with `once`";f.onceError=t+" shouldn't be called more than once";f.called=false;return f}},9341:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";const n=r(9341);e.exports=function(){return n.makeOptionalRequire.apply(n,arguments)};e.exports.tryRequire=n.tryRequire;e.exports.tryResolve=n.tryResolve;e.exports["try"]=n.tryRequire;e.exports.resolve=n.tryResolve;e.exports.makeOptionalRequire=n.makeOptionalRequire;e.exports.optionalRequire=n.optionalRequire;e.exports.optionalRequireCwd=n.optionalRequireCwd;e.exports.optionalRequireTop=n.optionalRequireTop;let o;Object.defineProperty(e.exports,"log",{set(e){o=e;n.setDefaultLog(e)},get(){return o}})},6978:(e,t,r)=>{"use strict";const n=r(7147);const{promisify:o}=r(3837);const s=o(n.access);e.exports=async e=>{try{await s(e);return true}catch(e){return false}};e.exports.sync=e=>{try{n.accessSync(e);return true}catch(e){return false}}},8714:e=>{"use strict";function posix(e){return e.charAt(0)==="/"}function win32(e){var t=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var r=t.exec(e);var n=r[1]||"";var o=Boolean(n&&n.charAt(1)!==":");return Boolean(r[2]||o)}e.exports=process.platform==="win32"?win32:posix;e.exports.posix=posix;e.exports.win32=win32},4833:e=>{e.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}Pend.prototype.go=function(e){if(this.pending0&&e.pending{"use strict";const n=r(1017);const o=r(1812);const pkgDir=async e=>{const t=await o("package.json",{cwd:e});return t&&n.dirname(t)};e.exports=pkgDir;e.exports["default"]=pkgDir;e.exports.sync=e=>{const t=o.sync("package.json",{cwd:e});return t&&n.dirname(t)}},1812:(e,t,r)=>{"use strict";const n=r(1017);const o=r(5937);const s=r(6978);const i=Symbol("findUp.stop");e.exports=async(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=async t=>{if(typeof e!=="function"){return o(a,t)}const r=await e(t.cwd);if(typeof r==="string"){return o([r],t)}return r};while(true){const e=await runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.sync=(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=t=>{if(typeof e!=="function"){return o.sync(a,t)}const r=e(t.cwd);if(typeof r==="string"){return o.sync([r],t)}return r};while(true){const e=runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.exists=s;e.exports.sync.exists=s.sync;e.exports.stop=i},5937:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const{promisify:s}=r(3837);const i=r(6249);const a=s(o.stat);const A=s(o.lstat);const c={directory:"isDirectory",file:"isFile"};function checkType({type:e}){if(e in c){return}throw new Error(`Invalid type specified: ${e}`)}const matchType=(e,t)=>e===undefined||t[c[e]]();e.exports=async(e,t)=>{t={cwd:process.cwd(),type:"file",allowSymlinks:true,...t};checkType(t);const r=t.allowSymlinks?a:A;return i(e,(async e=>{try{const o=await r(n.resolve(t.cwd,e));return matchType(t.type,o)}catch(e){return false}}),t)};e.exports.sync=(e,t)=>{t={cwd:process.cwd(),allowSymlinks:true,type:"file",...t};checkType(t);const r=t.allowSymlinks?o.statSync:o.lstatSync;for(const o of e){try{const e=r(n.resolve(t.cwd,o));if(matchType(t.type,e)){return o}}catch(e){}}}},4752:(e,t,r)=>{"use strict";const n=r(7471);const pLimit=e=>{if(!((Number.isInteger(e)||e===Infinity)&&e>0)){return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"))}const t=[];let r=0;const next=()=>{r--;if(t.length>0){t.shift()()}};const run=(e,t,...o)=>{r++;const s=n(e,...o);t(s);s.then(next,next)};const enqueue=(n,o,...s)=>{if(rnew Promise((r=>enqueue(e,r,...t)));Object.defineProperties(generator,{activeCount:{get:()=>r},pendingCount:{get:()=>t.length},clearQueue:{value:()=>{t.length=0}}});return generator};e.exports=pLimit;e.exports["default"]=pLimit},6249:(e,t,r)=>{"use strict";const n=r(4752);class EndError extends Error{constructor(e){super();this.value=e}}const testElement=async(e,t)=>t(await e);const finder=async e=>{const t=await Promise.all(e);if(t[1]===true){throw new EndError(t[0])}return false};const pLocate=async(e,t,r)=>{r={concurrency:Infinity,preserveOrder:true,...r};const o=n(r.concurrency);const s=[...e].map((e=>[e,o(testElement,e,t)]));const i=n(r.preserveOrder?1:Infinity);try{await Promise.all(s.map((e=>i(finder,e))))}catch(e){if(e instanceof EndError){return e.value}throw e}};e.exports=pLocate;e.exports["default"]=pLocate},7471:e=>{"use strict";const pTry=(e,...t)=>new Promise((r=>{r(e(...t))}));e.exports=pTry;e.exports["default"]=pTry},7214:e=>{"use strict";const t={};function createErrorType(e,r,n){if(!n){n=Error}function getMessage(e,t,n){if(typeof r==="string"){return r}else{return r(e,t,n)}}class NodeError extends n{constructor(e,t,r){super(getMessage(e,t,r))}}NodeError.prototype.name=n.name;NodeError.prototype.code=e;t[e]=NodeError}function oneOf(e,t){if(Array.isArray(e)){const r=e.length;e=e.map((e=>String(e)));if(r>2){return`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]}else if(r===2){return`one of ${t} ${e[0]} or ${e[1]}`}else{return`of ${t} ${e[0]}`}}else{return`of ${t} ${String(e)}`}}function startsWith(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function endsWith(e,t,r){if(r===undefined||r>e.length){r=e.length}return e.substring(r-t.length,r)===t}function includes(e,t,r){if(typeof r!=="number"){r=0}if(r+t.length>e.length){return false}else{return e.indexOf(t,r)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(e,t,r){let n;if(typeof t==="string"&&startsWith(t,"not ")){n="must not be";t=t.replace(/^not /,"")}else{n="must be"}let o;if(endsWith(e," argument")){o=`The ${e} ${n} ${oneOf(t,"type")}`}else{const r=includes(e,".")?"property":"argument";o=`The "${e}" ${r} ${n} ${oneOf(t,"type")}`}o+=`. Received type ${typeof r}`;return o}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.q=t},1359:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=r(1433);var s=r(6993);r(4124)(Duplex,o);{var i=n(s.prototype);for(var a=0;a{"use strict";e.exports=PassThrough;var n=r(4415);r(4124)(PassThrough,n);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);n.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},1433:(e,t,r)=>{"use strict";e.exports=Readable;var n;Readable.ReadableState=ReadableState;var o=r(2361).EventEmitter;var s=function EElistenerCount(e,t){return e.listeners(t).length};var i=r(2387);var a=r(4300).Buffer;var A=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return a.from(e)}function _isUint8Array(e){return a.isBuffer(e)||e instanceof A}var c=r(3837);var l;if(c&&c.debuglog){l=c.debuglog("stream")}else{l=function debug(){}}var u=r(2746);var h=r(7049);var d=r(9948),g=d.getHighWaterMark;var p=r(7214).q,E=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,C=p.ERR_METHOD_NOT_IMPLEMENTED,I=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var y;var B;var Q;r(4124)(Readable,i);var b=h.errorOrDestroy;var w=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(Array.isArray(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.readableObjectMode;this.highWaterMark=g(this,e,"readableHighWaterMark",o);this.buffer=new u;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(4841).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){n=n||r(1359);if(!(this instanceof Readable))return new Readable(e);var t=this instanceof n;this._readableState=new ReadableState(e,this,t);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}i.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=h.destroy;Readable.prototype._undestroy=h.undestroy;Readable.prototype._destroy=function(e,t){t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var n;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=a.from(e,t);t=""}n=true}}else{n=true}return readableAddChunk(this,e,t,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,n,o){l("readableAddChunk",t);var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var i;if(!o)i=chunkInvalid(s,t);if(i){b(e,i)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==a.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(s.endEmitted)b(e,new I);else addChunk(e,s,t,true)}else if(s.ended){b(e,new m)}else if(s.destroyed){return false}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!n){s.reading=false;maybeReadMore(e,s)}}return!s.ended&&(s.length=S){e=S}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){l("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=t.length<=t.highWaterMark;e=0}else{t.length-=e;t.awaitDrain=0}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){l("onEofChunk");if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.sync){emitReadable(e)}else{t.needReadable=false;if(!t.emittedReadable){t.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable);t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended);if(!t.destroyed&&(t.length||t.ended)){e.emit("readable");t.emittedReadable=false}t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark;flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;process.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){while(!t.reading&&!t.ended&&(t.length1&&indexOf(n.pipes,e)!==-1)&&!A){l("false write response, pause",n.awaitDrain);n.awaitDrain++}r.pause()}}function onerror(t){l("onerror",t);unpipe();e.removeListener("error",onerror);if(s(e,"error")===0)b(e,t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){l("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){l("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!n.flowing){l("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&s(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var n=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;l("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return r};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);if(e==="readable"){process.nextTick(updateReadableListening,this)}return r};Readable.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return t};function updateReadableListening(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0;if(t.resumeScheduled&&!t.paused){t.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){l("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){l("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,t){if(!t.resumeScheduled){t.resumeScheduled=true;process.nextTick(resume_,e,t)}}function resume_(e,t){l("resume",t.reading);if(!t.reading){e.read(0)}t.resumeScheduled=false;e.emit("resume");flow(e);if(t.flowing&&!t.reading)e.read(0)}Readable.prototype.pause=function(){l("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){l("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var t=e._readableState;l("flow",t.flowing);while(t.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var t=this;var r=this._readableState;var n=false;e.on("end",(function(){l("wrapped end");if(r.decoder&&!r.ended){var e=r.decoder.end();if(e&&e.length)t.push(e)}t.push(null)}));e.on("data",(function(o){l("wrapped data");if(r.decoder)o=r.decoder.write(o);if(r.objectMode&&(o===null||o===undefined))return;else if(!r.objectMode&&(!o||!o.length))return;var s=t.push(o);if(!s){n=true;e.pause()}}));for(var o in e){if(this[o]===undefined&&typeof e[o]==="function"){this[o]=function methodWrap(t){return function methodWrapReturnFunction(){return e[t].apply(e,arguments)}}(o)}}for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.first();else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=t.buffer.consume(e,t.decoder)}return r}function endReadable(e){var t=e._readableState;l("endReadable",t.endEmitted);if(!t.endEmitted){t.ended=true;process.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){l("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end");if(e.autoDestroy){var r=t._writableState;if(!r||r.autoDestroy&&r.finished){t.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(e,t){if(Q===undefined){Q=r(9082)}return Q(Readable,e,t)}}function indexOf(e,t){for(var r=0,n=e.length;r{"use strict";e.exports=Transform;var n=r(7214).q,o=n.ERR_METHOD_NOT_IMPLEMENTED,s=n.ERR_MULTIPLE_CALLBACK,i=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=n.ERR_TRANSFORM_WITH_LENGTH_0;var A=r(1359);r(4124)(Transform,A);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null){return this.emit("error",new s)}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);n(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var n;Writable.WritableState=WritableState;var o={deprecate:r(5278)};var s=r(2387);var i=r(4300).Buffer;var a=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return i.from(e)}function _isUint8Array(e){return i.isBuffer(e)||e instanceof a}var A=r(7049);var c=r(9948),l=c.getHighWaterMark;var u=r(7214).q,h=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,g=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,E=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,C=u.ERR_STREAM_WRITE_AFTER_END,I=u.ERR_UNKNOWN_ENCODING;var y=A.errorOrDestroy;r(4124)(Writable,s);function nop(){}function WritableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.writableObjectMode;this.highWaterMark=l(this,e,"writableHighWaterMark",o);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var s=e.decodeStrings===false;this.decodeStrings=!s;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:o.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var B;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){B=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(e){if(B.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{B=function realHasInstance(e){return e instanceof this}}function Writable(e){n=n||r(1359);var t=this instanceof n;if(!t&&!B.call(Writable,this))return new Writable(e);this._writableState=new WritableState(e,this,t);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}s.call(this)}Writable.prototype.pipe=function(){y(this,new p)};function writeAfterEnd(e,t){var r=new C;y(e,r);process.nextTick(t,r)}function validChunk(e,t,r,n){var o;if(r===null){o=new m}else if(typeof r!=="string"&&!t.objectMode){o=new h("chunk",["string","Buffer"],r)}if(o){y(e,o);process.nextTick(n,o);return false}return true}Writable.prototype.write=function(e,t,r){var n=this._writableState;var o=false;var s=!n.objectMode&&_isUint8Array(e);if(s&&!i.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=n.defaultEncoding;if(typeof r!=="function")r=nop;if(n.ending)writeAfterEnd(this,r);else if(s||validChunk(this,n,e,r)){n.pendingcb++;o=writeOrBuffer(this,n,s,e,t,r)}return o};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new I(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=i.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,n,o,s){if(!r){var i=decodeChunk(t,n,o);if(n!==i){r=true;o="buffer";n=i}}var a=t.objectMode?1:n.length;t.length+=a;var A=t.length{"use strict";var n;function _defineProperty(e,t,r){if(t in e){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true})}else{e[t]=r}return e}var o=r(6080);var s=Symbol("lastResolve");var i=Symbol("lastReject");var a=Symbol("error");var A=Symbol("ended");var c=Symbol("lastPromise");var l=Symbol("handlePromise");var u=Symbol("stream");function createIterResult(e,t){return{value:e,done:t}}function readAndResolve(e){var t=e[s];if(t!==null){var r=e[u].read();if(r!==null){e[c]=null;e[s]=null;e[i]=null;t(createIterResult(r,false))}}}function onReadable(e){process.nextTick(readAndResolve,e)}function wrapForNext(e,t){return function(r,n){e.then((function(){if(t[A]){r(createIterResult(undefined,true));return}t[l](r,n)}),n)}}var h=Object.getPrototypeOf((function(){}));var d=Object.setPrototypeOf((n={get stream(){return this[u]},next:function next(){var e=this;var t=this[a];if(t!==null){return Promise.reject(t)}if(this[A]){return Promise.resolve(createIterResult(undefined,true))}if(this[u].destroyed){return new Promise((function(t,r){process.nextTick((function(){if(e[a]){r(e[a])}else{t(createIterResult(undefined,true))}}))}))}var r=this[c];var n;if(r){n=new Promise(wrapForNext(r,this))}else{var o=this[u].read();if(o!==null){return Promise.resolve(createIterResult(o,false))}n=new Promise(this[l])}this[c]=n;return n}},_defineProperty(n,Symbol.asyncIterator,(function(){return this})),_defineProperty(n,"return",(function _return(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){if(e){r(e);return}t(createIterResult(undefined,true))}))}))})),n),h);var g=function createReadableStreamAsyncIterator(e){var t;var r=Object.create(d,(t={},_defineProperty(t,u,{value:e,writable:true}),_defineProperty(t,s,{value:null,writable:true}),_defineProperty(t,i,{value:null,writable:true}),_defineProperty(t,a,{value:null,writable:true}),_defineProperty(t,A,{value:e._readableState.endEmitted,writable:true}),_defineProperty(t,l,{value:function value(e,t){var n=r[u].read();if(n){r[c]=null;r[s]=null;r[i]=null;e(createIterResult(n,false))}else{r[s]=e;r[i]=t}},writable:true}),t));r[c]=null;o(e,(function(e){if(e&&e.code!=="ERR_STREAM_PREMATURE_CLOSE"){var t=r[i];if(t!==null){r[c]=null;r[s]=null;r[i]=null;t(e)}r[a]=e;return}var n=r[s];if(n!==null){r[c]=null;r[s]=null;r[i]=null;n(createIterResult(undefined,true))}r[A]=true}));e.on("readable",onReadable.bind(null,r));return r};e.exports=g},2746:(e,t,r)=>{"use strict";function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t0)this.tail.next=t;else this.head=t;this.tail=t;++this.length}},{key:"unshift",value:function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r}},{key:"concat",value:function concat(e){if(this.length===0)return o.alloc(0);var t=o.allocUnsafe(e>>>0);var r=this.head;var n=0;while(r){copyBuffer(r.data,t,n);n+=r.data.length;r=r.next}return t}},{key:"consume",value:function consume(e,t){var r;if(eo.length?o.length:e;if(s===o.length)n+=o;else n+=o.slice(0,e);e-=s;if(e===0){if(s===o.length){++r;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=o.slice(s)}break}++r}this.length-=r;return n}},{key:"_getBuffer",value:function _getBuffer(e){var t=o.allocUnsafe(e);var r=this.head;var n=1;r.data.copy(t);e-=r.data.length;while(r=r.next){var s=r.data;var i=e>s.length?s.length:e;s.copy(t,t.length-e,0,i);e-=i;if(e===0){if(i===s.length){++n;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=s.slice(i)}break}++n}this.length-=n;return t}},{key:a,value:function value(e,t){return i(this,_objectSpread({},t,{depth:0,customInspect:false}))}}]);return BufferList}()},7049:e=>{"use strict";function destroy(e,t){var r=this;var n=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(n||o){if(t){t(e)}else if(e){if(!this._writableState){process.nextTick(emitErrorNT,this,e)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,e)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){if(!r._writableState){process.nextTick(emitErrorAndCloseNT,r,e)}else if(!r._writableState.errorEmitted){r._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,r,e)}else{process.nextTick(emitCloseNT,r)}}else if(t){process.nextTick(emitCloseNT,r);t(e)}else{process.nextTick(emitCloseNT,r)}}));return this}function emitErrorAndCloseNT(e,t){emitErrorNT(e,t);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}function errorOrDestroy(e,t){var r=e._readableState;var n=e._writableState;if(r&&r.autoDestroy||n&&n.autoDestroy)e.destroy(t);else e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},6080:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_STREAM_PREMATURE_CLOSE;function once(e){var t=false;return function(){if(t)return;t=true;for(var r=arguments.length,n=new Array(r),o=0;o{"use strict";function asyncGeneratorStep(e,t,r,n,o,s,i){try{var a=e[s](i);var A=a.value}catch(e){r(e);return}if(a.done){t(A)}else{Promise.resolve(A).then(n,o)}}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var s=e.apply(t,r);function _next(e){asyncGeneratorStep(s,n,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(s,n,o,_next,_throw,"throw",e)}_next(undefined)}))}}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t{"use strict";var n;function once(e){var t=false;return function(){if(t)return;t=true;e.apply(void 0,arguments)}}var o=r(7214).q,s=o.ERR_MISSING_ARGS,i=o.ERR_STREAM_DESTROYED;function noop(e){if(e)throw e}function isRequest(e){return e.setHeader&&typeof e.abort==="function"}function destroyer(e,t,o,s){s=once(s);var a=false;e.on("close",(function(){a=true}));if(n===undefined)n=r(6080);n(e,{readable:t,writable:o},(function(e){if(e)return s(e);a=true;s()}));var A=false;return function(t){if(a)return;if(A)return;A=true;if(isRequest(e))return e.abort();if(typeof e.destroy==="function")return e.destroy();s(t||new i("pipe"))}}function call(e){e()}function pipe(e,t){return e.pipe(t)}function popCallback(e){if(!e.length)return noop;if(typeof e[e.length-1]!=="function")return noop;return e.pop()}function pipeline(){for(var e=arguments.length,t=new Array(e),r=0;r0;return destroyer(e,s,a,(function(e){if(!o)o=e;if(e)i.forEach(call);if(s)return;i.forEach(call);n(o)}))}));return t.reduce(pipe)}e.exports=pipeline},9948:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function getHighWaterMark(e,t,r,o){var s=highWaterMarkFrom(t,o,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var i=o?r:"highWaterMark";throw new n(i,s)}return Math.floor(s)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},2387:(e,t,r)=>{e.exports=r(2781)},1642:(e,t,r)=>{var n=r(2781);if(process.env.READABLE_STREAM==="disable"&&n){e.exports=n.Readable;Object.assign(e.exports,n);e.exports.Stream=n}else{t=e.exports=r(1433);t.Stream=n||t;t.Readable=t;t.Writable=r(6993);t.Duplex=r(1359);t.Transform=r(4415);t.PassThrough=r(1542);t.finished=r(6080);t.pipeline=r(6989)}},545:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";const Module=__nccwpck_require__(8188);const xrequire=eval("require");const createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{const r=new Module(e);r.filename=e;r.paths=Module._nodeModulePaths(t);function _require(e){return xrequire(resolve(e))}function resolve(e,t){return Module._resolveFilename(e,r,false,t)}_require.resolve=resolve;function paths(e){return Module._resolveLookupPaths(e,r,true)}resolve.paths=paths;_require.main=process.mainModule;_require.extensions=Module._extensions;_require.cache=Module._cache;return _require});module.exports=createRequireFromPath},2058:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(545);const i=new Map;function requireAt(e,t){const makeIt=(r,i)=>{let a=requireAt.cache&&requireAt.cache.get(r);if(!a){let t;try{t=o.statSync(r)}catch(e){throw new Error(`require-at: stat '${r}' failed: ${e.message}`)}if(!t||!t.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return makeIt(n.dirname(r),true)}a=s(n.join(r,"._require-at_"),r);requireAt.cache&&requireAt.cache.set(r,a)}return t?a(t):a};return makeIt(n.resolve(e),false)}requireAt.cache=i;e.exports=requireAt},4959:(e,t,r)=>{const n=r(9491);const o=r(1017);const s=r(7147);let i=undefined;try{i=r(1957)}catch(e){}const a={nosort:true,silent:true};let A=0;const c=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&i===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||a};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof r,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let a=0;const next=e=>{s=s||e;if(--a===0)r(s)};const afterGlob=(e,n)=>{if(e)return r(e);a=n.length;if(a===0)return r();n.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&Arimraf_(e,t,CB)),A++)}if(r.code==="ENOENT")r=null}A=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!i.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,n)=>{if(!r)return afterGlob(null,[e]);i(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.lstat(e,((n,o)=>{if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&c)fixWinEPERM(e,t,n,r);if(o&&o.isDirectory())return rmdir(e,t,n,r);t.unlink(e,(n=>{if(n){if(n.code==="ENOENT")return r(null);if(n.code==="EPERM")return c?fixWinEPERM(e,t,n,r):rmdir(e,t,n,r);if(n.code==="EISDIR")return rmdir(e,t,n,r)}return r(n)}))}))};const fixWinEPERM=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.chmod(e,438,(n=>{if(n)o(n.code==="ENOENT"?null:r);else t.stat(e,((n,s)=>{if(n)o(n.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{n(e);n(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.rmdir(e,(n=>{if(n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM"))rmkids(e,t,o);else if(n&&n.code==="ENOTDIR")o(r);else o(n)}))};const rmkids=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.readdir(e,((n,s)=>{if(n)return r(n);let i=s.length;if(i===0)return t.rmdir(e,r);let a;s.forEach((n=>{rimraf(o.join(e,n),t,(n=>{if(a)return;if(n)return r(a=n);if(--i===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n(t,"rimraf: missing options");n.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!i.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(n){r=i.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{n(e);n(t);try{t.rmdirSync(e)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;if(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{n(e);n(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=c?100:1;let s=0;do{let n=true;try{const r=t.rmdirSync(e,t);n=false;return r}finally{if(++s{var n=r(4300);var o=n.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=o(e);if(t!==undefined){if(typeof r==="string"){n.fill(t,r)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},9178:(e,t,r)=>{"use strict";const{unassigned_code_points:n,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:A}=r(8916);e.exports=saslprep;const c=s;const l=o;const getCodePoint=e=>e.codePointAt(0);const first=e=>e[0];const last=e=>e[e.length-1];function toCodePoints(e){const t=[];const r=e.length;for(let n=0;n=55296&&o<=56319&&r>n+1){const r=e.charCodeAt(n+1);if(r>=56320&&r<=57343){t.push((o-55296)*1024+r-56320+65536);n+=1;continue}}t.push(o)}return t}function saslprep(e,t={}){if(typeof e!=="string"){throw new TypeError("Expected string.")}if(e.length===0){return""}const r=toCodePoints(e).map((e=>c.get(e)?32:e)).filter((e=>!l.get(e)));const o=String.fromCodePoint.apply(null,r).normalize("NFKC");const s=toCodePoints(o);const u=s.some((e=>i.get(e)));if(u){throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3")}if(t.allowUnassigned!==true){const e=s.some((e=>n.get(e)));if(e){throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}}const h=s.some((e=>a.get(e)));const d=s.some((e=>A.get(e)));if(h&&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 g=a.get(getCodePoint(first(o)));const p=a.get(getCodePoint(last(o)));if(h&&!(g&&p)){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}},8916:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const s=r(1453);const i=n.readFileSync(r.ab+"code-points.mem");let a=0;function read(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);a+=e;return s({buffer:t})}const A=read();const c=read();const l=read();const u=read();const h=read();const d=read();e.exports={unassigned_code_points:A,commonly_mapped_to_nothing:c,non_ASCII_space_characters:l,prohibited_characters:u,bidirectional_r_al:h,bidirectional_l:d}},1532:(e,t,r)=>{const n=Symbol("SemVer ANY");class Comparator{static get ANY(){return n}constructor(e,t){t=o(t);if(e instanceof Comparator){if(e.loose===!!t.loose){return e}else{e=e.value}}e=e.trim().split(/\s+/).join(" ");A("comparator",e,t);this.options=t;this.loose=!!t.loose;this.parse(e);if(this.semver===n){this.value=""}else{this.value=this.operator+this.semver.version}A("comp",this)}parse(e){const t=this.options.loose?s[i.COMPARATORLOOSE]:s[i.COMPARATOR];const r=e.match(t);if(!r){throw new TypeError(`Invalid comparator: ${e}`)}this.operator=r[1]!==undefined?r[1]:"";if(this.operator==="="){this.operator=""}if(!r[2]){this.semver=n}else{this.semver=new c(r[2],this.options.loose)}}toString(){return this.value}test(e){A("Comparator.test",e,this.options.loose);if(this.semver===n||e===n){return true}if(typeof e==="string"){try{e=new c(e,this.options)}catch(e){return false}}return a(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator)){throw new TypeError("a Comparator is required")}if(this.operator===""){if(this.value===""){return true}return new l(e.value,t).test(this.value)}else if(e.operator===""){if(e.value===""){return true}return new l(this.value,t).test(e.semver)}t=o(t);if(t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")){return false}if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))){return false}if(this.operator.startsWith(">")&&e.operator.startsWith(">")){return true}if(this.operator.startsWith("<")&&e.operator.startsWith("<")){return true}if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")){return true}if(a(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")){return true}if(a(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")){return true}return false}}e.exports=Comparator;const o=r(785);const{safeRe:s,t:i}=r(9523);const a=r(5098);const A=r(427);const c=r(8088);const l=r(9828)},9828:(e,t,r)=>{class Range{constructor(e,t){t=s(t);if(e instanceof Range){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{return new Range(e.raw,t)}}if(e instanceof i){this.raw=e.value;this.set=[[e]];this.format();return this}this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;this.raw=e.trim().split(/\s+/).join(" ");this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length));if(!this.set.length){throw new TypeError(`Invalid SemVer Range: ${this.raw}`)}if(this.set.length>1){const e=this.set[0];this.set=this.set.filter((e=>!isNullSet(e[0])));if(this.set.length===0){this.set=[e]}else if(this.set.length>1){for(const e of this.set){if(e.length===1&&isAny(e[0])){this.set=[e];break}}}}this.format()}format(){this.range=this.set.map((e=>e.join(" ").trim())).join("||").trim();return this.range}toString(){return this.range}parseRange(e){const t=(this.options.includePrerelease&&g)|(this.options.loose&&p);const r=t+":"+e;const n=o.get(r);if(n){return n}const s=this.options.loose;const A=s?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(A,hyphenReplace(this.options.includePrerelease));a("hyphen replace",e);e=e.replace(c[l.COMPARATORTRIM],u);a("comparator trim",e);e=e.replace(c[l.TILDETRIM],h);a("tilde trim",e);e=e.replace(c[l.CARETTRIM],d);a("caret trim",e);let E=e.split(" ").map((e=>parseComparator(e,this.options))).join(" ").split(/\s+/).map((e=>replaceGTE0(e,this.options)));if(s){E=E.filter((e=>{a("loose invalid filter",e,this.options);return!!e.match(c[l.COMPARATORLOOSE])}))}a("range list",E);const m=new Map;const C=E.map((e=>new i(e,this.options)));for(const e of C){if(isNullSet(e)){return[e]}m.set(e.value,e)}if(m.size>1&&m.has("")){m.delete("")}const I=[...m.values()];o.set(r,I);return I}intersects(e,t){if(!(e instanceof Range)){throw new TypeError("a Range is required")}return this.set.some((r=>isSatisfiable(r,t)&&e.set.some((e=>isSatisfiable(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e){return false}if(typeof e==="string"){try{e=new A(e,this.options)}catch(e){return false}}for(let t=0;te.value==="<0.0.0-0";const isAny=e=>e.value==="";const isSatisfiable=(e,t)=>{let r=true;const n=e.slice();let o=n.pop();while(r&&n.length){r=n.every((e=>o.intersects(e,t)));o=n.pop()}return r};const parseComparator=(e,t)=>{a("comp",e,t);e=replaceCarets(e,t);a("caret",e);e=replaceTildes(e,t);a("tildes",e);e=replaceXRanges(e,t);a("xrange",e);e=replaceStars(e,t);a("stars",e);return e};const isX=e=>!e||e.toLowerCase()==="x"||e==="*";const replaceTildes=(e,t)=>e.trim().split(/\s+/).map((e=>replaceTilde(e,t))).join(" ");const replaceTilde=(e,t)=>{const r=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(r,((t,r,n,o,s)=>{a("tilde",e,t,r,n,o,s);let i;if(isX(r)){i=""}else if(isX(n)){i=`>=${r}.0.0 <${+r+1}.0.0-0`}else if(isX(o)){i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`}else if(s){a("replaceTilde pr",s);i=`>=${r}.${n}.${o}-${s} <${r}.${+n+1}.0-0`}else{i=`>=${r}.${n}.${o} <${r}.${+n+1}.0-0`}a("tilde return",i);return i}))};const replaceCarets=(e,t)=>e.trim().split(/\s+/).map((e=>replaceCaret(e,t))).join(" ");const replaceCaret=(e,t)=>{a("caret",e,t);const r=t.loose?c[l.CARETLOOSE]:c[l.CARET];const n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,o,s,i)=>{a("caret",e,t,r,o,s,i);let A;if(isX(r)){A=""}else if(isX(o)){A=`>=${r}.0.0${n} <${+r+1}.0.0-0`}else if(isX(s)){if(r==="0"){A=`>=${r}.${o}.0${n} <${r}.${+o+1}.0-0`}else{A=`>=${r}.${o}.0${n} <${+r+1}.0.0-0`}}else if(i){a("replaceCaret pr",i);if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}-${i} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}-${i} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s}-${i} <${+r+1}.0.0-0`}}else{a("no pr");if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}${n} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}${n} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s} <${+r+1}.0.0-0`}}a("caret return",A);return A}))};const replaceXRanges=(e,t)=>{a("replaceXRanges",e,t);return e.split(/\s+/).map((e=>replaceXRange(e,t))).join(" ")};const replaceXRange=(e,t)=>{e=e.trim();const r=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(r,((r,n,o,s,i,A)=>{a("xRange",e,r,n,o,s,i,A);const c=isX(o);const l=c||isX(s);const u=l||isX(i);const h=u;if(n==="="&&h){n=""}A=t.includePrerelease?"-0":"";if(c){if(n===">"||n==="<"){r="<0.0.0-0"}else{r="*"}}else if(n&&h){if(l){s=0}i=0;if(n===">"){n=">=";if(l){o=+o+1;s=0;i=0}else{s=+s+1;i=0}}else if(n==="<="){n="<";if(l){o=+o+1}else{s=+s+1}}if(n==="<"){A="-0"}r=`${n+o}.${s}.${i}${A}`}else if(l){r=`>=${o}.0.0${A} <${+o+1}.0.0-0`}else if(u){r=`>=${o}.${s}.0${A} <${o}.${+s+1}.0-0`}a("xRange return",r);return r}))};const replaceStars=(e,t)=>{a("replaceStars",e,t);return e.trim().replace(c[l.STAR],"")};const replaceGTE0=(e,t)=>{a("replaceGTE0",e,t);return e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],"")};const hyphenReplace=e=>(t,r,n,o,s,i,a,A,c,l,u,h)=>{if(isX(n)){r=""}else if(isX(o)){r=`>=${n}.0.0${e?"-0":""}`}else if(isX(s)){r=`>=${n}.${o}.0${e?"-0":""}`}else if(i){r=`>=${r}`}else{r=`>=${r}${e?"-0":""}`}if(isX(c)){A=""}else if(isX(l)){A=`<${+c+1}.0.0-0`}else if(isX(u)){A=`<${c}.${+l+1}.0-0`}else if(h){A=`<=${c}.${l}.${u}-${h}`}else if(e){A=`<${c}.${l}.${+u+1}-0`}else{A=`<=${A}`}return`${r} ${A}`.trim()};const testSet=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch){return true}}}return false}return true}},8088:(e,t,r)=>{const n=r(427);const{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=r(2293);const{safeRe:i,t:a}=r(9523);const A=r(785);const{compareIdentifiers:c}=r(2463);class SemVer{constructor(e,t){t=A(t);if(e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{e=e.version}}else if(typeof e!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`)}if(e.length>o){throw new TypeError(`version is longer than ${o} characters`)}n("SemVer",e,t);this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[a.LOOSE]:i[a.FULL]);if(!r){throw new TypeError(`Invalid Version: ${e}`)}this.raw=e;this.major=+r[1];this.minor=+r[2];this.patch=+r[3];if(this.major>s||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>s||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>s||this.patch<0){throw new TypeError("Invalid patch version")}if(!r[4]){this.prerelease=[]}else{this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0){if(typeof this.prerelease[n]==="number"){this.prerelease[n]++;n=-2}}if(n===-1){if(t===this.prerelease.join(".")&&r===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(e)}}if(t){let n=[t,e];if(r===false){n=[t]}if(c(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1])){this.prerelease=n}}else{this.prerelease=n}}break}default:throw new Error(`invalid increment argument: ${e}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}e.exports=SemVer},8848:(e,t,r)=>{const n=r(5925);const clean=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};e.exports=clean},5098:(e,t,r)=>{const n=r(1898);const o=r(6017);const s=r(4123);const i=r(5522);const a=r(194);const A=r(7520);const cmp=(e,t,r,c)=>{switch(t){case"===":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e===r;case"!==":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e!==r;case"":case"=":case"==":return n(e,r,c);case"!=":return o(e,r,c);case">":return s(e,r,c);case">=":return i(e,r,c);case"<":return a(e,r,c);case"<=":return A(e,r,c);default:throw new TypeError(`Invalid operator: ${t}`)}};e.exports=cmp},3466:(e,t,r)=>{const n=r(8088);const o=r(5925);const{safeRe:s,t:i}=r(9523);const coerce=(e,t)=>{if(e instanceof n){return e}if(typeof e==="number"){e=String(e)}if(typeof e!=="string"){return null}t=t||{};let r=null;if(!t.rtl){r=e.match(t.includePrerelease?s[i.COERCEFULL]:s[i.COERCE])}else{const n=t.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL];let o;while((o=n.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||o.index+o[0].length!==r.index+r[0].length){r=o}n.lastIndex=o.index+o[1].length+o[2].length}n.lastIndex=-1}if(r===null){return null}const a=r[2];const A=r[3]||"0";const c=r[4]||"0";const l=t.includePrerelease&&r[5]?`-${r[5]}`:"";const u=t.includePrerelease&&r[6]?`+${r[6]}`:"";return o(`${a}.${A}.${c}${l}${u}`,t)};e.exports=coerce},2156:(e,t,r)=>{const n=r(8088);const compareBuild=(e,t,r)=>{const o=new n(e,r);const s=new n(t,r);return o.compare(s)||o.compareBuild(s)};e.exports=compareBuild},2804:(e,t,r)=>{const n=r(4309);const compareLoose=(e,t)=>n(e,t,true);e.exports=compareLoose},4309:(e,t,r)=>{const n=r(8088);const compare=(e,t,r)=>new n(e,r).compare(new n(t,r));e.exports=compare},4297:(e,t,r)=>{const n=r(5925);const diff=(e,t)=>{const r=n(e,null,true);const o=n(t,null,true);const s=r.compare(o);if(s===0){return null}const i=s>0;const a=i?r:o;const A=i?o:r;const c=!!a.prerelease.length;const l=!!A.prerelease.length;if(l&&!c){if(!A.patch&&!A.minor){return"major"}if(a.patch){return"patch"}if(a.minor){return"minor"}return"major"}const u=c?"pre":"";if(r.major!==o.major){return u+"major"}if(r.minor!==o.minor){return u+"minor"}if(r.patch!==o.patch){return u+"patch"}return"prerelease"};e.exports=diff},1898:(e,t,r)=>{const n=r(4309);const eq=(e,t,r)=>n(e,t,r)===0;e.exports=eq},4123:(e,t,r)=>{const n=r(4309);const gt=(e,t,r)=>n(e,t,r)>0;e.exports=gt},5522:(e,t,r)=>{const n=r(4309);const gte=(e,t,r)=>n(e,t,r)>=0;e.exports=gte},929:(e,t,r)=>{const n=r(8088);const inc=(e,t,r,o,s)=>{if(typeof r==="string"){s=o;o=r;r=undefined}try{return new n(e instanceof n?e.version:e,r).inc(t,o,s).version}catch(e){return null}};e.exports=inc},194:(e,t,r)=>{const n=r(4309);const lt=(e,t,r)=>n(e,t,r)<0;e.exports=lt},7520:(e,t,r)=>{const n=r(4309);const lte=(e,t,r)=>n(e,t,r)<=0;e.exports=lte},6688:(e,t,r)=>{const n=r(8088);const major=(e,t)=>new n(e,t).major;e.exports=major},8447:(e,t,r)=>{const n=r(8088);const minor=(e,t)=>new n(e,t).minor;e.exports=minor},6017:(e,t,r)=>{const n=r(4309);const neq=(e,t,r)=>n(e,t,r)!==0;e.exports=neq},5925:(e,t,r)=>{const n=r(8088);const parse=(e,t,r=false)=>{if(e instanceof n){return e}try{return new n(e,t)}catch(e){if(!r){return null}throw e}};e.exports=parse},2866:(e,t,r)=>{const n=r(8088);const patch=(e,t)=>new n(e,t).patch;e.exports=patch},4016:(e,t,r)=>{const n=r(5925);const prerelease=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};e.exports=prerelease},6417:(e,t,r)=>{const n=r(4309);const rcompare=(e,t,r)=>n(t,e,r);e.exports=rcompare},8701:(e,t,r)=>{const n=r(2156);const rsort=(e,t)=>e.sort(((e,r)=>n(r,e,t)));e.exports=rsort},6055:(e,t,r)=>{const n=r(9828);const satisfies=(e,t,r)=>{try{t=new n(t,r)}catch(e){return false}return t.test(e)};e.exports=satisfies},1426:(e,t,r)=>{const n=r(2156);const sort=(e,t)=>e.sort(((e,r)=>n(e,r,t)));e.exports=sort},9601:(e,t,r)=>{const n=r(5925);const valid=(e,t)=>{const r=n(e,t);return r?r.version:null};e.exports=valid},1383:(e,t,r)=>{const n=r(9523);const o=r(2293);const s=r(8088);const i=r(2463);const a=r(5925);const A=r(9601);const c=r(8848);const l=r(929);const u=r(4297);const h=r(6688);const d=r(8447);const g=r(2866);const p=r(4016);const E=r(4309);const m=r(6417);const C=r(2804);const I=r(2156);const y=r(1426);const B=r(8701);const Q=r(4123);const b=r(194);const w=r(1898);const S=r(6017);const v=r(5522);const R=r(7520);const k=r(5098);const D=r(3466);const N=r(1532);const T=r(9828);const O=r(6055);const _=r(2706);const M=r(579);const L=r(832);const F=r(4179);const U=r(2098);const P=r(420);const G=r(9380);const Y=r(3323);const V=r(7008);const W=r(5297);const J=r(7863);e.exports={parse:a,valid:A,clean:c,inc:l,diff:u,major:h,minor:d,patch:g,prerelease:p,compare:E,rcompare:m,compareLoose:C,compareBuild:I,sort:y,rsort:B,gt:Q,lt:b,eq:w,neq:S,gte:v,lte:R,cmp:k,coerce:D,Comparator:N,Range:T,satisfies:O,toComparators:_,maxSatisfying:M,minSatisfying:L,minVersion:F,validRange:U,outside:P,gtr:G,ltr:Y,intersects:V,simplifyRange:W,subset:J,SemVer:s,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},2293:e=>{const t="2.0.0";const r=256;const n=Number.MAX_SAFE_INTEGER||9007199254740991;const o=16;const s=r-6;const i=["major","premajor","minor","preminor","patch","prepatch","prerelease"];e.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:i,SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},427:e=>{const t=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},2463:e=>{const t=/^[0-9]+$/;const compareIdentifiers=(e,r)=>{const n=t.test(e);const o=t.test(r);if(n&&o){e=+e;r=+r}return e===r?0:n&&!o?-1:o&&!n?1:ecompareIdentifiers(t,e);e.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},5339:e=>{class LRUCache{constructor(){this.max=1e3;this.map=new Map}get(e){const t=this.map.get(e);if(t===undefined){return undefined}else{this.map.delete(e);this.map.set(e,t);return t}}delete(e){return this.map.delete(e)}set(e,t){const r=this.delete(e);if(!r&&t!==undefined){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}e.exports=LRUCache},785:e=>{const t=Object.freeze({loose:true});const r=Object.freeze({});const parseOptions=e=>{if(!e){return r}if(typeof e!=="object"){return t}return e};e.exports=parseOptions},9523:(e,t,r)=>{const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=r(2293);const i=r(427);t=e.exports={};const a=t.re=[];const A=t.safeRe=[];const c=t.src=[];const l=t.t={};let u=0;const h="[a-zA-Z0-9-]";const d=[["\\s",1],["\\d",s],[h,o]];const makeSafeRegex=e=>{for(const[t,r]of d){e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`)}return e};const createToken=(e,t,r)=>{const n=makeSafeRegex(t);const o=u++;i(e,o,t);l[e]=o;c[o]=t;a[o]=new RegExp(t,r?"g":undefined);A[o]=new RegExp(n,r?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`);createToken("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${h}+`);createToken("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`);createToken("FULL",`^${c[l.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`);createToken("LOOSE",`^${c[l.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${n}})`+`(?:\\.(\\d{1,${n}}))?`+`(?:\\.(\\d{1,${n}}))?`);createToken("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",c[l.COERCE],true);createToken("COERCERTLFULL",c[l.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,true);t.tildeTrimReplace="$1~";createToken("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,true);t.caretTrimReplace="$1^";createToken("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,true);t.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9380:(e,t,r)=>{const n=r(420);const gtr=(e,t,r)=>n(e,t,">",r);e.exports=gtr},7008:(e,t,r)=>{const n=r(9828);const intersects=(e,t,r)=>{e=new n(e,r);t=new n(t,r);return e.intersects(t,r)};e.exports=intersects},3323:(e,t,r)=>{const n=r(420);const ltr=(e,t,r)=>n(e,t,"<",r);e.exports=ltr},579:(e,t,r)=>{const n=r(8088);const o=r(9828);const maxSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===-1){s=e;i=new n(s,r)}}}));return s};e.exports=maxSatisfying},832:(e,t,r)=>{const n=r(8088);const o=r(9828);const minSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===1){s=e;i=new n(s,r)}}}));return s};e.exports=minSatisfying},4179:(e,t,r)=>{const n=r(8088);const o=r(9828);const s=r(4123);const minVersion=(e,t)=>{e=new o(e,t);let r=new n("0.0.0");if(e.test(r)){return r}r=new n("0.0.0-0");if(e.test(r)){return r}r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":if(t.prerelease.length===0){t.patch++}else{t.prerelease.push(0)}t.raw=t.format();case"":case">=":if(!i||s(t,i)){i=t}break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}));if(i&&(!r||s(r,i))){r=i}}if(r&&e.test(r)){return r}return null};e.exports=minVersion},420:(e,t,r)=>{const n=r(8088);const o=r(1532);const{ANY:s}=o;const i=r(9828);const a=r(6055);const A=r(4123);const c=r(194);const l=r(7520);const u=r(5522);const outside=(e,t,r,h)=>{e=new n(e,h);t=new i(t,h);let d,g,p,E,m;switch(r){case">":d=A;g=l;p=c;E=">";m=">=";break;case"<":d=c;g=u;p=A;E="<";m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(e,t,h)){return false}for(let r=0;r{if(e.semver===s){e=new o(">=0.0.0")}i=i||e;a=a||e;if(d(e.semver,i.semver,h)){i=e}else if(p(e.semver,a.semver,h)){a=e}}));if(i.operator===E||i.operator===m){return false}if((!a.operator||a.operator===E)&&g(e,a.semver)){return false}else if(a.operator===m&&p(e,a.semver)){return false}}return true};e.exports=outside},5297:(e,t,r)=>{const n=r(6055);const o=r(4309);e.exports=(e,t,r)=>{const s=[];let i=null;let a=null;const A=e.sort(((e,t)=>o(e,t,r)));for(const e of A){const o=n(e,t,r);if(o){a=e;if(!i){i=e}}else{if(a){s.push([i,a])}a=null;i=null}}if(i){s.push([i,null])}const c=[];for(const[e,t]of s){if(e===t){c.push(e)}else if(!t&&e===A[0]){c.push("*")}else if(!t){c.push(`>=${e}`)}else if(e===A[0]){c.push(`<=${t}`)}else{c.push(`${e} - ${t}`)}}const l=c.join(" || ");const u=typeof t.raw==="string"?t.raw:String(t);return l.length{const n=r(9828);const o=r(1532);const{ANY:s}=o;const i=r(6055);const a=r(4309);const subset=(e,t,r={})=>{if(e===t){return true}e=new n(e,r);t=new n(t,r);let o=false;e:for(const n of e.set){for(const e of t.set){const t=simpleSubset(n,e,r);o=o||t!==null;if(t){continue e}}if(o){return false}}return true};const A=[new o(">=0.0.0-0")];const c=[new o(">=0.0.0")];const simpleSubset=(e,t,r)=>{if(e===t){return true}if(e.length===1&&e[0].semver===s){if(t.length===1&&t[0].semver===s){return true}else if(r.includePrerelease){e=A}else{e=c}}if(t.length===1&&t[0].semver===s){if(r.includePrerelease){return true}else{t=c}}const n=new Set;let o,l;for(const t of e){if(t.operator===">"||t.operator===">="){o=higherGT(o,t,r)}else if(t.operator==="<"||t.operator==="<="){l=lowerLT(l,t,r)}else{n.add(t.semver)}}if(n.size>1){return null}let u;if(o&&l){u=a(o.semver,l.semver,r);if(u>0){return null}else if(u===0&&(o.operator!==">="||l.operator!=="<=")){return null}}for(const e of n){if(o&&!i(e,String(o),r)){return null}if(l&&!i(e,String(l),r)){return null}for(const n of t){if(!i(e,String(n),r)){return false}}return true}let h,d;let g,p;let E=l&&!r.includePrerelease&&l.semver.prerelease.length?l.semver:false;let m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:false;if(E&&E.prerelease.length===1&&l.operator==="<"&&E.prerelease[0]===0){E=false}for(const e of t){p=p||e.operator===">"||e.operator===">=";g=g||e.operator==="<"||e.operator==="<=";if(o){if(m){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===m.major&&e.semver.minor===m.minor&&e.semver.patch===m.patch){m=false}}if(e.operator===">"||e.operator===">="){h=higherGT(o,e,r);if(h===e&&h!==o){return false}}else if(o.operator===">="&&!i(o.semver,String(e),r)){return false}}if(l){if(E){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===E.major&&e.semver.minor===E.minor&&e.semver.patch===E.patch){E=false}}if(e.operator==="<"||e.operator==="<="){d=lowerLT(l,e,r);if(d===e&&d!==l){return false}}else if(l.operator==="<="&&!i(l.semver,String(e),r)){return false}}if(!e.operator&&(l||o)&&u!==0){return false}}if(o&&g&&!l&&u!==0){return false}if(l&&p&&!o&&u!==0){return false}if(m||E){return false}return true};const higherGT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e};const lowerLT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};e.exports=subset},2706:(e,t,r)=>{const n=r(9828);const toComparators=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")));e.exports=toComparators},2098:(e,t,r)=>{const n=r(9828);const validRange=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}};e.exports=validRange},1453:(e,t,r)=>{var n=r(1529);e.exports=Bitfield;function Bitfield(e){if(!(this instanceof Bitfield))return new Bitfield(e);if(!e)e={};if(Buffer.isBuffer(e))e={buffer:e};this.pageOffset=e.pageOffset||0;this.pageSize=e.pageSize||1024;this.pages=e.pages||n(this.pageSize);this.byteLength=this.pages.length*this.pageSize;this.length=8*this.byteLength;if(!powerOfTwo(this.pageSize))throw new Error("The page size should be a power of two");this._trackUpdates=!!e.trackUpdates;this._pageMask=this.pageSize-1;if(e.buffer){for(var t=0;t>t)};Bitfield.prototype.getByte=function(e){var t=e&this._pageMask;var r=(e-t)/this.pageSize;var n=this.pages.get(r,true);return n?n.buffer[t+this.pageOffset]:0};Bitfield.prototype.set=function(e,t){var r=e&7;var n=(e-r)/8;var o=this.getByte(n);return this.setByte(n,t?o|128>>r:o&(255^128>>r))};Bitfield.prototype.toBuffer=function(){var e=alloc(this.pages.length*this.pageSize);for(var t=0;t=this.byteLength){this.byteLength=e+1;this.length=this.byteLength*8}if(this._trackUpdates)this.pages.updated(o);return true};function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function powerOfTwo(e){return!(e&e-1)}},4841:(e,t,r)=>{"use strict";var n=r(1867).Buffer;var o=n.isEncoding||function(e){e=""+e;switch(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 true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){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=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var n=t.length-1;if(n=0){if(o>0)e.lastNeed=o-1;return o}if(--n=0){if(o>0)e.lastNeed=o-2;return o}if(--n=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},9318:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6224);const s=r(1621);const{env:i}=process;let a;if(s("no-color")||s("no-colors")||s("color=false")||s("color=never")){a=0}else if(s("color")||s("colors")||s("color=true")||s("color=always")){a=1}if("FORCE_COLOR"in i){if(i.FORCE_COLOR==="true"){a=1}else if(i.FORCE_COLOR==="false"){a=0}else{a=i.FORCE_COLOR.length===0?1:Math.min(parseInt(i.FORCE_COLOR,10),3)}}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e,t){if(a===0){return 0}if(s("color=16m")||s("color=full")||s("color=truecolor")){return 3}if(s("color=256")){return 2}if(e&&!t&&a===undefined){return 0}const r=a||0;if(i.TERM==="dumb"){return r}if(process.platform==="win32"){const e=n.release().split(".");if(Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in i){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||i.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in i){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0}if(i.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(i.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)){return 1}if("COLORTERM"in i){return 1}return r}function getSupportLevel(e){const t=supportsColor(e,e&&e.isTTY);return translateLevel(t)}e.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(true,o.isatty(1))),stderr:translateLevel(supportsColor(true,o.isatty(2)))}},7882:(e,t,r)=>{var n=r(3837);var o=r(336);var s=r(8860);var i=r(1642).Writable;var a=r(1642).PassThrough;var noop=function(){};var overflow=function(e){e&=511;return e&&512-e};var emptyStream=function(e,t){var r=new Source(e,t);r.end();return r};var mixinPax=function(e,t){if(t.path)e.name=t.path;if(t.linkpath)e.linkname=t.linkpath;if(t.size)e.size=parseInt(t.size,10);e.pax=t;return e};var Source=function(e,t){this._parent=e;this.offset=t;a.call(this,{autoDestroy:false})};n.inherits(Source,a);Source.prototype.destroy=function(e){this._parent.destroy(e)};var Extract=function(e){if(!(this instanceof Extract))return new Extract(e);i.call(this,e);e=e||{};this._offset=0;this._buffer=o();this._missing=0;this._partial=false;this._onparse=noop;this._header=null;this._stream=null;this._overflow=null;this._cb=null;this._locked=false;this._destroyed=false;this._pax=null;this._paxGlobal=null;this._gnuLongPath=null;this._gnuLongLinkPath=null;var t=this;var r=t._buffer;var oncontinue=function(){t._continue()};var onunlock=function(e){t._locked=false;if(e)return t.destroy(e);if(!t._stream)oncontinue()};var onstreamend=function(){t._stream=null;var e=overflow(t._header.size);if(e)t._parse(e,ondrain);else t._parse(512,onheader);if(!t._locked)oncontinue()};var ondrain=function(){t._buffer.consume(overflow(t._header.size));t._parse(512,onheader);oncontinue()};var onpaxglobalheader=function(){var e=t._header.size;t._paxGlobal=s.decodePax(r.slice(0,e));r.consume(e);onstreamend()};var onpaxheader=function(){var e=t._header.size;t._pax=s.decodePax(r.slice(0,e));if(t._paxGlobal)t._pax=Object.assign({},t._paxGlobal,t._pax);r.consume(e);onstreamend()};var ongnulongpath=function(){var n=t._header.size;this._gnuLongPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var ongnulonglinkpath=function(){var n=t._header.size;this._gnuLongLinkPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var onheader=function(){var n=t._offset;var o;try{o=t._header=s.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(e){t.emit("error",e)}r.consume(512);if(!o){t._parse(512,onheader);oncontinue();return}if(o.type==="gnu-long-path"){t._parse(o.size,ongnulongpath);oncontinue();return}if(o.type==="gnu-long-link-path"){t._parse(o.size,ongnulonglinkpath);oncontinue();return}if(o.type==="pax-global-header"){t._parse(o.size,onpaxglobalheader);oncontinue();return}if(o.type==="pax-header"){t._parse(o.size,onpaxheader);oncontinue();return}if(t._gnuLongPath){o.name=t._gnuLongPath;t._gnuLongPath=null}if(t._gnuLongLinkPath){o.linkname=t._gnuLongLinkPath;t._gnuLongLinkPath=null}if(t._pax){t._header=o=mixinPax(o,t._pax);t._pax=null}t._locked=true;if(!o.size||o.type==="directory"){t._parse(512,onheader);t.emit("entry",o,emptyStream(t,n),onunlock);return}t._stream=new Source(t,n);t.emit("entry",o,t._stream,onunlock);t._parse(o.size,onstreamend);oncontinue()};this._onheader=onheader;this._parse(512,onheader)};n.inherits(Extract,i);Extract.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream)this._stream.emit("close")};Extract.prototype._parse=function(e,t){if(this._destroyed)return;this._offset+=e;this._missing=e;if(t===this._onheader)this._partial=false;this._onparse=t};Extract.prototype._continue=function(){if(this._destroyed)return;var e=this._cb;this._cb=noop;if(this._overflow)this._write(this._overflow,undefined,e);else e()};Extract.prototype._write=function(e,t,r){if(this._destroyed)return;var n=this._stream;var o=this._buffer;var s=this._missing;if(e.length)this._partial=true;if(e.lengths){i=e.slice(s);e=e.slice(0,s)}if(n)n.end(e);else o.append(e);this._overflow=i;this._onparse()};Extract.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};e.exports=Extract},8860:(e,t)=>{var r=Buffer.alloc;var n="0000000000000000000";var o="7777777777777777777";var s="0".charCodeAt(0);var i=Buffer.from("ustar\0","binary");var a=Buffer.from("00","binary");var A=Buffer.from("ustar ","binary");var c=Buffer.from(" \0","binary");var l=parseInt("7777",8);var u=257;var h=263;var clamp=function(e,t,r){if(typeof e!=="number")return r;e=~~e;if(e>=t)return t;if(e>=0)return e;e+=t;if(e>=0)return e;return 0};var toType=function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null};var toTypeflag=function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0};var indexOf=function(e,t,r,n){for(;rt)return o.slice(0,t)+" ";else return n.slice(0,t-e.length)+e+" "};function parse256(e){var t;if(e[0]===128)t=true;else if(e[0]===255)t=false;else return null;var r=[];for(var n=e.length-1;n>0;n--){var o=e[n];if(t)r.push(o);else r.push(255-o)}var s=0;var i=r.length;for(n=0;n=Math.pow(10,r))r++;return t+r+e};t.decodeLongPath=function(e,t){return decodeStr(e,0,e.length,t)};t.encodePax=function(e){var t="";if(e.name)t+=addLength(" path="+e.name+"\n");if(e.linkname)t+=addLength(" linkpath="+e.linkname+"\n");var r=e.pax;if(r){for(var n in r){t+=addLength(" "+n+"="+r[n]+"\n")}}return Buffer.from(t)};t.decodePax=function(e){var t={};while(e.length){var r=0;while(r100){var A=n.indexOf("/");if(A===-1)return null;o+=o?"/"+n.slice(0,A):n.slice(0,A);n=n.slice(A+1)}if(Buffer.byteLength(n)>100||Buffer.byteLength(o)>155)return null;if(e.linkname&&Buffer.byteLength(e.linkname)>100)return null;t.write(n);t.write(encodeOct(e.mode&l,6),100);t.write(encodeOct(e.uid,6),108);t.write(encodeOct(e.gid,6),116);t.write(encodeOct(e.size,11),124);t.write(encodeOct(e.mtime.getTime()/1e3|0,11),136);t[156]=s+toTypeflag(e.type);if(e.linkname)t.write(e.linkname,157);i.copy(t,u);a.copy(t,h);if(e.uname)t.write(e.uname,265);if(e.gname)t.write(e.gname,297);t.write(encodeOct(e.devmajor||0,6),329);t.write(encodeOct(e.devminor||0,6),337);if(o)t.write(o,345);t.write(encodeOct(cksum(t),6),148);return t};t.decode=function(e,t,r){var n=e[156]===0?0:e[156]-s;var o=decodeStr(e,0,100,t);var a=decodeOct(e,100,8);var l=decodeOct(e,108,8);var d=decodeOct(e,116,8);var g=decodeOct(e,124,12);var p=decodeOct(e,136,12);var E=toType(n);var m=e[157]===0?null:decodeStr(e,157,100,t);var C=decodeStr(e,265,32);var I=decodeStr(e,297,32);var y=decodeOct(e,329,8);var B=decodeOct(e,337,8);var Q=cksum(e);if(Q===8*32)return null;if(Q!==decodeOct(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(i.compare(e,u,u+6)===0){if(e[345])o=decodeStr(e,345,155,t)+"/"+o}else if(A.compare(e,u,u+6)===0&&c.compare(e,h,h+2)===0){}else{if(!r){throw new Error("Invalid tar header: unknown format.")}}if(n===0&&o&&o[o.length-1]==="/")n=5;return{name:o,mode:a,uid:l,gid:d,size:g,mtime:new Date(1e3*p),type:E,linkname:m,uname:C,gname:I,devmajor:y,devminor:B}}},2283:(e,t,r)=>{t.extract=r(7882);t.pack=r(4930)},4930:(e,t,r)=>{var n=r(3186);var o=r(1205);var s=r(4124);var i=Buffer.alloc;var a=r(1642).Readable;var A=r(1642).Writable;var c=r(1576).StringDecoder;var l=r(8860);var u=parseInt("755",8);var h=parseInt("644",8);var d=i(1024);var noop=function(){};var overflow=function(e,t){t&=511;if(t)e.push(d.slice(0,512-t))};function modeToType(e){switch(e&n.S_IFMT){case n.S_IFBLK:return"block-device";case n.S_IFCHR:return"character-device";case n.S_IFDIR:return"directory";case n.S_IFIFO:return"fifo";case n.S_IFLNK:return"symlink"}return"file"}var Sink=function(e){A.call(this);this.written=0;this._to=e;this._destroyed=false};s(Sink,A);Sink.prototype._write=function(e,t,r){this.written+=e.length;if(this._to.push(e))return r();this._to._drain=r};Sink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var LinkSink=function(){A.call(this);this.linkname="";this._decoder=new c("utf-8");this._destroyed=false};s(LinkSink,A);LinkSink.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e);r()};LinkSink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Void=function(){A.call(this);this._destroyed=false};s(Void,A);Void.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Void.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Pack=function(e){if(!(this instanceof Pack))return new Pack(e);a.call(this,e);this._drain=noop;this._finalized=false;this._finalizing=false;this._destroyed=false;this._stream=null};s(Pack,a);Pack.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(this._finalized||this._destroyed)return;if(typeof t==="function"){r=t;t=null}if(!r)r=noop;var n=this;if(!e.size||e.type==="symlink")e.size=0;if(!e.type)e.type=modeToType(e.mode);if(!e.mode)e.mode=e.type==="directory"?u:h;if(!e.uid)e.uid=0;if(!e.gid)e.gid=0;if(!e.mtime)e.mtime=new Date;if(typeof t==="string")t=Buffer.from(t);if(Buffer.isBuffer(t)){e.size=t.length;this._encode(e);var s=this.push(t);overflow(n,e.size);if(s)process.nextTick(r);else this._drain=r;return new Void}if(e.type==="symlink"&&!e.linkname){var i=new LinkSink;o(i,(function(t){if(t){n.destroy();return r(t)}e.linkname=i.linkname;n._encode(e);r()}));return i}this._encode(e);if(e.type!=="file"&&e.type!=="contiguous-file"){process.nextTick(r);return new Void}var a=new Sink(this);this._stream=a;o(a,(function(t){n._stream=null;if(t){n.destroy();return r(t)}if(a.written!==e.size){n.destroy();return r(new Error("size mismatch"))}overflow(n,e.size);if(n._finalizing)n.finalize();r()}));return a};Pack.prototype.finalize=function(){if(this._stream){this._finalizing=true;return}if(this._finalized)return;this._finalized=true;this.push(d);this.push(null)};Pack.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream&&this._stream.destroy)this._stream.destroy()};Pack.prototype._encode=function(e){if(!e.pax){var t=l.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Pack.prototype._encodePax=function(e){var t=l.encodePax({name:e.name,linkname:e.linkname,pax:e.pax});var r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(l.encode(r));this.push(t);overflow(this,t.length);r.size=e.size;r.type=e.type;this.push(l.encode(r))};Pack.prototype._read=function(e){var t=this._drain;this._drain=noop;t()};e.exports=Pack},8517:(e,t,r)=>{ +(()=>{var __webpack_modules__={924:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};var o=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function verb(e){return function(t){return step([e,t])}}function step(i){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,o&&(s=i[0]&2?o["return"]:i[0]?o["throw"]||((s=o["return"])&&s.call(o),0):o.next)&&!(s=s.call(o,i[1])).done)return s;if(o=0,s)i=[i[0]&2,s.value];switch(i[0]){case 0:case 1:s=i;break;case 4:r.label++;return{value:i[1],done:false};case 5:r.label++;o=i[1];i=[0];continue;case 7:i=r.ops.pop();r.trys.pop();continue;default:if(!(s=r.trys,s=s.length>0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0&&s[s.length-1])&&(i[0]===6||i[0]===2)){r=0;continue}if(i[0]===3&&(!s||i[1]>s[0]&&i[1]0){e+=" ";let t=true;for(const r in this.properties){if(this.properties.hasOwnProperty(r)){const n=this.properties[r];if(n){if(t){t=false}else{e+=","}e+=`${r}=${escapeProperty(n)}`}}}}e+=`${A}${escapeData(this.message)}`;return e}}function escapeData(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return a.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},2186:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.getIDToken=t.getState=t.saveState=t.group=t.endGroup=t.startGroup=t.info=t.notice=t.warning=t.error=t.debug=t.isDebug=t.setFailed=t.setCommandEcho=t.setOutput=t.getBooleanInput=t.getMultilineInput=t.getInput=t.addPath=t.setSecret=t.exportVariable=t.ExitCode=void 0;const a=r(7351);const A=r(717);const c=r(6321);const l=s(r(2037));const u=s(r(1017));const h=r(8041);var d;(function(e){e[e["Success"]=0]="Success";e[e["Failure"]=1]="Failure"})(d=t.ExitCode||(t.ExitCode={}));function exportVariable(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env["GITHUB_ENV"]||"";if(n){return A.issueFileCommand("ENV",A.prepareKeyValueMessage(e,t))}a.issueCommand("set-env",{name:e},r)}t.exportVariable=exportVariable;function setSecret(e){a.issueCommand("add-mask",{},e)}t.setSecret=setSecret;function addPath(e){const t=process.env["GITHUB_PATH"]||"";if(t){A.issueFileCommand("PATH",e)}else{a.issueCommand("add-path",{},e)}process.env["PATH"]=`${e}${u.delimiter}${process.env["PATH"]}`}t.addPath=addPath;function getInput(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r){throw new Error(`Input required and not supplied: ${e}`)}if(t&&t.trimWhitespace===false){return r}return r.trim()}t.getInput=getInput;function getMultilineInput(e,t){const r=getInput(e,t).split("\n").filter((e=>e!==""));if(t&&t.trimWhitespace===false){return r}return r.map((e=>e.trim()))}t.getMultilineInput=getMultilineInput;function getBooleanInput(e,t){const r=["true","True","TRUE"];const n=["false","False","FALSE"];const o=getInput(e,t);if(r.includes(o))return true;if(n.includes(o))return false;throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${e}\n`+`Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}t.getBooleanInput=getBooleanInput;function setOutput(e,t){const r=process.env["GITHUB_OUTPUT"]||"";if(r){return A.issueFileCommand("OUTPUT",A.prepareKeyValueMessage(e,t))}process.stdout.write(l.EOL);a.issueCommand("set-output",{name:e},c.toCommandValue(t))}t.setOutput=setOutput;function setCommandEcho(e){a.issue("echo",e?"on":"off")}t.setCommandEcho=setCommandEcho;function setFailed(e){process.exitCode=d.Failure;error(e)}t.setFailed=setFailed;function isDebug(){return process.env["RUNNER_DEBUG"]==="1"}t.isDebug=isDebug;function debug(e){a.issueCommand("debug",{},e)}t.debug=debug;function error(e,t={}){a.issueCommand("error",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.error=error;function warning(e,t={}){a.issueCommand("warning",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.warning=warning;function notice(e,t={}){a.issueCommand("notice",c.toCommandProperties(t),e instanceof Error?e.toString():e)}t.notice=notice;function info(e){process.stdout.write(e+l.EOL)}t.info=info;function startGroup(e){a.issue("group",e)}t.startGroup=startGroup;function endGroup(){a.issue("endgroup")}t.endGroup=endGroup;function group(e,t){return i(this,void 0,void 0,(function*(){startGroup(e);let r;try{r=yield t()}finally{endGroup()}return r}))}t.group=group;function saveState(e,t){const r=process.env["GITHUB_STATE"]||"";if(r){return A.issueFileCommand("STATE",A.prepareKeyValueMessage(e,t))}a.issueCommand("save-state",{name:e},c.toCommandValue(t))}t.saveState=saveState;function getState(e){return process.env[`STATE_${e}`]||""}t.getState=getState;function getIDToken(e){return i(this,void 0,void 0,(function*(){return yield h.OidcClient.getIDToken(e)}))}t.getIDToken=getIDToken;var g=r(1327);Object.defineProperty(t,"summary",{enumerable:true,get:function(){return g.summary}});var p=r(1327);Object.defineProperty(t,"markdownSummary",{enumerable:true,get:function(){return p.markdownSummary}});var E=r(2981);Object.defineProperty(t,"toPosixPath",{enumerable:true,get:function(){return E.toPosixPath}});Object.defineProperty(t,"toWin32Path",{enumerable:true,get:function(){return E.toWin32Path}});Object.defineProperty(t,"toPlatformPath",{enumerable:true,get:function(){return E.toPlatformPath}})},717:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.prepareKeyValueMessage=t.issueFileCommand=void 0;const i=s(r(7147));const a=s(r(2037));const A=r(5840);const c=r(6321);function issueFileCommand(e,t){const r=process.env[`GITHUB_${e}`];if(!r){throw new Error(`Unable to find environment variable for file command ${e}`)}if(!i.existsSync(r)){throw new Error(`Missing file at path: ${r}`)}i.appendFileSync(r,`${c.toCommandValue(t)}${a.EOL}`,{encoding:"utf8"})}t.issueFileCommand=issueFileCommand;function prepareKeyValueMessage(e,t){const r=`ghadelimiter_${A.v4()}`;const n=c.toCommandValue(t);if(e.includes(r)){throw new Error(`Unexpected input: name should not contain the delimiter "${r}"`)}if(n.includes(r)){throw new Error(`Unexpected input: value should not contain the delimiter "${r}"`)}return`${e}<<${r}${a.EOL}${n}${a.EOL}${r}`}t.prepareKeyValueMessage=prepareKeyValueMessage},8041:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.OidcClient=void 0;const o=r(6255);const s=r(5526);const i=r(2186);class OidcClient{static createHttpClient(e=true,t=10){const r={allowRetries:e,maxRetries:t};return new o.HttpClient("actions/oidc-client",[new s.BearerCredentialHandler(OidcClient.getRequestToken())],r)}static getRequestToken(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable")}return e}static getIDTokenUrl(){const e=process.env["ACTIONS_ID_TOKEN_REQUEST_URL"];if(!e){throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable")}return e}static getCall(e){var t;return n(this,void 0,void 0,(function*(){const r=OidcClient.createHttpClient();const n=yield r.getJson(e).catch((e=>{throw new Error(`Failed to get ID Token. \n \n Error Code : ${e.statusCode}\n \n Error Message: ${e.message}`)}));const o=(t=n.result)===null||t===void 0?void 0:t.value;if(!o){throw new Error("Response json body do not have ID Token field")}return o}))}static getIDToken(e){return n(this,void 0,void 0,(function*(){try{let t=OidcClient.getIDTokenUrl();if(e){const r=encodeURIComponent(e);t=`${t}&audience=${r}`}i.debug(`ID token url is ${t}`);const r=yield OidcClient.getCall(t);i.setSecret(r);return r}catch(e){throw new Error(`Error message: ${e.message}`)}}))}}t.OidcClient=OidcClient},2981:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};Object.defineProperty(t,"__esModule",{value:true});t.toPlatformPath=t.toWin32Path=t.toPosixPath=void 0;const i=s(r(1017));function toPosixPath(e){return e.replace(/[\\]/g,"/")}t.toPosixPath=toPosixPath;function toWin32Path(e){return e.replace(/[/]/g,"\\")}t.toWin32Path=toWin32Path;function toPlatformPath(e){return e.replace(/[/\\]/g,i.sep)}t.toPlatformPath=toPlatformPath},1327:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.summary=t.markdownSummary=t.SUMMARY_DOCS_URL=t.SUMMARY_ENV_VAR=void 0;const o=r(2037);const s=r(7147);const{access:i,appendFile:a,writeFile:A}=s.promises;t.SUMMARY_ENV_VAR="GITHUB_STEP_SUMMARY";t.SUMMARY_DOCS_URL="https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";class Summary{constructor(){this._buffer=""}filePath(){return n(this,void 0,void 0,(function*(){if(this._filePath){return this._filePath}const e=process.env[t.SUMMARY_ENV_VAR];if(!e){throw new Error(`Unable to find environment variable for $${t.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`)}try{yield i(e,s.constants.R_OK|s.constants.W_OK)}catch(t){throw new Error(`Unable to access summary file: '${e}'. Check if the file has correct read/write permissions.`)}this._filePath=e;return this._filePath}))}wrap(e,t,r={}){const n=Object.entries(r).map((([e,t])=>` ${e}="${t}"`)).join("");if(!t){return`<${e}${n}>`}return`<${e}${n}>${t}`}write(e){return n(this,void 0,void 0,(function*(){const t=!!(e===null||e===void 0?void 0:e.overwrite);const r=yield this.filePath();const n=t?A:a;yield n(r,this._buffer,{encoding:"utf8"});return this.emptyBuffer()}))}clear(){return n(this,void 0,void 0,(function*(){return this.emptyBuffer().write({overwrite:true})}))}stringify(){return this._buffer}isEmptyBuffer(){return this._buffer.length===0}emptyBuffer(){this._buffer="";return this}addRaw(e,t=false){this._buffer+=e;return t?this.addEOL():this}addEOL(){return this.addRaw(o.EOL)}addCodeBlock(e,t){const r=Object.assign({},t&&{lang:t});const n=this.wrap("pre",this.wrap("code",e),r);return this.addRaw(n).addEOL()}addList(e,t=false){const r=t?"ol":"ul";const n=e.map((e=>this.wrap("li",e))).join("");const o=this.wrap(r,n);return this.addRaw(o).addEOL()}addTable(e){const t=e.map((e=>{const t=e.map((e=>{if(typeof e==="string"){return this.wrap("td",e)}const{header:t,data:r,colspan:n,rowspan:o}=e;const s=t?"th":"td";const i=Object.assign(Object.assign({},n&&{colspan:n}),o&&{rowspan:o});return this.wrap(s,r,i)})).join("");return this.wrap("tr",t)})).join("");const r=this.wrap("table",t);return this.addRaw(r).addEOL()}addDetails(e,t){const r=this.wrap("details",this.wrap("summary",e)+t);return this.addRaw(r).addEOL()}addImage(e,t,r){const{width:n,height:o}=r||{};const s=Object.assign(Object.assign({},n&&{width:n}),o&&{height:o});const i=this.wrap("img",null,Object.assign({src:e,alt:t},s));return this.addRaw(i).addEOL()}addHeading(e,t){const r=`h${t}`;const n=["h1","h2","h3","h4","h5","h6"].includes(r)?r:"h1";const o=this.wrap(n,e);return this.addRaw(o).addEOL()}addSeparator(){const e=this.wrap("hr",null);return this.addRaw(e).addEOL()}addBreak(){const e=this.wrap("br",null);return this.addRaw(e).addEOL()}addQuote(e,t){const r=Object.assign({},t&&{cite:t});const n=this.wrap("blockquote",e,r);return this.addRaw(n).addEOL()}addLink(e,t){const r=this.wrap("a",e,{href:t});return this.addRaw(r).addEOL()}}const c=new Summary;t.markdownSummary=c;t.summary=c},6321:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.toCommandProperties=t.toCommandValue=void 0;function toCommandValue(e){if(e===null||e===undefined){return""}else if(typeof e==="string"||e instanceof String){return e}return JSON.stringify(e)}t.toCommandValue=toCommandValue;function toCommandProperties(e){if(!Object.keys(e).length){return{}}return{title:e.title,file:e.file,line:e.startLine,endLine:e.endLine,col:e.startColumn,endColumn:e.endColumn}}t.toCommandProperties=toCommandProperties},5526:function(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.PersonalAccessTokenCredentialHandler=t.BearerCredentialHandler=t.BasicCredentialHandler=void 0;class BasicCredentialHandler{constructor(e,t){this.username=e;this.password=t}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`${this.username}:${this.password}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BasicCredentialHandler=BasicCredentialHandler;class BearerCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Bearer ${this.token}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.BearerCredentialHandler=BearerCredentialHandler;class PersonalAccessTokenCredentialHandler{constructor(e){this.token=e}prepareRequest(e){if(!e.headers){throw Error("The request has no headers")}e.headers["Authorization"]=`Basic ${Buffer.from(`PAT:${this.token}`).toString("base64")}`}canHandleAuthentication(){return false}handleAuthentication(){return r(this,void 0,void 0,(function*(){throw new Error("not implemented")}))}}t.PersonalAccessTokenCredentialHandler=PersonalAccessTokenCredentialHandler},6255:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable)){o={enumerable:true,get:function(){return t[r]}}}Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))n(t,e,r);o(t,e);return t};var i=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(n.next(e))}catch(e){o(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:true});t.HttpClient=t.isHttps=t.HttpClientResponse=t.HttpClientError=t.getProxyUrl=t.MediaTypes=t.Headers=t.HttpCodes=void 0;const a=s(r(3685));const A=s(r(5687));const c=s(r(9835));const l=s(r(4294));const u=r(1773);var h;(function(e){e[e["OK"]=200]="OK";e[e["MultipleChoices"]=300]="MultipleChoices";e[e["MovedPermanently"]=301]="MovedPermanently";e[e["ResourceMoved"]=302]="ResourceMoved";e[e["SeeOther"]=303]="SeeOther";e[e["NotModified"]=304]="NotModified";e[e["UseProxy"]=305]="UseProxy";e[e["SwitchProxy"]=306]="SwitchProxy";e[e["TemporaryRedirect"]=307]="TemporaryRedirect";e[e["PermanentRedirect"]=308]="PermanentRedirect";e[e["BadRequest"]=400]="BadRequest";e[e["Unauthorized"]=401]="Unauthorized";e[e["PaymentRequired"]=402]="PaymentRequired";e[e["Forbidden"]=403]="Forbidden";e[e["NotFound"]=404]="NotFound";e[e["MethodNotAllowed"]=405]="MethodNotAllowed";e[e["NotAcceptable"]=406]="NotAcceptable";e[e["ProxyAuthenticationRequired"]=407]="ProxyAuthenticationRequired";e[e["RequestTimeout"]=408]="RequestTimeout";e[e["Conflict"]=409]="Conflict";e[e["Gone"]=410]="Gone";e[e["TooManyRequests"]=429]="TooManyRequests";e[e["InternalServerError"]=500]="InternalServerError";e[e["NotImplemented"]=501]="NotImplemented";e[e["BadGateway"]=502]="BadGateway";e[e["ServiceUnavailable"]=503]="ServiceUnavailable";e[e["GatewayTimeout"]=504]="GatewayTimeout"})(h||(t.HttpCodes=h={}));var d;(function(e){e["Accept"]="accept";e["ContentType"]="content-type"})(d||(t.Headers=d={}));var g;(function(e){e["ApplicationJson"]="application/json"})(g||(t.MediaTypes=g={}));function getProxyUrl(e){const t=c.getProxyUrl(new URL(e));return t?t.href:""}t.getProxyUrl=getProxyUrl;const p=[h.MovedPermanently,h.ResourceMoved,h.SeeOther,h.TemporaryRedirect,h.PermanentRedirect];const E=[h.BadGateway,h.ServiceUnavailable,h.GatewayTimeout];const m=["OPTIONS","GET","DELETE","HEAD"];const C=10;const I=5;class HttpClientError extends Error{constructor(e,t){super(e);this.name="HttpClientError";this.statusCode=t;Object.setPrototypeOf(this,HttpClientError.prototype)}}t.HttpClientError=HttpClientError;class HttpClientResponse{constructor(e){this.message=e}readBody(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){let t=Buffer.alloc(0);this.message.on("data",(e=>{t=Buffer.concat([t,e])}));this.message.on("end",(()=>{e(t.toString())}))}))))}))}readBodyBuffer(){return i(this,void 0,void 0,(function*(){return new Promise((e=>i(this,void 0,void 0,(function*(){const t=[];this.message.on("data",(e=>{t.push(e)}));this.message.on("end",(()=>{e(Buffer.concat(t))}))}))))}))}}t.HttpClientResponse=HttpClientResponse;function isHttps(e){const t=new URL(e);return t.protocol==="https:"}t.isHttps=isHttps;class HttpClient{constructor(e,t,r){this._ignoreSslError=false;this._allowRedirects=true;this._allowRedirectDowngrade=false;this._maxRedirects=50;this._allowRetries=false;this._maxRetries=1;this._keepAlive=false;this._disposed=false;this.userAgent=e;this.handlers=t||[];this.requestOptions=r;if(r){if(r.ignoreSslError!=null){this._ignoreSslError=r.ignoreSslError}this._socketTimeout=r.socketTimeout;if(r.allowRedirects!=null){this._allowRedirects=r.allowRedirects}if(r.allowRedirectDowngrade!=null){this._allowRedirectDowngrade=r.allowRedirectDowngrade}if(r.maxRedirects!=null){this._maxRedirects=Math.max(r.maxRedirects,0)}if(r.keepAlive!=null){this._keepAlive=r.keepAlive}if(r.allowRetries!=null){this._allowRetries=r.allowRetries}if(r.maxRetries!=null){this._maxRetries=r.maxRetries}}}options(e,t){return i(this,void 0,void 0,(function*(){return this.request("OPTIONS",e,null,t||{})}))}get(e,t){return i(this,void 0,void 0,(function*(){return this.request("GET",e,null,t||{})}))}del(e,t){return i(this,void 0,void 0,(function*(){return this.request("DELETE",e,null,t||{})}))}post(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("POST",e,t,r||{})}))}patch(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PATCH",e,t,r||{})}))}put(e,t,r){return i(this,void 0,void 0,(function*(){return this.request("PUT",e,t,r||{})}))}head(e,t){return i(this,void 0,void 0,(function*(){return this.request("HEAD",e,null,t||{})}))}sendStream(e,t,r,n){return i(this,void 0,void 0,(function*(){return this.request(e,t,r,n)}))}getJson(e,t={}){return i(this,void 0,void 0,(function*(){t[d.Accept]=this._getExistingOrDefaultHeader(t,d.Accept,g.ApplicationJson);const r=yield this.get(e,t);return this._processResponse(r,this.requestOptions)}))}postJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.post(e,n,r);return this._processResponse(o,this.requestOptions)}))}putJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.put(e,n,r);return this._processResponse(o,this.requestOptions)}))}patchJson(e,t,r={}){return i(this,void 0,void 0,(function*(){const n=JSON.stringify(t,null,2);r[d.Accept]=this._getExistingOrDefaultHeader(r,d.Accept,g.ApplicationJson);r[d.ContentType]=this._getExistingOrDefaultHeader(r,d.ContentType,g.ApplicationJson);const o=yield this.patch(e,n,r);return this._processResponse(o,this.requestOptions)}))}request(e,t,r,n){return i(this,void 0,void 0,(function*(){if(this._disposed){throw new Error("Client has already been disposed.")}const o=new URL(t);let s=this._prepareRequest(e,o,n);const i=this._allowRetries&&m.includes(e)?this._maxRetries+1:1;let a=0;let A;do{A=yield this.requestRaw(s,r);if(A&&A.message&&A.message.statusCode===h.Unauthorized){let e;for(const t of this.handlers){if(t.canHandleAuthentication(A)){e=t;break}}if(e){return e.handleAuthentication(this,s,r)}else{return A}}let t=this._maxRedirects;while(A.message.statusCode&&p.includes(A.message.statusCode)&&this._allowRedirects&&t>0){const i=A.message.headers["location"];if(!i){break}const a=new URL(i);if(o.protocol==="https:"&&o.protocol!==a.protocol&&!this._allowRedirectDowngrade){throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.")}yield A.readBody();if(a.hostname!==o.hostname){for(const e in n){if(e.toLowerCase()==="authorization"){delete n[e]}}}s=this._prepareRequest(e,a,n);A=yield this.requestRaw(s,r);t--}if(!A.message.statusCode||!E.includes(A.message.statusCode)){return A}a+=1;if(a{function callbackForResult(e,t){if(e){n(e)}else if(!t){n(new Error("Unknown error"))}else{r(t)}}this.requestRawWithCallback(e,t,callbackForResult)}))}))}requestRawWithCallback(e,t,r){if(typeof t==="string"){if(!e.options.headers){e.options.headers={}}e.options.headers["Content-Length"]=Buffer.byteLength(t,"utf8")}let n=false;function handleResult(e,t){if(!n){n=true;r(e,t)}}const o=e.httpModule.request(e.options,(e=>{const t=new HttpClientResponse(e);handleResult(undefined,t)}));let s;o.on("socket",(e=>{s=e}));o.setTimeout(this._socketTimeout||3*6e4,(()=>{if(s){s.end()}handleResult(new Error(`Request timeout: ${e.options.path}`))}));o.on("error",(function(e){handleResult(e)}));if(t&&typeof t==="string"){o.write(t,"utf8")}if(t&&typeof t!=="string"){t.on("close",(function(){o.end()}));t.pipe(o)}else{o.end()}}getAgent(e){const t=new URL(e);return this._getAgent(t)}getAgentDispatcher(e){const t=new URL(e);const r=c.getProxyUrl(t);const n=r&&r.hostname;if(!n){return}return this._getProxyAgentDispatcher(t,r)}_prepareRequest(e,t,r){const n={};n.parsedUrl=t;const o=n.parsedUrl.protocol==="https:";n.httpModule=o?A:a;const s=o?443:80;n.options={};n.options.host=n.parsedUrl.hostname;n.options.port=n.parsedUrl.port?parseInt(n.parsedUrl.port):s;n.options.path=(n.parsedUrl.pathname||"")+(n.parsedUrl.search||"");n.options.method=e;n.options.headers=this._mergeHeaders(r);if(this.userAgent!=null){n.options.headers["user-agent"]=this.userAgent}n.options.agent=this._getAgent(n.parsedUrl);if(this.handlers){for(const e of this.handlers){e.prepareRequest(n.options)}}return n}_mergeHeaders(e){if(this.requestOptions&&this.requestOptions.headers){return Object.assign({},lowercaseKeys(this.requestOptions.headers),lowercaseKeys(e||{}))}return lowercaseKeys(e||{})}_getExistingOrDefaultHeader(e,t,r){let n;if(this.requestOptions&&this.requestOptions.headers){n=lowercaseKeys(this.requestOptions.headers)[t]}return e[t]||n||r}_getAgent(e){let t;const r=c.getProxyUrl(e);const n=r&&r.hostname;if(this._keepAlive&&n){t=this._proxyAgent}if(!n){t=this._agent}if(t){return t}const o=e.protocol==="https:";let s=100;if(this.requestOptions){s=this.requestOptions.maxSockets||a.globalAgent.maxSockets}if(r&&r.hostname){const e={maxSockets:s,keepAlive:this._keepAlive,proxy:Object.assign(Object.assign({},(r.username||r.password)&&{proxyAuth:`${r.username}:${r.password}`}),{host:r.hostname,port:r.port})};let n;const i=r.protocol==="https:";if(o){n=i?l.httpsOverHttps:l.httpsOverHttp}else{n=i?l.httpOverHttps:l.httpOverHttp}t=n(e);this._proxyAgent=t}if(!t){const e={keepAlive:this._keepAlive,maxSockets:s};t=o?new A.Agent(e):new a.Agent(e);this._agent=t}if(o&&this._ignoreSslError){t.options=Object.assign(t.options||{},{rejectUnauthorized:false})}return t}_getProxyAgentDispatcher(e,t){let r;if(this._keepAlive){r=this._proxyAgentDispatcher}if(r){return r}const n=e.protocol==="https:";r=new u.ProxyAgent(Object.assign({uri:t.href,pipelining:!this._keepAlive?0:1},(t.username||t.password)&&{token:`${t.username}:${t.password}`}));this._proxyAgentDispatcher=r;if(n&&this._ignoreSslError){r.options=Object.assign(r.options.requestTls||{},{rejectUnauthorized:false})}return r}_performExponentialBackoff(e){return i(this,void 0,void 0,(function*(){e=Math.min(C,e);const t=I*Math.pow(2,e);return new Promise((e=>setTimeout((()=>e()),t)))}))}_processResponse(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((r,n)=>i(this,void 0,void 0,(function*(){const o=e.message.statusCode||0;const s={statusCode:o,result:null,headers:{}};if(o===h.NotFound){r(s)}function dateTimeDeserializer(e,t){if(typeof t==="string"){const e=new Date(t);if(!isNaN(e.valueOf())){return e}}return t}let i;let a;try{a=yield e.readBody();if(a&&a.length>0){if(t&&t.deserializeDates){i=JSON.parse(a,dateTimeDeserializer)}else{i=JSON.parse(a)}s.result=i}s.headers=e.message.headers}catch(e){}if(o>299){let e;if(i&&i.message){e=i.message}else if(a&&a.length>0){e=a}else{e=`Failed request: (${o})`}const t=new HttpClientError(e,o);t.result=s.result;n(t)}else{r(s)}}))))}))}}t.HttpClient=HttpClient;const lowercaseKeys=e=>Object.keys(e).reduce(((t,r)=>(t[r.toLowerCase()]=e[r],t)),{})},9835:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.checkBypass=t.getProxyUrl=void 0;function getProxyUrl(e){const t=e.protocol==="https:";if(checkBypass(e)){return undefined}const r=(()=>{if(t){return process.env["https_proxy"]||process.env["HTTPS_PROXY"]}else{return process.env["http_proxy"]||process.env["HTTP_PROXY"]}})();if(r){try{return new URL(r)}catch(e){if(!r.startsWith("http://")&&!r.startsWith("https://"))return new URL(`http://${r}`)}}else{return undefined}}t.getProxyUrl=getProxyUrl;function checkBypass(e){if(!e.hostname){return false}const t=e.hostname;if(isLoopbackAddress(t)){return true}const r=process.env["no_proxy"]||process.env["NO_PROXY"]||"";if(!r){return false}let n;if(e.port){n=Number(e.port)}else if(e.protocol==="http:"){n=80}else if(e.protocol==="https:"){n=443}const o=[e.hostname.toUpperCase()];if(typeof n==="number"){o.push(`${o[0]}:${n}`)}for(const e of r.split(",").map((e=>e.trim().toUpperCase())).filter((e=>e))){if(e==="*"||o.some((t=>t===e||t.endsWith(`.${e}`)||e.startsWith(".")&&t.endsWith(`${e}`)))){return true}}return false}t.checkBypass=checkBypass;function isLoopbackAddress(e){const t=e.toLowerCase();return t==="localhost"||t.startsWith("127.")||t.startsWith("[::1]")||t.startsWith("[0:0:0:0:0:0:0:1]")}},9690:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=r(2361);const s=n(r(8237));const i=n(r(6570));const a=s.default("agent-base");function isAgent(e){return Boolean(e)&&typeof e.addRequest==="function"}function isSecureEndpoint(){const{stack:e}=new Error;if(typeof e!=="string")return false;return e.split("\n").some((e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1))}function createAgent(e,t){return new createAgent.Agent(e,t)}(function(e){class Agent extends o.EventEmitter{constructor(e,t){super();let r=t;if(typeof e==="function"){this.callback=e}else if(e){r=e}this.timeout=null;if(r&&typeof r.timeout==="number"){this.timeout=r.timeout}this.maxFreeSockets=1;this.maxSockets=1;this.maxTotalSockets=Infinity;this.sockets={};this.freeSockets={};this.requests={};this.options={}}get defaultPort(){if(typeof this.explicitDefaultPort==="number"){return this.explicitDefaultPort}return isSecureEndpoint()?443:80}set defaultPort(e){this.explicitDefaultPort=e}get protocol(){if(typeof this.explicitProtocol==="string"){return this.explicitProtocol}return isSecureEndpoint()?"https:":"http:"}set protocol(e){this.explicitProtocol=e}callback(e,t,r){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(e,t){const r=Object.assign({},t);if(typeof r.secureEndpoint!=="boolean"){r.secureEndpoint=isSecureEndpoint()}if(r.host==null){r.host="localhost"}if(r.port==null){r.port=r.secureEndpoint?443:80}if(r.protocol==null){r.protocol=r.secureEndpoint?"https:":"http:"}if(r.host&&r.path){delete r.path}delete r.agent;delete r.hostname;delete r._defaultAgent;delete r.defaultPort;delete r.createConnection;e._last=true;e.shouldKeepAlive=false;let n=false;let o=null;const s=r.timeout||this.timeout;const onerror=t=>{if(e._hadError)return;e.emit("error",t);e._hadError=true};const ontimeout=()=>{o=null;n=true;const e=new Error(`A "socket" was not created for HTTP request before ${s}ms`);e.code="ETIMEOUT";onerror(e)};const callbackError=e=>{if(n)return;if(o!==null){clearTimeout(o);o=null}onerror(e)};const onsocket=t=>{if(n)return;if(o!=null){clearTimeout(o);o=null}if(isAgent(t)){a("Callback returned another Agent instance %o",t.constructor.name);t.addRequest(e,r);return}if(t){t.once("free",(()=>{this.freeSocket(t,r)}));e.onSocket(t);return}const s=new Error(`no Duplex stream was returned to agent-base for \`${e.method} ${e.path}\``);onerror(s)};if(typeof this.callback!=="function"){onerror(new Error("`callback` is not defined"));return}if(!this.promisifiedCallback){if(this.callback.length>=3){a("Converting legacy callback function to promise");this.promisifiedCallback=i.default(this.callback)}else{this.promisifiedCallback=this.callback}}if(typeof s==="number"&&s>0){o=setTimeout(ontimeout,s)}if("port"in r&&typeof r.port!=="number"){r.port=Number(r.port)}try{a("Resolving socket for %o request: %o",r.protocol,`${e.method} ${e.path}`);Promise.resolve(this.promisifiedCallback(e,r)).then(onsocket,callbackError)}catch(e){Promise.reject(e).catch(callbackError)}}freeSocket(e,t){a("Freeing socket %o %o",e.constructor.name,t);e.destroy()}destroy(){a("Destroying agent %o",this.constructor.name)}}e.Agent=Agent;e.prototype=e.Agent.prototype})(createAgent||(createAgent={}));e.exports=createAgent},6570:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function promisify(e){return function(t,r){return new Promise(((n,o)=>{e.call(this,t,r,((e,t)=>{if(e){o(e)}else{n(t)}}))}))}}t["default"]=promisify},4855:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6006);var s=function(){function Mutex(e){this._semaphore=new o.default(1,e)}Mutex.prototype.acquire=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,n.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._semaphore.acquire()];case 1:e=r.sent(),t=e[1];return[2,t]}}))}))};Mutex.prototype.runExclusive=function(e){return this._semaphore.runExclusive((function(){return e()}))};Mutex.prototype.isLocked=function(){return this._semaphore.isLocked()};Mutex.prototype.waitForUnlock=function(){return this._semaphore.waitForUnlock()};Mutex.prototype.release=function(){this._semaphore.release()};Mutex.prototype.cancel=function(){return this._semaphore.cancel()};return Mutex}();t["default"]=s},6006:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(4351);var o=r(6984);var s=function(){function Semaphore(e,t){if(t===void 0){t=o.E_CANCELED}this._maxConcurrency=e;this._cancelError=t;this._queue=[];this._waiters=[];if(e<=0){throw new Error("semaphore must be initialized to a positive value")}this._value=e}Semaphore.prototype.acquire=function(){var e=this;var t=this.isLocked();var r=new Promise((function(t,r){return e._queue.push({resolve:t,reject:r})}));if(!t)this._dispatch();return r};Semaphore.prototype.runExclusive=function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r,o;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.acquire()];case 1:t=n.sent(),r=t[0],o=t[1];n.label=2;case 2:n.trys.push([2,,4,5]);return[4,e(r)];case 3:return[2,n.sent()];case 4:o();return[7];case 5:return[2]}}))}))};Semaphore.prototype.waitForUnlock=function(){return(0,n.__awaiter)(this,void 0,void 0,(function(){var e;var t=this;return(0,n.__generator)(this,(function(r){if(!this.isLocked()){return[2,Promise.resolve()]}e=new Promise((function(e){return t._waiters.push({resolve:e})}));return[2,e]}))}))};Semaphore.prototype.isLocked=function(){return this._value<=0};Semaphore.prototype.release=function(){if(this._maxConcurrency>1){throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead")}if(this._currentReleaser){var e=this._currentReleaser;this._currentReleaser=undefined;e()}};Semaphore.prototype.cancel=function(){var e=this;this._queue.forEach((function(t){return t.reject(e._cancelError)}));this._queue=[]};Semaphore.prototype._dispatch=function(){var e=this;var t=this._queue.shift();if(!t)return;var r=false;this._currentReleaser=function(){if(r)return;r=true;e._value++;e._resolveWaiters();e._dispatch()};t.resolve([this._value--,this._currentReleaser])};Semaphore.prototype._resolveWaiters=function(){this._waiters.forEach((function(e){return e.resolve()}));this._waiters=[]};return Semaphore}();t["default"]=s},6984:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.E_CANCELED=t.E_ALREADY_LOCKED=t.E_TIMEOUT=void 0;t.E_TIMEOUT=new Error("timeout while waiting for mutex to become available");t.E_ALREADY_LOCKED=new Error("mutex already locked");t.E_CANCELED=new Error("request for lock canceled")},4038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=t.withTimeout=t.Semaphore=t.Mutex=void 0;var n=r(4351);var o=r(4855);Object.defineProperty(t,"Mutex",{enumerable:true,get:function(){return o.default}});var s=r(6006);Object.defineProperty(t,"Semaphore",{enumerable:true,get:function(){return s.default}});var i=r(5124);Object.defineProperty(t,"withTimeout",{enumerable:true,get:function(){return i.withTimeout}});var a=r(2621);Object.defineProperty(t,"tryAcquire",{enumerable:true,get:function(){return a.tryAcquire}});(0,n.__exportStar)(r(6984),t)},2621:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.tryAcquire=void 0;var n=r(6984);var o=r(5124);function tryAcquire(e,t){if(t===void 0){t=n.E_ALREADY_LOCKED}return(0,o.withTimeout)(e,0,t)}t.tryAcquire=tryAcquire},5124:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.withTimeout=void 0;var n=r(4351);var o=r(6984);function withTimeout(e,t,r){var s=this;if(r===void 0){r=o.E_TIMEOUT}return{acquire:function(){return new Promise((function(o,i){return(0,n.__awaiter)(s,void 0,void 0,(function(){var s,a,A,c,l;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:s=false;a=setTimeout((function(){s=true;i(r)}),t);n.label=1;case 1:n.trys.push([1,3,,4]);return[4,e.acquire()];case 2:A=n.sent();if(s){c=Array.isArray(A)?A[1]:A;c()}else{clearTimeout(a);o(A)}return[3,4];case 3:l=n.sent();if(!s){clearTimeout(a);i(l)}return[3,4];case 4:return[2]}}))}))}))},runExclusive:function(e){return(0,n.__awaiter)(this,void 0,void 0,(function(){var t,r;return(0,n.__generator)(this,(function(n){switch(n.label){case 0:t=function(){return undefined};n.label=1;case 1:n.trys.push([1,,7,8]);return[4,this.acquire()];case 2:r=n.sent();if(!Array.isArray(r))return[3,4];t=r[1];return[4,e(r[0])];case 3:return[2,n.sent()];case 4:t=r;return[4,e()];case 5:return[2,n.sent()];case 6:return[3,8];case 7:t();return[7];case 8:return[2]}}))}))},release:function(){e.release()},cancel:function(){return e.cancel()},waitForUnlock:function(){return e.waitForUnlock()},isLocked:function(){return e.isLocked()}}}t.withTimeout=withTimeout},9417:e=>{"use strict";e.exports=balanced;function balanced(e,t,r){if(e instanceof RegExp)e=maybeMatch(e,r);if(t instanceof RegExp)t=maybeMatch(t,r);var n=range(e,t,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+e.length,n[1]),post:r.slice(n[1]+t.length)}}function maybeMatch(e,t){var r=t.match(e);return r?r[0]:null}balanced.range=range;function range(e,t,r){var n,o,s,i,a;var A=r.indexOf(e);var c=r.indexOf(t,A+1);var l=A;if(A>=0&&c>0){if(e===t){return[A,c]}n=[];s=r.length;while(l>=0&&!a){if(l==A){n.push(l);A=r.indexOf(e,l+1)}else if(n.length==1){a=[n.pop(),c]}else{o=n.pop();if(o=0?A:c}if(n.length){a=[s,i]}}return a}},336:(e,t,r)=>{"use strict";var n=r(1642).Duplex,o=r(3837),s=r(1867).Buffer;function BufferList(e){if(!(this instanceof BufferList))return new BufferList(e);this._bufs=[];this.length=0;if(typeof e=="function"){this._callback=e;var t=function piper(e){if(this._callback){this._callback(e);this._callback=null}}.bind(this);this.on("pipe",(function onPipe(e){e.on("error",t)}));this.on("unpipe",(function onUnpipe(e){e.removeListener("error",t)}))}else{this.append(e)}n.call(this)}o.inherits(BufferList,n);BufferList.prototype._offset=function _offset(e){var t=0,r=0,n;if(e===0)return[0,0];for(;rthis.length||e<0){return undefined}var t=this._offset(e);return this._bufs[t[0]][t[1]]};BufferList.prototype.slice=function slice(e,t){if(typeof e=="number"&&e<0)e+=this.length;if(typeof t=="number"&&t<0)t+=this.length;return this.copy(null,0,e,t)};BufferList.prototype.copy=function copy(e,t,r,n){if(typeof r!="number"||r<0)r=0;if(typeof n!="number"||n>this.length)n=this.length;if(r>=this.length)return e||s.alloc(0);if(n<=0)return e||s.alloc(0);var copy=!!e,o=this._offset(r),i=n-r,a=i,A=copy&&t||0,c=o[1],l,u;if(r===0&&n==this.length){if(!copy){return this._bufs.length===1?this._bufs[0]:s.concat(this._bufs,this.length)}for(u=0;ul){this._bufs[u].copy(e,A,c);A+=l}else{this._bufs[u].copy(e,A,c,c+a);A+=l;break}a-=l;if(c)c=0}if(e.length>A)return e.slice(0,A);return e};BufferList.prototype.shallowSlice=function shallowSlice(e,t){e=e||0;t=typeof t!=="number"?this.length:t;if(e<0)e+=this.length;if(t<0)t+=this.length;if(e===t){return new BufferList}var r=this._offset(e),n=this._offset(t),o=this._bufs.slice(r[0],n[0]+1);if(n[1]==0)o.pop();else o[o.length-1]=o[o.length-1].slice(0,n[1]);if(r[1]!=0)o[0]=o[0].slice(r[1]);return new BufferList(o)};BufferList.prototype.toString=function toString(e,t,r){return this.slice(t,r).toString(e)};BufferList.prototype.consume=function consume(e){e=Math.trunc(e);if(Number.isNaN(e)||e<=0)return this;while(this._bufs.length){if(e>=this._bufs[0].length){e-=this._bufs[0].length;this.length-=this._bufs[0].length;this._bufs.shift()}else{this._bufs[0]=this._bufs[0].slice(e);this.length-=e;break}}return this};BufferList.prototype.duplicate=function duplicate(){var e=0,t=new BufferList;for(;ethis.length?this.length:t}var n=this._offset(t);var o=n[0];var i=n[1];for(o;o=e.length){var c=a.indexOf(e,i);if(c!==-1){return this._reverseOffset([o,c])}i=a.length-e.length+1}else{var l=this._reverseOffset([o,i]);if(this._match(l,e)){return l}i++}}i=0}return-1};BufferList.prototype._match=function(e,t){if(this.length-e{var n=r(6891);var o=r(9417);e.exports=expandTop;var s="\0SLASH"+Math.random()+"\0";var i="\0OPEN"+Math.random()+"\0";var a="\0CLOSE"+Math.random()+"\0";var A="\0COMMA"+Math.random()+"\0";var c="\0PERIOD"+Math.random()+"\0";function numeric(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function escapeBraces(e){return e.split("\\\\").join(s).split("\\{").join(i).split("\\}").join(a).split("\\,").join(A).split("\\.").join(c)}function unescapeBraces(e){return e.split(s).join("\\").split(i).join("{").split(a).join("}").split(A).join(",").split(c).join(".")}function parseCommaParts(e){if(!e)return[""];var t=[];var r=o("{","}",e);if(!r)return e.split(",");var n=r.pre;var s=r.body;var i=r.post;var a=n.split(",");a[a.length-1]+="{"+s+"}";var A=parseCommaParts(i);if(i.length){a[a.length-1]+=A.shift();a.push.apply(a,A)}t.push.apply(t,a);return t}function expandTop(e){if(!e)return[];if(e.substr(0,2)==="{}"){e="\\{\\}"+e.substr(2)}return expand(escapeBraces(e),true).map(unescapeBraces)}function identity(e){return e}function embrace(e){return"{"+e+"}"}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand(e,t){var r=[];var s=o("{","}",e);if(!s||/\$$/.test(s.pre))return[e];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body);var A=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body);var c=i||A;var l=s.body.indexOf(",")>=0;if(!c&&!l){if(s.post.match(/,.*\}/)){e=s.pre+"{"+s.body+a+s.post;return expand(e)}return[e]}var u;if(c){u=s.body.split(/\.\./)}else{u=parseCommaParts(s.body);if(u.length===1){u=expand(u[0],false).map(embrace);if(u.length===1){var h=s.post.length?expand(s.post,false):[""];return h.map((function(e){return s.pre+u[0]+e}))}}}var d=s.pre;var h=s.post.length?expand(s.post,false):[""];var g;if(c){var p=numeric(u[0]);var E=numeric(u[1]);var m=Math.max(u[0].length,u[1].length);var C=u.length==3?Math.abs(numeric(u[2])):1;var I=lte;var y=E0){var S=new Array(w+1).join("0");if(Q<0)b="-"+S+b.slice(1);else b=S+b}}}g.push(b)}}else{g=n(u,(function(e){return expand(e,false)}))}for(var v=0;v{var n=r(6800),o=r(5497),s=r(7113),i=r(3797),a=r(414),A=r(972),c=r(6142),l=r(8522),u=r(3639),h=r(5846),d=r(5325),g=r(9502),p=r(4636),E=r(2259),m=r(1031);n.BSON_INT32_MAX=2147483647;n.BSON_INT32_MIN=-2147483648;n.BSON_INT64_MAX=Math.pow(2,63)-1;n.BSON_INT64_MIN=-Math.pow(2,63);n.JS_INT_MAX=9007199254740992;n.JS_INT_MIN=-9007199254740992;n.Binary=o;n.Code=s;n.DBRef=i;n.Decimal128=a;n.Double=A;n.Int32=c;n.Long=l;n.Map=u;n.MaxKey=h;n.MinKey=d;n.ObjectId=g;n.ObjectID=g;n.BSONRegExp=p;n.Symbol=E;n.Timestamp=m;e.exports=n},5497:(e,t,r)=>{if(typeof global!=="undefined"){var n=r(4300).Buffer}var o=r(2863);function Binary(e,t){if(!(this instanceof Binary))return new Binary(e,t);if(e!=null&&!(typeof e==="string")&&!n.isBuffer(e)&&!(e instanceof Uint8Array)&&!Array.isArray(e)){throw new Error("only String, Buffer, Uint8Array or Array accepted")}this._bsontype="Binary";if(e instanceof Number){this.sub_type=e;this.position=0}else{this.sub_type=t==null?s:t;this.position=0}if(e!=null&&!(e instanceof Number)){if(typeof e==="string"){if(typeof n!=="undefined"){this.buffer=o.toBuffer(e)}else if(typeof Uint8Array!=="undefined"||Object.prototype.toString.call(e)==="[object Array]"){this.buffer=writeStringToArray(e)}else{throw new Error("only String, Buffer, Uint8Array or Array accepted")}}else{this.buffer=e}this.position=e.length}else{if(typeof n!=="undefined"){this.buffer=o.allocBuffer(Binary.BUFFER_SIZE)}else if(typeof Uint8Array!=="undefined"){this.buffer=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE))}else{this.buffer=new Array(Binary.BUFFER_SIZE)}this.position=0}}Binary.prototype.put=function put(e){if(e["length"]!=null&&typeof e!=="number"&&e.length!==1)throw new Error("only accepts single character String, Uint8Array or Array");if(typeof e!=="number"&&e<0||e>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var t=null;if(typeof e==="string"){t=e.charCodeAt(0)}else if(e["length"]!=null){t=e[0]}else{t=e}if(this.buffer.length>this.position){this.buffer[this.position++]=t}else{if(typeof n!=="undefined"&&n.isBuffer(this.buffer)){var r=o.allocBuffer(Binary.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length);this.buffer=r;this.buffer[this.position++]=t}else{r=null;if(Object.prototype.toString.call(this.buffer)==="[object Uint8Array]"){r=new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE+this.buffer.length))}else{r=new Array(Binary.BUFFER_SIZE+this.buffer.length)}for(var s=0;sthis.position?t+e.length:this.position}else if(typeof n!=="undefined"&&typeof e==="string"&&n.isBuffer(this.buffer)){this.buffer.write(e,t,"binary");this.position=t+e.length>this.position?t+e.length:this.position}else if(Object.prototype.toString.call(e)==="[object Uint8Array]"||Object.prototype.toString.call(e)==="[object Array]"&&typeof e!=="string"){for(s=0;sthis.position?t:this.position}else if(typeof e==="string"){for(s=0;sthis.position?t:this.position}};Binary.prototype.read=function read(e,t){t=t&&t>0?t:this.position;if(this.buffer["slice"]){return this.buffer.slice(e,e+t)}else{var r=typeof Uint8Array!=="undefined"?new Uint8Array(new ArrayBuffer(t)):new Array(t);for(var n=0;n{"use strict";var n=r(3639),o=r(8522),s=r(972),i=r(1031),a=r(9502),A=r(4636),c=r(2259),l=r(6142),u=r(7113),h=r(414),d=r(5325),g=r(5846),p=r(3797),E=r(5497);var m=r(2139),C=r(9290),I=r(1273),y=r(2863);var B=1024*1024*17;var Q=y.allocBuffer(B);var BSON=function(){};BSON.prototype.serialize=function serialize(e,t){t=t||{};var r=typeof t.checkKeys==="boolean"?t.checkKeys:false;var n=typeof t.serializeFunctions==="boolean"?t.serializeFunctions:false;var o=typeof t.ignoreUndefined==="boolean"?t.ignoreUndefined:true;var s=typeof t.minInternalBufferSize==="number"?t.minInternalBufferSize:B;if(Q.length{var t=function Code(e,t){if(!(this instanceof Code))return new Code(e,t);this._bsontype="Code";this.code=e;this.scope=t};t.prototype.toJSON=function(){return{scope:this.scope,code:this.code}};e.exports=t;e.exports.Code=t},3797:e=>{function DBRef(e,t,r){if(!(this instanceof DBRef))return new DBRef(e,t,r);this._bsontype="DBRef";this.namespace=e;this.oid=t;this.db=r}DBRef.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:this.db==null?"":this.db}};e.exports=DBRef;e.exports.DBRef=DBRef},414:(e,t,r)=>{"use strict";var n=r(8522);var o=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var s=/^(\+|-)?(Infinity|inf)$/i;var i=/^(\+|-)?NaN$/i;var a=6111;var A=-6176;var c=6176;var l=34;var u=[124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var h=[248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var d=[120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse();var g=/^([-+])?(\d+)?$/;var p=r(2863);var isDigit=function(e){return!isNaN(parseInt(e,10))};var divideu128=function(e){var t=n.fromNumber(1e3*1e3*1e3);var r=n.fromNumber(0);var o=0;if(!e.parts[0]&&!e.parts[1]&&!e.parts[2]&&!e.parts[3]){return{quotient:e,rem:r}}for(o=0;o<=3;o++){r=r.shiftLeft(32);r=r.add(new n(e.parts[o],0));e.parts[o]=r.div(t).low_;r=r.modulo(t)}return{quotient:e,rem:r}};var multiply64x2=function(e,t){if(!e&&!t){return{high:n.fromNumber(0),low:n.fromNumber(0)}}var r=e.shiftRightUnsigned(32);var o=new n(e.getLowBits(),0);var s=t.shiftRightUnsigned(32);var i=new n(t.getLowBits(),0);var a=r.multiply(s);var A=r.multiply(i);var c=o.multiply(s);var l=o.multiply(i);a=a.add(A.shiftRightUnsigned(32));A=new n(A.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32));a=a.add(A.shiftRightUnsigned(32));l=A.shiftLeft(32).add(new n(l.getLowBits(),0));return{high:a,low:l}};var lessThan=function(e,t){var r=e.high_>>>0;var n=t.high_>>>0;if(r>>0;var s=t.low_>>>0;if(o=7e3){throw new Error(""+e+" not a valid Decimal128 string")}var _=e.match(o);var M=e.match(s);var L=e.match(i);if(!_&&!M&&!L||e.length===0){throw new Error(""+e+" not a valid Decimal128 string")}if(_&&_[4]&&_[2]===undefined){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="+"||e[O]==="-"){t=e[O++]==="-"}if(!isDigit(e[O])&&e[O]!=="."){if(e[O]==="i"||e[O]==="I"){return new Decimal128(p.toBuffer(t?h:d))}else if(e[O]==="N"){return new Decimal128(p.toBuffer(u))}}while(isDigit(e[O])||e[O]==="."){if(e[O]==="."){if(r){return new Decimal128(p.toBuffer(u))}r=true;O=O+1;continue}if(b<34){if(e[O]!=="0"||E){if(!E){B=C}E=true;Q[w++]=parseInt(e[O],10);b=b+1}}if(E){I=I+1}if(r){y=y+1}C=C+1;O=O+1}if(r&&!C){throw new Error(""+e+" not a valid Decimal128 string")}if(e[O]==="e"||e[O]==="E"){var F=e.substr(++O).match(g);if(!F||!F[2]){return new Decimal128(p.toBuffer(u))}R=parseInt(F[0],10);O=O+F[0].length}if(e[O]){return new Decimal128(p.toBuffer(u))}S=0;if(!b){S=0;v=0;Q[0]=0;I=1;b=1;m=0}else{v=b-1;m=I;if(R!==0&&m!==1){while(e[B+m-1]==="0"){m=m-1}}}if(R<=y&&y-R>1<<14){R=A}else{R=R-y}while(R>a){v=v+1;if(v-S>l){var U=Q.join("");if(U.match(/^0+$/)){R=a;break}else{return new Decimal128(p.toBuffer(t?h:d))}}R=R-1}while(R=5){Y=1;if(G===5){Y=Q[v]%2===1;for(k=B+v+2;k=0;V--){if(++Q[V]>9){Q[V]=0;if(V===0){if(R>8&255;q[O++]=J.low.low_>>16&255;q[O++]=J.low.low_>>24&255;q[O++]=J.low.high_&255;q[O++]=J.low.high_>>8&255;q[O++]=J.low.high_>>16&255;q[O++]=J.low.high_>>24&255;q[O++]=J.high.low_&255;q[O++]=J.high.low_>>8&255;q[O++]=J.high.low_>>16&255;q[O++]=J.high.low_>>24&255;q[O++]=J.high.high_&255;q[O++]=J.high.high_>>8&255;q[O++]=J.high.high_>>16&255;q[O++]=J.high.high_>>24&255;return new Decimal128(q)};var E=31;var m=16383;var C=30;var I=31;c=6176;Decimal128.prototype.toString=function(){var e;var t;var r;var o;var s;var i;var a=0;var A=new Array(36);for(var l=0;l>26&E;if(s>>3===3){if(s===C){return b.join("")+"Infinity"}else if(s===I){return"NaN"}else{i=e>>15&m;p=8+(e>>14&1)}}else{p=e>>14&7;i=e>>17&m}h=i-c;y.parts[0]=(e&16383)+((p&15)<<14);y.parts[1]=t;y.parts[2]=r;y.parts[3]=o;if(y.parts[0]===0&&y.parts[1]===0&&y.parts[2]===0&&y.parts[3]===0){g=true}else{for(Q=3;Q>=0;Q--){var v=0;var R=divideu128(y);y=R.quotient;v=R.rem.low_;if(!v)continue;for(B=8;B>=0;B--){A[Q*9+B]=v%10;v=Math.floor(v/10)}}}if(g){a=1;A[u]=0}else{a=36;l=0;while(!A[u]){l++;a=a-1;u=u+1}}d=a-1+h;if(d>=34||d<=-7||h>0){b.push(A[u++]);a=a-1;if(a){b.push(".")}for(l=0;l0){b.push("+"+d)}else{b.push(d)}}else{if(h>=0){for(l=0;l0){for(l=0;l{function Double(e){if(!(this instanceof Double))return new Double(e);this._bsontype="Double";this.value=e}Double.prototype.valueOf=function(){return this.value};Double.prototype.toJSON=function(){return this.value};e.exports=Double;e.exports.Double=Double},7998:(e,t)=>{var r;var readIEEE754=function(e,t,r,n,o){var s,i,a=r==="big",A=o*8-n-1,c=(1<>1,u=-7,h=a?0:o-1,d=a?1:-1,g=e[t+h];h+=d;s=g&(1<<-u)-1;g>>=-u;u+=A;for(;u>0;s=s*256+e[t+h],h+=d,u-=8);i=s&(1<<-u)-1;s>>=-u;u+=n;for(;u>0;i=i*256+e[t+h],h+=d,u-=8);if(s===0){s=1-l}else if(s===c){return i?NaN:(g?-1:1)*Infinity}else{i=i+Math.pow(2,n);s=s-l}return(g?-1:1)*i*Math.pow(2,s-n)};var writeIEEE754=function(e,t,r,n,o,s){var i,a,A,c=n==="big",l=s*8-o-1,u=(1<>1,d=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=c?s-1:0,p=c?-1:1,E=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){a=isNaN(t)?1:0;i=u}else{i=Math.floor(Math.log(t)/Math.LN2);if(t*(A=Math.pow(2,-i))<1){i--;A*=2}if(i+h>=1){t+=d/A}else{t+=d*Math.pow(2,1-h)}if(t*A>=2){i++;A/=2}if(i+h>=u){a=0;i=u}else if(i+h>=1){a=(t*A-1)*Math.pow(2,o);i=i+h}else{a=t*Math.pow(2,h-1)*Math.pow(2,o);i=0}}for(;o>=8;e[r+g]=a&255,g+=p,a/=256,o-=8);i=i<0;e[r+g]=i&255,g+=p,i/=256,l-=8);e[r+g-p]|=E*128};r=readIEEE754;t.P=writeIEEE754},6142:e=>{var Int32=function(e){if(!(this instanceof Int32))return new Int32(e);this._bsontype="Int32";this.value=e};Int32.prototype.valueOf=function(){return this.value};Int32.prototype.toJSON=function(){return this.value};e.exports=Int32;e.exports.Int32=Int32},8522:e=>{function Long(e,t){if(!(this instanceof Long))return new Long(e,t);this._bsontype="Long";this.low_=e|0;this.high_=t|0}Long.prototype.toInt=function(){return this.low_};Long.prototype.toNumber=function(){return this.high_*Long.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Long.prototype.toBigInt=function(){return BigInt(this.toString())};Long.prototype.toJSON=function(){return this.toString()};Long.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Long.TWO_PWR_32_DBL_+this.low_};Long.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Long.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Long.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Long.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Long.prototype.negate=function(){if(this.equals(Long.MIN_VALUE)){return Long.MIN_VALUE}else{return this.not().add(Long.ONE)}};Long.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.subtract=function(e){return this.add(e.negate())};Long.prototype.multiply=function(e){if(this.isZero()){return Long.ZERO}else if(e.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){return e.isOdd()?Long.MIN_VALUE:Long.ZERO}else if(e.equals(Long.MIN_VALUE)){return this.isOdd()?Long.MIN_VALUE:Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Long.TWO_PWR_24_)&&e.lessThan(Long.TWO_PWR_24_)){return Long.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Long.fromBits(u<<16|h,c<<16|l)};Long.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Long.ZERO}if(this.equals(Long.MIN_VALUE)){if(e.equals(Long.ONE)||e.equals(Long.NEG_ONE)){return Long.MIN_VALUE}else if(e.equals(Long.MIN_VALUE)){return Long.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Long.ZERO)){return e.isNegative()?Long.ONE:Long.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Long.MIN_VALUE)){return Long.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Long.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Long.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Long.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Long.ONE}s=s.add(A);n=n.subtract(c)}return s};Long.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Long.prototype.not=function(){return Long.fromBits(~this.low_,~this.high_)};Long.prototype.and=function(e){return Long.fromBits(this.low_&e.low_,this.high_&e.high_)};Long.prototype.or=function(e){return Long.fromBits(this.low_|e.low_,this.high_|e.high_)};Long.prototype.xor=function(e){return Long.fromBits(this.low_^e.low_,this.high_^e.high_)};Long.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Long.fromBits(t<>>32-e)}else{return Long.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Long.fromBits(t>>e-32,t>=0?0:-1)}}};Long.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Long.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Long.fromBits(t,0)}else{return Long.fromBits(t>>>e-32,0)}}};Long.fromInt=function(e){if(-128<=e&&e<128){var t=Long.INT_CACHE_[e];if(t){return t}}var r=new Long(e|0,e<0?-1:0);if(-128<=e&&e<128){Long.INT_CACHE_[e]=r}return r};Long.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Long.ZERO}else if(e<=-Long.TWO_PWR_63_DBL_){return Long.MIN_VALUE}else if(e+1>=Long.TWO_PWR_63_DBL_){return Long.MAX_VALUE}else if(e<0){return Long.fromNumber(-e).negate()}else{return new Long(e%Long.TWO_PWR_32_DBL_|0,e/Long.TWO_PWR_32_DBL_|0)}};Long.fromBigInt=function(e){return Long.fromString(e.toString(10),10)};Long.fromBits=function(e,t){return new Long(e,t)};Long.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Long.fromNumber(Math.pow(r,8));var o=Long.ZERO;for(var s=0;s{"use strict";if(typeof global.Map!=="undefined"){e.exports=global.Map;e.exports.Map=global.Map}else{var Map=function(e){this._keys=[];this._values={};for(var t=0;t{function MaxKey(){if(!(this instanceof MaxKey))return new MaxKey;this._bsontype="MaxKey"}e.exports=MaxKey;e.exports.MaxKey=MaxKey},5325:e=>{function MinKey(){if(!(this instanceof MinKey))return new MinKey;this._bsontype="MinKey"}e.exports=MinKey;e.exports.MinKey=MinKey},9502:(e,t,r)=>{var n="inspect";var o=r(2863);var s=parseInt(Math.random()*16777215,10);var i=new RegExp("^[0-9a-fA-F]{24}$");try{if(Buffer&&Buffer.from){var a=true;n=r(3837).inspect.custom||"inspect"}}catch(e){a=false}var A=function ObjectID(e){if(e instanceof ObjectID)return e;if(!(this instanceof ObjectID))return new ObjectID(e);this._bsontype="ObjectID";if(e==null||typeof e==="number"){this.id=this.generate(e);if(ObjectID.cacheHexString)this.__id=this.toString("hex");return}var t=ObjectID.isValid(e);if(!t&&e!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(t&&typeof e==="string"&&e.length===24&&a){return new ObjectID(o.toBuffer(e,"hex"))}else if(t&&typeof e==="string"&&e.length===24){return ObjectID.createFromHexString(e)}else if(e!=null&&e.length===12){this.id=e}else if(e!=null&&typeof e.toHexString==="function"){return e}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}if(ObjectID.cacheHexString)this.__id=this.toString("hex")};var c=[];for(var l=0;l<256;l++){c[l]=(l<=15?"0":"")+l.toString(16)}A.prototype.toHexString=function(){if(A.cacheHexString&&this.__id)return this.__id;var e="";if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id instanceof h){e=convertToHex(this.id);if(A.cacheHexString)this.__id=e;return e}for(var t=0;t>8&255;n[1]=e>>16&255;n[0]=e>>24&255;n[6]=s&255;n[5]=s>>8&255;n[4]=s>>16&255;n[8]=t&255;n[7]=t>>8&255;n[11]=r&255;n[10]=r>>8&255;n[9]=r>>16&255;return n};A.prototype.toString=function(e){if(this.id&&this.id.copy){return this.id.toString(typeof e==="string"?e:"hex")}return this.toHexString()};A.prototype[n]=A.prototype.toString;A.prototype.toJSON=function(){return this.toHexString()};A.prototype.equals=function equals(e){if(e instanceof A){return this.toString()===e.toString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12&&this.id instanceof h){return e===this.id.toString("binary")}else if(typeof e==="string"&&A.isValid(e)&&e.length===24){return e.toLowerCase()===this.toHexString()}else if(typeof e==="string"&&A.isValid(e)&&e.length===12){return e===this.id}else if(e!=null&&(e instanceof A||e.toHexString)){return e.toHexString()===this.toHexString()}else{return false}};A.prototype.getTimestamp=function(){var e=new Date;var t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;e.setTime(Math.floor(t)*1e3);return e};A.index=~~(Math.random()*16777215);A.createPk=function createPk(){return new A};A.createFromTime=function createFromTime(e){var t=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);t[3]=e&255;t[2]=e>>8&255;t[1]=e>>16&255;t[0]=e>>24&255;return new A(t)};var u=[];l=0;while(l<10)u[48+l]=l++;while(l<16)u[65-10+l]=u[97-10+l]=l++;var h=Buffer;var convertToHex=function(e){return e.toString("hex")};A.createFromHexString=function createFromHexString(e){if(typeof e==="undefined"||e!=null&&e.length!==24){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 A(o.toBuffer(e,"hex"));var t=new h(12);var r=0;var n=0;while(n<24){t[r++]=u[e.charCodeAt(n++)]<<4|u[e.charCodeAt(n++)]}return new A(t)};A.isValid=function isValid(e){if(e==null)return false;if(typeof e==="number"){return true}if(typeof e==="string"){return e.length===12||e.length===24&&i.test(e)}if(e instanceof A){return true}if(e instanceof h){return true}if(typeof e.toHexString==="function"&&(e.id instanceof h||typeof e.id==="string")){return e.id.length===12||e.id.length===24&&i.test(e.id)}return false};Object.defineProperty(A.prototype,"generationTime",{enumerable:true,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(e){this.id[3]=e&255;this.id[2]=e>>8&255;this.id[1]=e>>16&255;this.id[0]=e>>24&255}});e.exports=A;e.exports.ObjectID=A;e.exports.ObjectId=A},1273:(e,t,r)=>{"use strict";var n=r(8522).Long,o=r(972).Double,s=r(1031).Timestamp,i=r(9502).ObjectID,a=r(2259).Symbol,A=r(4636).BSONRegExp,c=r(7113).Code,l=r(414),u=r(5325).MinKey,h=r(5846).MaxKey,d=r(3797).DBRef,g=r(5497).Binary;var p=r(2863).normalizedFunctionString;var E=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var m=function calculateObjectSize(e,t,r){var n=4+1;if(Array.isArray(e)){for(var o=0;o=C.JS_INT_MIN&&t<=C.JS_INT_MAX){if(t>=C.BSON_INT32_MIN&&t<=C.BSON_INT32_MAX){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(4+1)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}case"undefined":if(I||!y)return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1;return 0;case"boolean":return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+1);case"object":if(t==null||t instanceof u||t instanceof h||t["_bsontype"]==="MinKey"||t["_bsontype"]==="MaxKey"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1}else if(t instanceof i||t["_bsontype"]==="ObjectID"||t["_bsontype"]==="ObjectId"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(12+1)}else if(t instanceof Date||E(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(typeof Buffer!=="undefined"&&Buffer.isBuffer(t)){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(1+4+1)+t.length}else if(t instanceof n||t instanceof o||t instanceof s||t["_bsontype"]==="Long"||t["_bsontype"]==="Double"||t["_bsontype"]==="Timestamp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(8+1)}else if(t instanceof l||t["_bsontype"]==="Decimal128"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(16+1)}else if(t instanceof c||t["_bsontype"]==="Code"){if(t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(t.code.toString(),"utf8")+1+m(t.scope,r,y)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(t.code.toString(),"utf8")+1}}else if(t instanceof g||t["_bsontype"]==="Binary"){if(t.sub_type===g.SUBTYPE_BYTE_ARRAY){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1+4)}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+(t.position+1+4+1)}}else if(t instanceof a||t["_bsontype"]==="Symbol"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+Buffer.byteLength(t.value,"utf8")+4+1+1}else if(t instanceof d||t["_bsontype"]==="DBRef"){var B={$ref:t.namespace,$id:t.oid};if(null!=t.db){B["$db"]=t.db}return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+m(B,r,y)}else if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"){return(e!=null?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}else if(t instanceof A||t["_bsontype"]==="BSONRegExp"){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+Buffer.byteLength(t.pattern,"utf8")+1+Buffer.byteLength(t.options,"utf8")+1}else{return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+m(t,r,y)+1}case"function":if(t instanceof RegExp||Object.prototype.toString.call(t)==="[object RegExp]"||String.call(t)==="[object RegExp]"){return(e!=null?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}else{if(r&&t.scope!=null&&Object.keys(t.scope).length>0){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+4+Buffer.byteLength(p(t),"utf8")+1+m(t.scope,r,y)}else if(r){return(e!=null?Buffer.byteLength(e,"utf8")+1:0)+1+4+Buffer.byteLength(p(t),"utf8")+1}}}return 0}var C={};C.BSON_INT32_MAX=2147483647;C.BSON_INT32_MIN=-2147483648;C.JS_INT_MAX=9007199254740992;C.JS_INT_MIN=-9007199254740992;e.exports=m},2139:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";var Long=__nccwpck_require__(8522).Long,Double=__nccwpck_require__(972).Double,Timestamp=__nccwpck_require__(1031).Timestamp,ObjectID=__nccwpck_require__(9502).ObjectID,Symbol=__nccwpck_require__(2259).Symbol,Code=__nccwpck_require__(7113).Code,MinKey=__nccwpck_require__(5325).MinKey,MaxKey=__nccwpck_require__(5846).MaxKey,Decimal128=__nccwpck_require__(414),Int32=__nccwpck_require__(6142),DBRef=__nccwpck_require__(3797).DBRef,BSONRegExp=__nccwpck_require__(4636).BSONRegExp,Binary=__nccwpck_require__(5497).Binary;var utils=__nccwpck_require__(2863);var deserialize=function(e,t,r){t=t==null?{}:t;var n=t&&t.index?t.index:0;var o=e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24;if(o<5||e.lengthe.length){throw new Error("corrupt bson message")}if(e[n+o-1]!==0){throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(e,n,t,r)};var deserializeObject=function(e,t,r,n){var o=r["evalFunctions"]==null?false:r["evalFunctions"];var s=r["cacheFunctions"]==null?false:r["cacheFunctions"];var i=r["cacheFunctionsCrc32"]==null?false:r["cacheFunctionsCrc32"];if(!i)var a=null;var A=r["fieldsAsRaw"]==null?null:r["fieldsAsRaw"];var c=r["raw"]==null?false:r["raw"];var l=typeof r["bsonRegExp"]==="boolean"?r["bsonRegExp"]:false;var u=r["promoteBuffers"]==null?false:r["promoteBuffers"];var h=r["promoteLongs"]==null?true:r["promoteLongs"];var d=r["promoteValues"]==null?true:r["promoteValues"];var g=t;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var p=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(p<5||p>e.length)throw new Error("corrupt bson message");var E=n?[]:{};var m=0;var C=false;while(!C){var I=e[t++];if(I===0)break;var y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var B=n?m++:e.toString("utf8",t,y);t=y+1;if(I===BSON.BSON_DATA_STRING){var Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=e.toString("utf8",t,t+Q-1);t=t+Q}else if(I===BSON.BSON_DATA_OID){var b=utils.allocBuffer(12);e.copy(b,0,t,t+12);E[B]=new ObjectID(b);t=t+12}else if(I===BSON.BSON_DATA_INT&&d===false){E[B]=new Int32(e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24)}else if(I===BSON.BSON_DATA_INT){E[B]=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}else if(I===BSON.BSON_DATA_NUMBER&&d===false){E[B]=new Double(e.readDoubleLE(t));t=t+8}else if(I===BSON.BSON_DATA_NUMBER){E[B]=e.readDoubleLE(t);t=t+8}else if(I===BSON.BSON_DATA_DATE){var w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Date(new Long(w,S).toNumber())}else if(I===BSON.BSON_DATA_BOOLEAN){if(e[t]!==0&&e[t]!==1)throw new Error("illegal boolean type value");E[B]=e[t++]===1}else if(I===BSON.BSON_DATA_OBJECT){var v=t;var R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;if(R<=0||R>e.length-t)throw new Error("bad embedded document length in bson");if(c){E[B]=e.slice(t,t+R)}else{E[B]=deserializeObject(e,v,r,false)}t=t+R}else if(I===BSON.BSON_DATA_ARRAY){v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var k=r;var D=t+R;if(A&&A[B]){k={};for(var N in r)k[N]=r[N];k["raw"]=true}E[B]=deserializeObject(e,v,k,true);t=t+R;if(e[t-1]!==0)throw new Error("invalid array terminator byte");if(t!==D)throw new Error("corrupted array bson")}else if(I===BSON.BSON_DATA_UNDEFINED){E[B]=undefined}else if(I===BSON.BSON_DATA_NULL){E[B]=null}else if(I===BSON.BSON_DATA_LONG){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var T=new Long(w,S);if(h&&d===true){E[B]=T.lessThanOrEqual(JS_INT_MAX_LONG)&&T.greaterThanOrEqual(JS_INT_MIN_LONG)?T.toNumber():T}else{E[B]=T}}else if(I===BSON.BSON_DATA_DECIMAL128){var O=utils.allocBuffer(16);e.copy(O,0,t,t+16);t=t+16;var _=new Decimal128(O);E[B]=_.toObject?_.toObject():_}else if(I===BSON.BSON_DATA_BINARY){var M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;var L=M;var F=e[t++];if(M<0)throw new Error("Negative binary type element size found");if(M>e.length)throw new Error("Binary type size larger than document size");if(e["slice"]!=null){if(F===Binary.SUBTYPE_BYTE_ARRAY){M=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(M<0)throw new Error("Negative binary type element size found for subtype 0x02");if(M>L-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(ML-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(M=e.length)throw new Error("Bad BSON Document: illegal CString");var P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");var G=e.toString("utf8",t,y);t=y+1;var Y=new Array(G.length);for(y=0;y=e.length)throw new Error("Bad BSON Document: illegal CString");P=e.toString("utf8",t,y);t=y+1;y=t;while(e[y]!==0&&y=e.length)throw new Error("Bad BSON Document: illegal CString");G=e.toString("utf8",t,y);t=y+1;E[B]=new BSONRegExp(P,G)}else if(I===BSON.BSON_DATA_SYMBOL){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");E[B]=new Symbol(e.toString("utf8",t,t+Q-1));t=t+Q}else if(I===BSON.BSON_DATA_TIMESTAMP){w=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;S=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;E[B]=new Timestamp(w,S)}else if(I===BSON.BSON_DATA_MIN_KEY){E[B]=new MinKey}else if(I===BSON.BSON_DATA_MAX_KEY){E[B]=new MaxKey}else if(I===BSON.BSON_DATA_CODE){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var V=e.toString("utf8",t,t+Q-1);if(o){if(s){var W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}}else{E[B]=new Code(V)}t=t+Q}else if(I===BSON.BSON_DATA_CODE_W_SCOPE){var J=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(J<4+4+4+1){throw new Error("code_w_scope total size shorter minimum expected length")}Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");V=e.toString("utf8",t,t+Q-1);t=t+Q;v=t;R=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;var q=deserializeObject(e,v,r,false);t=t+R;if(J<4+4+R+Q){throw new Error("code_w_scope total size is to short, truncating scope")}if(J>4+4+R+Q){throw new Error("code_w_scope total size is to long, clips outer document")}if(o){if(s){W=i?a(V):V;E[B]=isolateEvalWithHash(functionCache,W,V,E)}else{E[B]=isolateEval(V)}E[B].scope=q}else{E[B]=new Code(V,q)}}else if(I===BSON.BSON_DATA_DBPOINTER){Q=e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24;if(Q<=0||Q>e.length-t||e[t+Q-1]!==0)throw new Error("bad string length in bson");var j=e.toString("utf8",t,t+Q-1);t=t+Q;var z=utils.allocBuffer(12);e.copy(z,0,t,t+12);b=new ObjectID(z);t=t+12;var $=j.split(".");var K=$.shift();var X=$.join(".");E[B]=new DBRef(X,b,K)}else{throw new Error("Detected unknown BSON type "+I.toString(16)+' for fieldname "'+B+'", are you using the latest BSON parser')}}if(p!==t-g){if(n)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}if(E["$id"]!=null)E=new DBRef(E["$ref"],E["$id"],E["$db"]);return E};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;if(functionCache[hash]==null){eval("value = "+functionString);functionCache[hash]=value}return functionCache[hash].bind(object)};var isolateEval=function(functionString){var value=null;eval("value = "+functionString);return value};var BSON={};var 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);var JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},9290:(e,t,r)=>{"use strict";var n=r(7998).P,o=r(8522).Long,s=r(3639),i=r(5497).Binary;var a=r(2863).normalizedFunctionString;var A=/\x00/;var c=["$db","$ref","$id","$clusterTime"];var l=function isDate(e){return typeof e==="object"&&Object.prototype.toString.call(e)==="[object Date]"};var u=function isRegExp(e){return Object.prototype.toString.call(e)==="[object RegExp]"};var serializeString=function(e,t,r,n,o){e[n++]=d.BSON_DATA_STRING;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s+1;e[n-1]=0;var i=e.write(r,n+4,"utf8");e[n+3]=i+1>>24&255;e[n+2]=i+1>>16&255;e[n+1]=i+1>>8&255;e[n]=i+1&255;n=n+4+i;e[n++]=0;return n};var serializeNumber=function(e,t,r,s,i){if(Math.floor(r)===r&&r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){if(r>=d.BSON_INT32_MIN&&r<=d.BSON_INT32_MAX){e[s++]=d.BSON_DATA_INT;var a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;e[s++]=r&255;e[s++]=r>>8&255;e[s++]=r>>16&255;e[s++]=r>>24&255}else if(r>=d.JS_INT_MIN&&r<=d.JS_INT_MAX){e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}else{e[s++]=d.BSON_DATA_LONG;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;var A=o.fromNumber(r);var c=A.getLowBits();var l=A.getHighBits();e[s++]=c&255;e[s++]=c>>8&255;e[s++]=c>>16&255;e[s++]=c>>24&255;e[s++]=l&255;e[s++]=l>>8&255;e[s++]=l>>16&255;e[s++]=l>>24&255}}else{e[s++]=d.BSON_DATA_NUMBER;a=!i?e.write(t,s,"utf8"):e.write(t,s,"ascii");s=s+a;e[s++]=0;n(e,r,s,"little",52,8);s=s+8}return s};var serializeNull=function(e,t,r,n,o){e[n++]=d.BSON_DATA_NULL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeBoolean=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BOOLEAN;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r?1:0;return n};var serializeDate=function(e,t,r,n,s){e[n++]=d.BSON_DATA_DATE;var i=!s?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+i;e[n++]=0;var a=o.fromNumber(r.getTime());var A=a.getLowBits();var c=a.getHighBits();e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=c&255;e[n++]=c>>8&255;e[n++]=c>>16&255;e[n++]=c>>24&255;return n};var serializeRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.source&&r.source.match(A)!=null){throw Error("value "+r.source+" must not contain null bytes")}n=n+e.write(r.source,n,"utf8");e[n++]=0;if(r.global)e[n++]=115;if(r.ignoreCase)e[n++]=105;if(r.multiline)e[n++]=109;e[n++]=0;return n};var serializeBSONRegExp=function(e,t,r,n,o){e[n++]=d.BSON_DATA_REGEXP;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(r.pattern.match(A)!=null){throw Error("pattern "+r.pattern+" must not contain null bytes")}n=n+e.write(r.pattern,n,"utf8");e[n++]=0;n=n+e.write(r.options.split("").sort().join(""),n,"utf8");e[n++]=0;return n};var serializeMinMax=function(e,t,r,n,o){if(r===null){e[n++]=d.BSON_DATA_NULL}else if(r._bsontype==="MinKey"){e[n++]=d.BSON_DATA_MIN_KEY}else{e[n++]=d.BSON_DATA_MAX_KEY}var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;return n};var serializeObjectId=function(e,t,r,n,o){e[n++]=d.BSON_DATA_OID;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;if(typeof r.id==="string"){e.write(r.id,n,"binary")}else if(r.id&&r.id.copy){r.id.copy(e,n,0,12)}else{throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId")}return n+12};var serializeBuffer=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=r.length;e[n++]=i&255;e[n++]=i>>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=d.BSON_BINARY_SUBTYPE_DEFAULT;r.copy(e,n,0,i);n=n+i;return n};var serializeObject=function(e,t,r,n,o,s,i,a,A,c){for(var l=0;l>8&255;e[n++]=i>>16&255;e[n++]=i>>24&255;e[n++]=a&255;e[n++]=a>>8&255;e[n++]=a>>16&255;e[n++]=a>>24&255;return n};var serializeInt32=function(e,t,r,n,o){e[n++]=d.BSON_DATA_INT;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;e[n++]=r&255;e[n++]=r>>8&255;e[n++]=r>>16&255;e[n++]=r>>24&255;return n};var serializeDouble=function(e,t,r,o,s){e[o++]=d.BSON_DATA_NUMBER;var i=!s?e.write(t,o,"utf8"):e.write(t,o,"ascii");o=o+i;e[o++]=0;n(e,r,o,"little",52,8);o=o+8;return o};var serializeFunction=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_CODE;var A=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+A;e[n++]=0;var c=a(r);var l=e.write(c,n+4,"utf8")+1;e[n]=l&255;e[n+1]=l>>8&255;e[n+2]=l>>16&255;e[n+3]=l>>24&255;n=n+4+l-1;e[n++]=0;return n};var serializeCode=function(e,t,r,n,o,s,i,a,A){if(r.scope&&typeof r.scope==="object"){e[n++]=d.BSON_DATA_CODE_W_SCOPE;var c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;var l=n;var u=typeof r.code==="string"?r.code:r.code.toString();n=n+4;var g=e.write(u,n+4,"utf8")+1;e[n]=g&255;e[n+1]=g>>8&255;e[n+2]=g>>16&255;e[n+3]=g>>24&255;e[n+4+g-1]=0;n=n+g+4;var p=h(e,r.scope,o,n,s+1,i,a);n=p-1;var E=p-l;e[l++]=E&255;e[l++]=E>>8&255;e[l++]=E>>16&255;e[l++]=E>>24&255;e[n++]=0}else{e[n++]=d.BSON_DATA_CODE;c=!A?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+c;e[n++]=0;u=r.code.toString();var m=e.write(u,n+4,"utf8")+1;e[n]=m&255;e[n+1]=m>>8&255;e[n+2]=m>>16&255;e[n+3]=m>>24&255;n=n+4+m-1;e[n++]=0}return n};var serializeBinary=function(e,t,r,n,o){e[n++]=d.BSON_DATA_BINARY;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var a=r.value(true);var A=r.position;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY)A=A+4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255;e[n++]=r.sub_type;if(r.sub_type===i.SUBTYPE_BYTE_ARRAY){A=A-4;e[n++]=A&255;e[n++]=A>>8&255;e[n++]=A>>16&255;e[n++]=A>>24&255}a.copy(e,n,0,r.position);n=n+r.position;return n};var serializeSymbol=function(e,t,r,n,o){e[n++]=d.BSON_DATA_SYMBOL;var s=!o?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+s;e[n++]=0;var i=e.write(r.value,n+4,"utf8")+1;e[n]=i&255;e[n+1]=i>>8&255;e[n+2]=i>>16&255;e[n+3]=i>>24&255;n=n+4+i-1;e[n++]=0;return n};var serializeDBRef=function(e,t,r,n,o,s,i){e[n++]=d.BSON_DATA_OBJECT;var a=!i?e.write(t,n,"utf8"):e.write(t,n,"ascii");n=n+a;e[n++]=0;var A=n;var c;if(null!=r.db){c=h(e,{$ref:r.namespace,$id:r.oid,$db:r.db},false,n,o+1,s)}else{c=h(e,{$ref:r.namespace,$id:r.oid},false,n,o+1,s)}var l=c-A;e[A++]=l&255;e[A++]=l>>8&255;e[A++]=l>>16&255;e[A++]=l>>24&255;return c};var h=function serializeInto(e,t,r,n,o,i,a,h){n=n||0;h=h||[];h.push(t);var d=n+4;if(Array.isArray(t)){for(var g=0;g>8&255;e[n++]=B>>16&255;e[n++]=B>>24&255;return d};var d={};d.BSON_DATA_NUMBER=1;d.BSON_DATA_STRING=2;d.BSON_DATA_OBJECT=3;d.BSON_DATA_ARRAY=4;d.BSON_DATA_BINARY=5;d.BSON_DATA_UNDEFINED=6;d.BSON_DATA_OID=7;d.BSON_DATA_BOOLEAN=8;d.BSON_DATA_DATE=9;d.BSON_DATA_NULL=10;d.BSON_DATA_REGEXP=11;d.BSON_DATA_CODE=13;d.BSON_DATA_SYMBOL=14;d.BSON_DATA_CODE_W_SCOPE=15;d.BSON_DATA_INT=16;d.BSON_DATA_TIMESTAMP=17;d.BSON_DATA_LONG=18;d.BSON_DATA_DECIMAL128=19;d.BSON_DATA_MIN_KEY=255;d.BSON_DATA_MAX_KEY=127;d.BSON_BINARY_SUBTYPE_DEFAULT=0;d.BSON_BINARY_SUBTYPE_FUNCTION=1;d.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2;d.BSON_BINARY_SUBTYPE_UUID=3;d.BSON_BINARY_SUBTYPE_MD5=4;d.BSON_BINARY_SUBTYPE_USER_DEFINED=128;d.BSON_INT32_MAX=2147483647;d.BSON_INT32_MIN=-2147483648;d.BSON_INT64_MAX=Math.pow(2,63)-1;d.BSON_INT64_MIN=-Math.pow(2,63);d.JS_INT_MAX=9007199254740992;d.JS_INT_MIN=-9007199254740992;e.exports=h},2863:e=>{"use strict";function normalizedFunctionString(e){return e.toString().replace(/function *\(/,"function (")}function newBuffer(e,t){return new Buffer(e,t)}function allocBuffer(){return Buffer.alloc.apply(Buffer,arguments)}function toBuffer(){return Buffer.from.apply(Buffer,arguments)}e.exports={normalizedFunctionString:normalizedFunctionString,allocBuffer:typeof Buffer.alloc==="function"?allocBuffer:newBuffer,toBuffer:typeof Buffer.from==="function"?toBuffer:newBuffer}},4636:e=>{function BSONRegExp(e,t){if(!(this instanceof BSONRegExp))return new BSONRegExp;this._bsontype="BSONRegExp";this.pattern=e||"";this.options=t||"";for(var r=0;r{var n=Buffer?r(3837).inspect.custom||"inspect":"inspect";function Symbol(e){if(!(this instanceof Symbol))return new Symbol(e);this._bsontype="Symbol";this.value=e}Symbol.prototype.valueOf=function(){return this.value};Symbol.prototype.toString=function(){return this.value};Symbol.prototype[n]=function(){return this.value};Symbol.prototype.toJSON=function(){return this.value};e.exports=Symbol;e.exports.Symbol=Symbol},1031:e=>{function Timestamp(e,t){if(!(this instanceof Timestamp))return new Timestamp(e,t);this._bsontype="Timestamp";this.low_=e|0;this.high_=t|0}Timestamp.prototype.toInt=function(){return this.low_};Timestamp.prototype.toNumber=function(){return this.high_*Timestamp.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()};Timestamp.prototype.toJSON=function(){return this.toString()};Timestamp.prototype.toString=function(e){var t=e||10;if(t<2||36=0?this.low_:Timestamp.TWO_PWR_32_DBL_+this.low_};Timestamp.prototype.getNumBitsAbs=function(){if(this.isNegative()){if(this.equals(Timestamp.MIN_VALUE)){return 64}else{return this.negate().getNumBitsAbs()}}else{var e=this.high_!==0?this.high_:this.low_;for(var t=31;t>0;t--){if((e&1<0};Timestamp.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0};Timestamp.prototype.compare=function(e){if(this.equals(e)){return 0}var t=this.isNegative();var r=e.isNegative();if(t&&!r){return-1}if(!t&&r){return 1}if(this.subtract(e).isNegative()){return-1}else{return 1}};Timestamp.prototype.negate=function(){if(this.equals(Timestamp.MIN_VALUE)){return Timestamp.MIN_VALUE}else{return this.not().add(Timestamp.ONE)}};Timestamp.prototype.add=function(e){var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o+A;u+=h>>>16;h&=65535;u+=n+a;l+=u>>>16;u&=65535;l+=r+i;c+=l>>>16;l&=65535;c+=t+s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.subtract=function(e){return this.add(e.negate())};Timestamp.prototype.multiply=function(e){if(this.isZero()){return Timestamp.ZERO}else if(e.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){return e.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}else if(e.equals(Timestamp.MIN_VALUE)){return this.isOdd()?Timestamp.MIN_VALUE:Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().multiply(e.negate())}else{return this.negate().multiply(e).negate()}}else if(e.isNegative()){return this.multiply(e.negate()).negate()}if(this.lessThan(Timestamp.TWO_PWR_24_)&&e.lessThan(Timestamp.TWO_PWR_24_)){return Timestamp.fromNumber(this.toNumber()*e.toNumber())}var t=this.high_>>>16;var r=this.high_&65535;var n=this.low_>>>16;var o=this.low_&65535;var s=e.high_>>>16;var i=e.high_&65535;var a=e.low_>>>16;var A=e.low_&65535;var c=0,l=0,u=0,h=0;h+=o*A;u+=h>>>16;h&=65535;u+=n*A;l+=u>>>16;u&=65535;u+=o*a;l+=u>>>16;u&=65535;l+=r*A;c+=l>>>16;l&=65535;l+=n*a;c+=l>>>16;l&=65535;l+=o*i;c+=l>>>16;l&=65535;c+=t*A+r*a+n*i+o*s;c&=65535;return Timestamp.fromBits(u<<16|h,c<<16|l)};Timestamp.prototype.div=function(e){if(e.isZero()){throw Error("division by zero")}else if(this.isZero()){return Timestamp.ZERO}if(this.equals(Timestamp.MIN_VALUE)){if(e.equals(Timestamp.ONE)||e.equals(Timestamp.NEG_ONE)){return Timestamp.MIN_VALUE}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ONE}else{var t=this.shiftRight(1);var r=t.div(e).shiftLeft(1);if(r.equals(Timestamp.ZERO)){return e.isNegative()?Timestamp.ONE:Timestamp.NEG_ONE}else{var n=this.subtract(e.multiply(r));var o=r.add(n.div(e));return o}}}else if(e.equals(Timestamp.MIN_VALUE)){return Timestamp.ZERO}if(this.isNegative()){if(e.isNegative()){return this.negate().div(e.negate())}else{return this.negate().div(e).negate()}}else if(e.isNegative()){return this.div(e.negate()).negate()}var s=Timestamp.ZERO;n=this;while(n.greaterThanOrEqual(e)){r=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(r)/Math.LN2);var a=i<=48?1:Math.pow(2,i-48);var A=Timestamp.fromNumber(r);var c=A.multiply(e);while(c.isNegative()||c.greaterThan(n)){r-=a;A=Timestamp.fromNumber(r);c=A.multiply(e)}if(A.isZero()){A=Timestamp.ONE}s=s.add(A);n=n.subtract(c)}return s};Timestamp.prototype.modulo=function(e){return this.subtract(this.div(e).multiply(e))};Timestamp.prototype.not=function(){return Timestamp.fromBits(~this.low_,~this.high_)};Timestamp.prototype.and=function(e){return Timestamp.fromBits(this.low_&e.low_,this.high_&e.high_)};Timestamp.prototype.or=function(e){return Timestamp.fromBits(this.low_|e.low_,this.high_|e.high_)};Timestamp.prototype.xor=function(e){return Timestamp.fromBits(this.low_^e.low_,this.high_^e.high_)};Timestamp.prototype.shiftLeft=function(e){e&=63;if(e===0){return this}else{var t=this.low_;if(e<32){var r=this.high_;return Timestamp.fromBits(t<>>32-e)}else{return Timestamp.fromBits(0,t<>>e|t<<32-e,t>>e)}else{return Timestamp.fromBits(t>>e-32,t>=0?0:-1)}}};Timestamp.prototype.shiftRightUnsigned=function(e){e&=63;if(e===0){return this}else{var t=this.high_;if(e<32){var r=this.low_;return Timestamp.fromBits(r>>>e|t<<32-e,t>>>e)}else if(e===32){return Timestamp.fromBits(t,0)}else{return Timestamp.fromBits(t>>>e-32,0)}}};Timestamp.fromInt=function(e){if(-128<=e&&e<128){var t=Timestamp.INT_CACHE_[e];if(t){return t}}var r=new Timestamp(e|0,e<0?-1:0);if(-128<=e&&e<128){Timestamp.INT_CACHE_[e]=r}return r};Timestamp.fromNumber=function(e){if(isNaN(e)||!isFinite(e)){return Timestamp.ZERO}else if(e<=-Timestamp.TWO_PWR_63_DBL_){return Timestamp.MIN_VALUE}else if(e+1>=Timestamp.TWO_PWR_63_DBL_){return Timestamp.MAX_VALUE}else if(e<0){return Timestamp.fromNumber(-e).negate()}else{return new Timestamp(e%Timestamp.TWO_PWR_32_DBL_|0,e/Timestamp.TWO_PWR_32_DBL_|0)}};Timestamp.fromBits=function(e,t){return new Timestamp(e,t)};Timestamp.fromString=function(e,t){if(e.length===0){throw Error("number format error: empty string")}var r=t||10;if(r<2||36=0){throw Error('number format error: interior "-" character: '+e)}var n=Timestamp.fromNumber(Math.pow(r,8));var o=Timestamp.ZERO;for(var s=0;s{var n=r(4300).Buffer;var o=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array!=="undefined"){o=new Int32Array(o)}function ensureBuffer(e){if(n.isBuffer(e)){return e}var t=typeof n.alloc==="function"&&typeof n.from==="function";if(typeof e==="number"){return t?n.alloc(e):new n(e)}else if(typeof e==="string"){return t?n.from(e):new n(e)}else{throw new Error("input must be buffer, number, or string, received "+typeof e)}}function bufferizeInt(e){var t=ensureBuffer(4);t.writeInt32BE(e,0);return t}function _crc32(e,t){e=ensureBuffer(e);if(n.isBuffer(t)){t=t.readUInt32BE(0)}var r=~~t^-1;for(var s=0;s>>8}return r^-1}function crc32(){return bufferizeInt(_crc32.apply(null,arguments))}crc32.signed=function(){return _crc32.apply(null,arguments)};crc32.unsigned=function(){return _crc32.apply(null,arguments)>>>0};e.exports=crc32},1362:e=>{"use strict";const t=/[\p{Lu}]/u;const r=/[\p{Ll}]/u;const n=/^[\p{Lu}](?![\p{Lu}])/gu;const o=/([\p{Alpha}\p{N}_]|$)/u;const s=/[_.\- ]+/;const i=new RegExp("^"+s.source);const a=new RegExp(s.source+o.source,"gu");const A=new RegExp("\\d+"+o.source,"gu");const preserveCamelCase=(e,n,o)=>{let s=false;let i=false;let a=false;for(let A=0;A{n.lastIndex=0;return e.replace(n,(e=>t(e)))};const postProcess=(e,t)=>{a.lastIndex=0;A.lastIndex=0;return e.replace(a,((e,r)=>t(r))).replace(A,(e=>t(e)))};const camelCase=(e,t)=>{if(!(typeof e==="string"||Array.isArray(e))){throw new TypeError("Expected the input to be `string | string[]`")}t={pascalCase:false,preserveConsecutiveUppercase:false,...t};if(Array.isArray(e)){e=e.map((e=>e.trim())).filter((e=>e.length)).join("-")}else{e=e.trim()}if(e.length===0){return""}const r=t.locale===false?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale);const n=t.locale===false?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);if(e.length===1){return t.pascalCase?n(e):r(e)}const o=e!==r(e);if(o){e=preserveCamelCase(e,r,n)}e=e.replace(i,"");if(t.preserveConsecutiveUppercase){e=preserveConsecutiveUppercase(e,r)}else{e=r(e)}if(t.pascalCase){e=n(e.charAt(0))+e.slice(1)}return postProcess(e,n)};e.exports=camelCase;e.exports["default"]=camelCase},9930:(e,t,r)=>{var n=r(1017);e.exports=function(e,t){if(t){var r=t.map((function(t){return n.resolve(e,t)}))}else{var r=e}var o=r.slice(1).reduce((function(e,t){if(!t.match(/^([A-Za-z]:)?\/|\\/)){throw new Error("relative path without a basedir")}var r=t.split(/\/+|\\+/);for(var n=0;e[n]===r[n]&&n1?o.join("/"):"/"}},6891:e=>{e.exports=function(e,r){var n=[];for(var o=0;o{t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.storage=localstorage();t.destroy=(()=>{let e=false;return()=>{if(!e){e=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(t){t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff);if(!this.useColors){return}const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0;let o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{if(e==="%%"){return}n++;if(e==="%c"){o=n}}));t.splice(o,0,r)}t.log=console.debug||console.log||(()=>{});function save(e){try{if(e){t.storage.setItem("debug",e)}else{t.storage.removeItem("debug")}}catch(e){}}function load(){let e;try{e=t.storage.getItem("debug")}catch(e){}if(!e&&typeof process!=="undefined"&&"env"in process){e=process.env.DEBUG}return e}function localstorage(){try{return localStorage}catch(e){}}e.exports=r(6243)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},6243:(e,t,r)=>{function setup(e){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=r(900);createDebug.destroy=destroy;Object.keys(e).forEach((t=>{createDebug[t]=e[t]}));createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let t=0;for(let r=0;r{if(t==="%%"){return"%"}s++;const o=createDebug.formatters[n];if(typeof o==="function"){const n=e[s];t=o.call(r,n);e.splice(s,1);s--}return t}));createDebug.formatArgs.call(r,e);const i=r.log||createDebug.log;i.apply(r,e)}debug.namespace=e;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(e);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>r===null?createDebug.enabled(e):r,set:e=>{r=e}});if(typeof createDebug.init==="function"){createDebug.init(debug)}return debug}function extend(e,t){const r=createDebug(this.namespace+(typeof t==="undefined"?":":t)+e);r.log=this.log;return r}function enable(e){createDebug.save(e);createDebug.names=[];createDebug.skips=[];let t;const r=(typeof e==="string"?e:"").split(/[\s,]+/);const n=r.length;for(t=0;t"-"+e))].join(",");createDebug.enable("");return e}function enabled(e){if(e[e.length-1]==="*"){return true}let t;let r;for(t=0,r=createDebug.skips.length;t{if(typeof process==="undefined"||process.type==="renderer"||process.browser===true||process.__nwjs){e.exports=r(8222)}else{e.exports=r(5332)}},5332:(e,t,r)=>{const n=r(6224);const o=r(3837);t.init=init;t.log=log;t.formatArgs=formatArgs;t.save=save;t.load=load;t.useColors=useColors;t.destroy=o.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");t.colors=[6,2,3,4,5,1];try{const e=r(9318);if(e&&(e.stderr||e).level>=2){t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];if(/^(yes|on|true|enabled)$/i.test(n)){n=true}else if(/^(no|off|false|disabled)$/i.test(n)){n=false}else if(n==="null"){n=null}else{n=Number(n)}e[r]=n;return e}),{});function useColors(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(t){const{namespace:r,useColors:n}=this;if(n){const n=this.color;const o="[3"+(n<8?n:"8;5;"+n);const s=` ${o};1m${r} `;t[0]=s+t[0].split("\n").join("\n"+s);t.push(o+"m+"+e.exports.humanize(this.diff)+"")}else{t[0]=getDate()+r+" "+t[0]}}function getDate(){if(t.inspectOpts.hideDate){return""}return(new Date).toISOString()+" "}function log(...e){return process.stderr.write(o.format(...e)+"\n")}function save(e){if(e){process.env.DEBUG=e}else{delete process.env.DEBUG}}function load(){return process.env.DEBUG}function init(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;ne.trim())).join(" ")};s.O=function(e){this.inspectOpts.colors=this.useColors;return o.inspect(e,this.inspectOpts)}},2342:e=>{"use strict";function Denque(e,t){var t=t||{};this._head=0;this._tail=0;this._capacity=t.capacity;this._capacityMask=3;this._list=new Array(4);if(Array.isArray(e)){this._fromArray(e)}}Denque.prototype.peekAt=function peekAt(e){var t=e;if(t!==(t|0)){return void 0}var r=this.size();if(t>=r||t<-r)return undefined;if(t<0)t+=r;t=this._head+t&this._capacityMask;return this._list[t]};Denque.prototype.get=function get(e){return this.peekAt(e)};Denque.prototype.peek=function peek(){if(this._head===this._tail)return undefined;return this._list[this._head]};Denque.prototype.peekFront=function peekFront(){return this.peek()};Denque.prototype.peekBack=function peekBack(){return this.peekAt(-1)};Object.defineProperty(Denque.prototype,"length",{get:function length(){return this.size()}});Denque.prototype.size=function size(){if(this._head===this._tail)return 0;if(this._headthis._capacity)this.pop();if(this._head1e4&&this._tail<=this._list.length>>>2)this._shrinkArray();return t};Denque.prototype.push=function push(e){if(e===undefined)return this.size();var t=this._tail;this._list[t]=e;this._tail=t+1&this._capacityMask;if(this._tail===this._head){this._growArray()}if(this._capacity&&this.size()>this._capacity){this.shift()}if(this._head1e4&&e<=t>>>2)this._shrinkArray();return r};Denque.prototype.removeOne=function removeOne(e){var t=e;if(t!==(t|0)){return void 0}if(this._head===this._tail)return void 0;var r=this.size();var n=this._list.length;if(t>=r||t<-r)return void 0;if(t<0)t+=r;t=this._head+t&this._capacityMask;var o=this._list[t];var s;if(e0;s--){this._list[t]=this._list[t=t-1+n&this._capacityMask]}this._list[t]=void 0;this._head=this._head+1+n&this._capacityMask}else{for(s=r-1-e;s>0;s--){this._list[t]=this._list[t=t+1+n&this._capacityMask]}this._list[t]=void 0;this._tail=this._tail-1+n&this._capacityMask}return o};Denque.prototype.remove=function remove(e,t){var r=e;var n;var o=t;if(r!==(r|0)){return void 0}if(this._head===this._tail)return void 0;var s=this.size();var i=this._list.length;if(r>=s||r<-s||t<1)return void 0;if(r<0)r+=s;if(t===1||!t){n=new Array(1);n[0]=this.removeOne(r);return n}if(r===0&&r+t>=s){n=this.toArray();this.clear();return n}if(r+t>s)t=s-r;var a;n=new Array(t);for(a=0;a0;a--){this._list[r=r+1+i&this._capacityMask]=void 0}return n}if(e===0){this._head=this._head+t+i&this._capacityMask;for(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])}r=this._head-1+i&this._capacityMask;while(o>0){this._list[r=r-1+i&this._capacityMask]=void 0;o--}if(e<0)this._tail=r}else{this._tail=r;r=r+t+i&this._capacityMask;for(a=s-(t+e);a>0;a--){this.push(this._list[r++])}r=this._tail;while(o>0){this._list[r=r+1+i&this._capacityMask]=void 0;o--}}if(this._head<2&&this._tail>1e4&&this._tail<=i>>>2)this._shrinkArray();return n};Denque.prototype.splice=function splice(e,t){var r=e;if(r!==(r|0)){return void 0}var n=this.size();if(r<0)r+=n;if(r>n)return void 0;if(arguments.length>2){var o;var s;var i;var a=arguments.length;var A=this._list.length;var c=2;if(!n||r0){this._head=this._head+r+A&this._capacityMask}}else{i=this.remove(r,t);this._head=this._head+r+A&this._capacityMask}while(a>c){this.unshift(arguments[--a])}for(o=r;o>0;o--){this.unshift(s[o-1])}}else{s=new Array(n-(r+t));var l=s.length;for(o=0;othis._tail){for(o=this._head;o>>=1;this._capacityMask>>>=1};e.exports=Denque},1205:(e,t,r)=>{var n=r(1223);var noop=function(){};var isRequest=function(e){return e.setHeader&&typeof e.abort==="function"};var isChildProcess=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3};var eos=function(e,t,r){if(typeof t==="function")return eos(e,null,t);if(!t)t={};r=n(r||noop);var o=e._writableState;var s=e._readableState;var i=t.readable||t.readable!==false&&e.readable;var a=t.writable||t.writable!==false&&e.writable;var A=false;var onlegacyfinish=function(){if(!e.writable)onfinish()};var onfinish=function(){a=false;if(!i)r.call(e)};var onend=function(){i=false;if(!a)r.call(e)};var onexit=function(t){r.call(e,t?new Error("exited with error code: "+t):null)};var onerror=function(t){r.call(e,t)};var onclose=function(){process.nextTick(onclosenexttick)};var onclosenexttick=function(){if(A)return;if(i&&!(s&&(s.ended&&!s.destroyed)))return r.call(e,new Error("premature close"));if(a&&!(o&&(o.ended&&!o.destroyed)))return r.call(e,new Error("premature close"))};var onrequest=function(){e.req.on("finish",onfinish)};if(isRequest(e)){e.on("complete",onfinish);e.on("abort",onclose);if(e.req)onrequest();else e.on("request",onrequest)}else if(a&&!o){e.on("end",onlegacyfinish);e.on("close",onlegacyfinish)}if(isChildProcess(e))e.on("exit",onexit);e.on("end",onend);e.on("finish",onfinish);if(t.error!==false)e.on("error",onerror);e.on("close",onclose);return function(){A=true;e.removeListener("complete",onfinish);e.removeListener("abort",onclose);e.removeListener("request",onrequest);if(e.req)e.req.removeListener("finish",onfinish);e.removeListener("end",onlegacyfinish);e.removeListener("close",onlegacyfinish);e.removeListener("finish",onfinish);e.removeListener("exit",onexit);e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose)}};e.exports=eos},5010:(e,t,r)=>{var n=r(7147);var o=r(3837);var s=r(2781);var i=s.Readable;var a=s.Writable;var A=s.PassThrough;var c=r(4833);var l=r(2361).EventEmitter;t.createFromBuffer=createFromBuffer;t.createFromFd=createFromFd;t.BufferSlicer=BufferSlicer;t.FdSlicer=FdSlicer;o.inherits(FdSlicer,l);function FdSlicer(e,t){t=t||{};l.call(this);this.fd=e;this.pend=new c;this.pend.max=1;this.refCount=0;this.autoClose=!!t.autoClose}FdSlicer.prototype.read=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.read(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.write=function(e,t,r,o,s){var i=this;i.pend.go((function(a){n.write(i.fd,e,t,r,o,(function(e,t,r){a();s(e,t,r)}))}))};FdSlicer.prototype.createReadStream=function(e){return new ReadStream(this,e)};FdSlicer.prototype.createWriteStream=function(e){return new WriteStream(this,e)};FdSlicer.prototype.ref=function(){this.refCount+=1};FdSlicer.prototype.unref=function(){var e=this;e.refCount-=1;if(e.refCount>0)return;if(e.refCount<0)throw new Error("invalid unref");if(e.autoClose){n.close(e.fd,onCloseDone)}function onCloseDone(t){if(t){e.emit("error",t)}else{e.emit("close")}}};o.inherits(ReadStream,i);function ReadStream(e,t){t=t||{};i.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end;this.pos=this.start;this.destroyed=false}ReadStream.prototype._read=function(e){var t=this;if(t.destroyed)return;var r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null){r=Math.min(r,t.endOffset-t.pos)}if(r<=0){t.destroyed=true;t.push(null);t.context.unref();return}t.context.pend.go((function(e){if(t.destroyed)return e();var o=new Buffer(r);n.read(t.context.fd,o,0,r,t.pos,(function(r,n){if(r){t.destroy(r)}else if(n===0){t.destroyed=true;t.push(null);t.context.unref()}else{t.pos+=n;t.push(o.slice(0,n))}e()}))}))};ReadStream.prototype.destroy=function(e){if(this.destroyed)return;e=e||new Error("stream destroyed");this.destroyed=true;this.emit("error",e);this.context.unref()};o.inherits(WriteStream,a);function WriteStream(e,t){t=t||{};a.call(this,t);this.context=e;this.context.ref();this.start=t.start||0;this.endOffset=t.end==null?Infinity:+t.end;this.bytesWritten=0;this.pos=this.start;this.destroyed=false;this.on("finish",this.destroy.bind(this))}WriteStream.prototype._write=function(e,t,r){var o=this;if(o.destroyed)return;if(o.pos+e.length>o.endOffset){var s=new Error("maximum file length exceeded");s.code="ETOOBIG";o.destroy();r(s);return}o.context.pend.go((function(t){if(o.destroyed)return t();n.write(o.context.fd,e,0,e.length,o.pos,(function(e,n){if(e){o.destroy();t();r(e)}else{o.bytesWritten+=n;o.pos+=n;o.emit("progress");t();r()}}))}))};WriteStream.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=true;this.context.unref()};o.inherits(BufferSlicer,l);function BufferSlicer(e,t){l.call(this);t=t||{};this.refCount=0;this.buffer=e;this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}BufferSlicer.prototype.read=function(e,t,r,n,o){var s=n+r;var i=s-this.buffer.length;var a=i>0?i:r;this.buffer.copy(e,t,n,s);setImmediate((function(){o(null,a)}))};BufferSlicer.prototype.write=function(e,t,r,n,o){e.copy(this.buffer,n,t,t+r);setImmediate((function(){o(null,r,e)}))};BufferSlicer.prototype.createReadStream=function(e){e=e||{};var t=new A(e);t.destroyed=false;t.start=e.start||0;t.endOffset=e.end;t.pos=t.endOffset||this.buffer.length;var r=this.buffer.slice(t.start,t.pos);var n=0;while(true){var o=n+this.maxChunkSize;if(o>=r.length){if(nr.endOffset){var i=new Error("maximum file length exceeded");i.code="ETOOBIG";r.destroyed=true;o(i);return}e.copy(t.buffer,r.pos,0,e.length);r.bytesWritten+=e.length;r.pos=s;r.emit("progress");o()};r.destroy=function(){r.destroyed=true};return r};BufferSlicer.prototype.ref=function(){this.refCount+=1};BufferSlicer.prototype.unref=function(){this.refCount-=1;if(this.refCount<0){throw new Error("invalid unref")}};function createFromBuffer(e,t){return new BufferSlicer(e,t)}function createFromFd(e,t){return new FdSlicer(e,t)}},7281:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(9930);const i=r(8098);const a=r(9126);const{env:A,cwd:c}=process;const isWritable=e=>{try{o.accessSync(e,o.constants.W_OK);return true}catch(e){return false}};function useDirectory(e,t){if(t.create){a.sync(e)}if(t.thunk){return(...t)=>n.join(e,...t)}return e}function getNodeModuleDirectory(e){const t=n.join(e,"node_modules");if(!isWritable(t)&&(o.existsSync(t)||!isWritable(n.join(e)))){return}return t}e.exports=(e={})=>{if(A.CACHE_DIR&&!["true","false","1","0"].includes(A.CACHE_DIR)){return useDirectory(n.join(A.CACHE_DIR,e.name),e)}let{cwd:t=c()}=e;if(e.files){t=s(t,e.files)}t=i.sync(t);if(!t){return}const r=getNodeModuleDirectory(t);if(!r){return undefined}return useDirectory(n.join(t,"node_modules",".cache",e.name),e)}},3186:(e,t,r)=>{e.exports=r(7147).constants||r(2057)},6863:(e,t,r)=>{e.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var n=r(7147);var o=n.realpath;var s=n.realpathSync;var i=process.version;var a=/^v[0-5]\./.test(i);var A=r(1734);function newError(e){return e&&e.syscall==="realpath"&&(e.code==="ELOOP"||e.code==="ENOMEM"||e.code==="ENAMETOOLONG")}function realpath(e,t,r){if(a){return o(e,t,r)}if(typeof t==="function"){r=t;t=null}o(e,t,(function(n,o){if(newError(n)){A.realpath(e,t,r)}else{r(n,o)}}))}function realpathSync(e,t){if(a){return s(e,t)}try{return s(e,t)}catch(r){if(newError(r)){return A.realpathSync(e,t)}else{throw r}}}function monkeypatch(){n.realpath=realpath;n.realpathSync=realpathSync}function unmonkeypatch(){n.realpath=o;n.realpathSync=s}},1734:(e,t,r)=>{var n=r(1017);var o=process.platform==="win32";var s=r(7147);var i=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function rethrow(){var e;if(i){var t=new Error;e=debugCallback}else e=missingCallback;return e;function debugCallback(e){if(e){t.message=e.message;e=t;missingCallback(e)}}function missingCallback(e){if(e){if(process.throwDeprecation)throw e;else if(!process.noDeprecation){var t="fs: missing callback "+(e.stack||e.message);if(process.traceDeprecation)console.trace(t);else console.error(t)}}}}function maybeCallback(e){return typeof e==="function"?e:rethrow()}var a=n.normalize;if(o){var A=/(.*?)(?:[\/\\]+|$)/g}else{var A=/(.*?)(?:[\/]+|$)/g}if(o){var c=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/}else{var c=/^[\/]*/}t.realpathSync=function realpathSync(e,t){e=n.resolve(e);if(t&&Object.prototype.hasOwnProperty.call(t,e)){return t[e]}var r=e,i={},a={};var l;var u;var h;var d;start();function start(){var t=c.exec(e);l=t[0].length;u=t[0];h=t[0];d="";if(o&&!a[h]){s.lstatSync(h);a[h]=true}}while(l=e.length){if(t)t[i]=e;return r(null,e)}A.lastIndex=u;var n=A.exec(e);g=h;h+=n[0];d=g+n[1];u=A.lastIndex;if(l[d]||t&&t[d]===d){return process.nextTick(LOOP)}if(t&&Object.prototype.hasOwnProperty.call(t,d)){return gotResolvedLink(t[d])}return s.lstat(d,gotStat)}function gotStat(e,n){if(e)return r(e);if(!n.isSymbolicLink()){l[d]=true;if(t)t[d]=d;return process.nextTick(LOOP)}if(!o){var i=n.dev.toString(32)+":"+n.ino.toString(32);if(a.hasOwnProperty(i)){return gotTarget(null,a[i],d)}}s.stat(d,(function(e){if(e)return r(e);s.readlink(d,(function(e,t){if(!o)a[i]=t;gotTarget(e,t)}))}))}function gotTarget(e,o,s){if(e)return r(e);var i=n.resolve(g,o);if(t)t[s]=i;gotResolvedLink(i)}function gotResolvedLink(t){e=n.resolve(t,e.slice(u));start()}}},3002:(e,t,r)=>{"use strict";const n=r(1808);class Locked extends Error{constructor(e){super(`${e} is locked`)}}const o={old:new Set,young:new Set};const s=1e3*15;let i;const getAvailablePort=e=>new Promise(((t,r)=>{const o=n.createServer();o.unref();o.on("error",r);o.listen(e,(()=>{const{port:e}=o.address();o.close((()=>{t(e)}))}))}));const portCheckSequence=function*(e){if(e){yield*e}yield 0};e.exports=async e=>{let t;if(e){t=typeof e.port==="number"?[e.port]:e.port}if(i===undefined){i=setInterval((()=>{o.old=o.young;o.young=new Set}),s);if(i.unref){i.unref()}}for(const r of portCheckSequence(t)){try{let t=await getAvailablePort({...e,port:r});while(o.old.has(t)||o.young.has(t)){if(r!==0){throw new Locked(r)}t=await getAvailablePort({...e,port:r})}o.young.add(t);return t}catch(e){if(!["EADDRINUSE","EACCES"].includes(e.code)&&!(e instanceof Locked)){throw e}}}throw new Error("No available ports found")};e.exports.makeRange=(e,t)=>{if(!Number.isInteger(e)||!Number.isInteger(t)){throw new TypeError("`from` and `to` must be integer numbers")}if(e<1024||e>65535){throw new RangeError("`from` must be between 1024 and 65535")}if(t<1024||t>65536){throw new RangeError("`to` must be between 1024 and 65536")}if(t{t.setopts=setopts;t.ownProp=ownProp;t.makeAbs=makeAbs;t.finish=finish;t.mark=mark;t.isIgnored=isIgnored;t.childrenIgnored=childrenIgnored;function ownProp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var n=r(1017);var o=r(3973);var s=r(8714);var i=o.Minimatch;function alphasort(e,t){return e.localeCompare(t,"en")}function setupIgnores(e,t){e.ignore=t.ignore||[];if(!Array.isArray(e.ignore))e.ignore=[e.ignore];if(e.ignore.length){e.ignore=e.ignore.map(ignoreMap)}}function ignoreMap(e){var t=null;if(e.slice(-3)==="/**"){var r=e.replace(/(\/\*\*)+$/,"");t=new i(r,{dot:true})}return{matcher:new i(e,{dot:true}),gmatcher:t}}function setopts(e,t,r){if(!r)r={};if(r.matchBase&&-1===t.indexOf("/")){if(r.noglobstar){throw new Error("base matching requires globstar")}t="**/"+t}e.silent=!!r.silent;e.pattern=t;e.strict=r.strict!==false;e.realpath=!!r.realpath;e.realpathCache=r.realpathCache||Object.create(null);e.follow=!!r.follow;e.dot=!!r.dot;e.mark=!!r.mark;e.nodir=!!r.nodir;if(e.nodir)e.mark=true;e.sync=!!r.sync;e.nounique=!!r.nounique;e.nonull=!!r.nonull;e.nosort=!!r.nosort;e.nocase=!!r.nocase;e.stat=!!r.stat;e.noprocess=!!r.noprocess;e.absolute=!!r.absolute;e.maxLength=r.maxLength||Infinity;e.cache=r.cache||Object.create(null);e.statCache=r.statCache||Object.create(null);e.symlinks=r.symlinks||Object.create(null);setupIgnores(e,r);e.changedCwd=false;var o=process.cwd();if(!ownProp(r,"cwd"))e.cwd=o;else{e.cwd=n.resolve(r.cwd);e.changedCwd=e.cwd!==o}e.root=r.root||n.resolve(e.cwd,"/");e.root=n.resolve(e.root);if(process.platform==="win32")e.root=e.root.replace(/\\/g,"/");e.cwdAbs=s(e.cwd)?e.cwd:makeAbs(e,e.cwd);if(process.platform==="win32")e.cwdAbs=e.cwdAbs.replace(/\\/g,"/");e.nomount=!!r.nomount;r.nonegate=true;r.nocomment=true;e.minimatch=new i(t,r);e.options=e.minimatch.options}function finish(e){var t=e.nounique;var r=t?[]:Object.create(null);for(var n=0,o=e.matches.length;n{e.exports=glob;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(4124);var A=r(2361).EventEmitter;var c=r(1017);var l=r(9491);var u=r(8714);var h=r(9010);var d=r(7625);var g=d.setopts;var p=d.ownProp;var E=r(2492);var m=r(3837);var C=d.childrenIgnored;var I=d.isIgnored;var y=r(1223);function glob(e,t,r){if(typeof t==="function")r=t,t={};if(!t)t={};if(t.sync){if(r)throw new TypeError("callback provided to sync glob");return h(e,t)}return new Glob(e,t,r)}glob.sync=h;var B=glob.GlobSync=h.GlobSync;glob.glob=glob;function extend(e,t){if(t===null||typeof t!=="object"){return e}var r=Object.keys(t);var n=r.length;while(n--){e[r[n]]=t[r[n]]}return e}glob.hasMagic=function(e,t){var r=extend({},t);r.noprocess=true;var n=new Glob(e,r);var o=n.minimatch.set;if(!e)return false;if(o.length>1)return true;for(var s=0;sthis.maxLength)return t();if(!this.stat&&p(this.cache,r)){var s=this.cache[r];if(Array.isArray(s))s="DIR";if(!o||s==="DIR")return t(null,s);if(o&&s==="FILE")return t()}var i;var a=this.statCache[r];if(a!==undefined){if(a===false)return t(null,a);else{var A=a.isDirectory()?"DIR":"FILE";if(o&&A==="FILE")return t();else return t(null,A,a)}}var c=this;var l=E("stat\0"+r,lstatcb_);if(l)n.lstat(r,l);function lstatcb_(o,s){if(s&&s.isSymbolicLink()){return n.stat(r,(function(n,o){if(n)c._stat2(e,r,null,s,t);else c._stat2(e,r,n,o,t)}))}else{c._stat2(e,r,o,s,t)}}};Glob.prototype._stat2=function(e,t,r,n,o){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR")){this.statCache[t]=false;return o()}var s=e.slice(-1)==="/";this.statCache[t]=n;if(t.slice(-1)==="/"&&n&&!n.isDirectory())return o(null,false,n);var i=true;if(n)i=n.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||i;if(s&&i==="FILE")return o();return o(null,i,n)}},9010:(e,t,r)=>{e.exports=globSync;globSync.GlobSync=GlobSync;var n=r(7147);var o=r(6863);var s=r(3973);var i=s.Minimatch;var a=r(1957).Glob;var A=r(3837);var c=r(1017);var l=r(9491);var u=r(8714);var h=r(7625);var d=h.setopts;var g=h.ownProp;var p=h.childrenIgnored;var E=h.isIgnored;function globSync(e,t){if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(e,t).found}function GlobSync(e,t){if(!e)throw new Error("must provide pattern");if(typeof t==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(e,t);d(this,e,t);if(this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;nthis.maxLength)return false;if(!this.stat&&g(this.cache,t)){var o=this.cache[t];if(Array.isArray(o))o="DIR";if(!r||o==="DIR")return o;if(r&&o==="FILE")return false}var s;var i=this.statCache[t];if(!i){var a;try{a=n.lstatSync(t)}catch(e){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[t]=false;return false}}if(a&&a.isSymbolicLink()){try{i=n.statSync(t)}catch(e){i=a}}else{i=a}}this.statCache[t]=i;var o=true;if(i)o=i.isDirectory()?"DIR":"FILE";this.cache[t]=this.cache[t]||o;if(r&&o==="FILE")return false;return o};GlobSync.prototype._mark=function(e){return h.mark(this,e)};GlobSync.prototype._makeAbs=function(e){return h.makeAbs(this,e)}},1621:e=>{"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":e.length===1?"-":"--";const n=t.indexOf(r+e);const o=t.indexOf("--");return n!==-1&&(o===-1||n{h("replaying proxy buffer for failed request");A.default(e.listenerCount("data")>0);e.push(C);e.push(null)}));return I}))}}t["default"]=HttpsProxyAgent;function resume(e){e.resume()}function isDefaultPort(e,t){return Boolean(!t&&e===80||t&&e===443)}function isHTTPS(e){return typeof e==="string"?/^https:?$/i.test(e):false}function omit(e,...t){const r={};let n;for(n in e){if(!t.includes(n)){r[n]=e[n]}}return r}},7219:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};const o=n(r(3734));function createHttpsProxyAgent(e){return new o.default(e)}(function(e){e.HttpsProxyAgent=o.default;e.prototype=o.default.prototype})(createHttpsProxyAgent||(createHttpsProxyAgent={}));e.exports=createHttpsProxyAgent},595:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=n(r(8237));const s=o.default("https-proxy-agent:parse-proxy-response");function parseProxyResponse(e){return new Promise(((t,r)=>{let n=0;const o=[];function read(){const t=e.read();if(t)ondata(t);else e.once("readable",read)}function cleanup(){e.removeListener("end",onend);e.removeListener("error",onerror);e.removeListener("close",onclose);e.removeListener("readable",read)}function onclose(e){s("onclose had error %o",e)}function onend(){s("onend")}function onerror(e){cleanup();s("onerror %o",e);r(e)}function ondata(e){o.push(e);n+=e.length;const r=Buffer.concat(o,n);const i=r.indexOf("\r\n\r\n");if(i===-1){s("have not received end of HTTP headers yet...");read();return}const a=r.toString("ascii",0,r.indexOf("\r\n"));const A=+a.split(" ")[1];s("got proxy server response: %o",a);t({statusCode:A,buffered:r})}e.on("error",onerror);e.on("close",onclose);e.on("end",onend);read()}))}t["default"]=parseProxyResponse},2492:(e,t,r)=>{var n=r(2940);var o=Object.create(null);var s=r(1223);e.exports=n(inflight);function inflight(e,t){if(o[e]){o[e].push(t);return null}else{o[e]=[t];return makeres(e)}}function makeres(e){return s((function RES(){var t=o[e];var r=t.length;var n=slice(arguments);try{for(var s=0;sr){t.splice(0,r);process.nextTick((function(){RES.apply(null,n)}))}else{delete o[e]}}}))}function slice(e){var t=e.length;var r=[];for(var n=0;n{try{var n=r(3837);if(typeof n.inherits!=="function")throw"";e.exports=n.inherits}catch(t){e.exports=r(8544)}},8544:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9126:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const{promisify:s}=r(3837);const i=r(1383);const a=i.satisfies(process.version,">=10.12.0");const checkPath=e=>{if(process.platform==="win32"){const t=/[<>:"|?*]/.test(e.replace(o.parse(e).root,""));if(t){const t=new Error(`Path contains invalid characters: ${e}`);t.code="EINVAL";throw t}}};const processOptions=e=>{const t={mode:511,fs:n};return{...t,...e}};const permissionError=e=>{const t=new Error(`operation not permitted, mkdir '${e}'`);t.code="EPERM";t.errno=-4048;t.path=e;t.syscall="mkdir";return t};const makeDir=async(e,t)=>{checkPath(e);t=processOptions(t);const r=s(t.fs.mkdir);const i=s(t.fs.stat);if(a&&t.fs.mkdir===n.mkdir){const n=o.resolve(e);await r(n,{mode:t.mode,recursive:true});return n}const make=async e=>{try{await r(e,t.mode);return e}catch(t){if(t.code==="EPERM"){throw t}if(t.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(t.message.includes("null bytes")){throw t}await make(o.dirname(e));return make(e)}try{const t=await i(e);if(!t.isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw t}return e}};return make(o.resolve(e))};e.exports=makeDir;e.exports.sync=(e,t)=>{checkPath(e);t=processOptions(t);if(a&&t.fs.mkdirSync===n.mkdirSync){const r=o.resolve(e);n.mkdirSync(r,{mode:t.mode,recursive:true});return r}const make=e=>{try{t.fs.mkdirSync(e,t.mode)}catch(r){if(r.code==="EPERM"){throw r}if(r.code==="ENOENT"){if(o.dirname(e)===e){throw permissionError(e)}if(r.message.includes("null bytes")){throw r}make(o.dirname(e));return make(e)}try{if(!t.fs.statSync(e).isDirectory()){throw new Error("The path is not a directory")}}catch(e){throw r}}return e};return make(o.resolve(e))}},1446:(e,t,r)=>{const n=r(6113);const o=r(7147);const s=8192;function md5FileSync(e){const t=o.openSync(e,"r");const r=n.createHash("md5");const i=Buffer.alloc(s);try{let e;do{e=o.readSync(t,i,0,s);r.update(i.slice(0,e))}while(e===s)}finally{o.closeSync(t)}return r.digest("hex")}function md5File(e){return new Promise(((t,r)=>{const s=n.createHash("md5");const i=o.createReadStream(e);i.on("error",(e=>{r(e)}));s.once("readable",(()=>{t(s.read().toString("hex"))}));i.pipe(s)}))}e.exports=md5File;e.exports.sync=md5FileSync},1529:e=>{e.exports=Pager;function Pager(e,t){if(!(this instanceof Pager))return new Pager(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?alloc(this.deduplicate.length):null}Pager.prototype.updated=function(e){while(this.deduplicate&&e.buffer[e.deduplicate]===this.deduplicate[e.deduplicate]){e.deduplicate++;if(e.deduplicate===this.deduplicate.length){e.deduplicate=0;if(e.buffer.equals&&e.buffer.equals(this.deduplicate))e.buffer=this.deduplicate;break}}if(e.updated||!this.updates)return;e.updated=true;this.updates.push(e)};Pager.prototype.lastUpdate=function(){if(!this.updates||!this.updates.length)return null;var e=this.updates.pop();e.updated=false;return e};Pager.prototype._array=function(e,t){if(e>=this.maxPages){if(t)return;grow(this,e)}factor(e,this.path);var r=this.pages;for(var n=this.level;n>0;n--){var o=this.path[n];var s=r[o];if(!s){if(t)return;s=r[o]=new Array(32768)}r=s}return r};Pager.prototype.get=function(e,t){var r=this._array(e,t);var n=this.path[0];var o=r&&r[n];if(!o&&!t){o=r[n]=new Page(e,alloc(this.pageSize));if(e>=this.length)this.length=e+1}if(o&&o.buffer===this.deduplicate&&this.deduplicate&&!t){o.buffer=copy(o.buffer);o.deduplicate=0}return o};Pager.prototype.set=function(e,t){var r=this._array(e,false);var n=this.path[0];if(e>=this.length)this.length=e+1;if(!t||this.zeros&&t.equals&&t.equals(this.zeros)){r[n]=undefined;return}if(this.deduplicate&&t.equals&&t.equals(this.deduplicate)){t=this.deduplicate}var o=r[n];var s=truncate(t,this.pageSize);if(o)o.buffer=s;else r[n]=new Page(e,s)};Pager.prototype.toBuffer=function(){var e=new Array(this.length);var t=alloc(this.pageSize);var r=0;while(rt)return e.slice(0,t);var r=alloc(t);e.copy(r);return r}function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function copy(e){var t=Buffer.allocUnsafe?Buffer.allocUnsafe(e.length):new Buffer(e.length);e.copy(t);return t}function Page(e,t){this.offset=e*t.length;this.buffer=t;this.updated=false;this.deduplicate=0}function factor(e,t){e=(e-(t[0]=e&32767))/32768;e=(e-(t[1]=e&32767))/32768;t[3]=(e-(t[2]=e&32767))/32768&32767}},3973:(e,t,r)=>{e.exports=minimatch;minimatch.Minimatch=Minimatch;var n=function(){try{return r(1017)}catch(e){}}()||{sep:"/"};minimatch.sep=n.sep;var o=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={};var s=r(3717);var i={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};var a="[^/]";var A=a+"*?";var c="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var l="(?:(?!(?:\\/|^)\\.).)*?";var u=charSet("().*{}+?[]^$\\!");function charSet(e){return e.split("").reduce((function(e,t){e[t]=true;return e}),{})}var h=/\/+/;minimatch.filter=filter;function filter(e,t){t=t||{};return function(r,n,o){return minimatch(r,e,t)}}function ext(e,t){t=t||{};var r={};Object.keys(e).forEach((function(t){r[t]=e[t]}));Object.keys(t).forEach((function(e){r[e]=t[e]}));return r}minimatch.defaults=function(e){if(!e||typeof e!=="object"||!Object.keys(e).length){return minimatch}var t=minimatch;var r=function minimatch(r,n,o){return t(r,n,ext(e,o))};r.Minimatch=function Minimatch(r,n){return new t.Minimatch(r,ext(e,n))};r.Minimatch.defaults=function defaults(r){return t.defaults(ext(e,r)).Minimatch};r.filter=function filter(r,n){return t.filter(r,ext(e,n))};r.defaults=function defaults(r){return t.defaults(ext(e,r))};r.makeRe=function makeRe(r,n){return t.makeRe(r,ext(e,n))};r.braceExpand=function braceExpand(r,n){return t.braceExpand(r,ext(e,n))};r.match=function(r,n,o){return t.match(r,n,ext(e,o))};return r};Minimatch.defaults=function(e){return minimatch.defaults(e).Minimatch};function minimatch(e,t,r){assertValidPattern(t);if(!r)r={};if(!r.nocomment&&t.charAt(0)==="#"){return false}return new Minimatch(t,r).match(e)}function Minimatch(e,t){if(!(this instanceof Minimatch)){return new Minimatch(e,t)}assertValidPattern(e);if(!t)t={};e=e.trim();if(!t.allowWindowsEscape&&n.sep!=="/"){e=e.split(n.sep).join("/")}this.options=t;this.set=[];this.pattern=e;this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.partial=!!t.partial;this.make()}Minimatch.prototype.debug=function(){};Minimatch.prototype.make=make;function make(){var e=this.pattern;var t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate();var r=this.globSet=this.braceExpand();if(t.debug)this.debug=function debug(){console.error.apply(console,arguments)};this.debug(this.pattern,r);r=this.globParts=r.map((function(e){return e.split(h)}));this.debug(this.pattern,r);r=r.map((function(e,t,r){return e.map(this.parse,this)}),this);this.debug(this.pattern,r);r=r.filter((function(e){return e.indexOf(false)===-1}));this.debug(this.pattern,r);this.set=r}Minimatch.prototype.parseNegate=parseNegate;function parseNegate(){var e=this.pattern;var t=false;var r=this.options;var n=0;if(r.nonegate)return;for(var o=0,s=e.length;od){throw new TypeError("pattern is too long")}};Minimatch.prototype.parse=parse;var g={};function parse(e,t){assertValidPattern(e);var r=this.options;if(e==="**"){if(!r.noglobstar)return o;else e="*"}if(e==="")return"";var n="";var s=!!r.nocase;var c=false;var l=[];var h=[];var d;var p=false;var E=-1;var m=-1;var C=e.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var I=this;function clearStateChar(){if(d){switch(d){case"*":n+=A;s=true;break;case"?":n+=a;s=true;break;default:n+="\\"+d;break}I.debug("clearStateChar %j %j",d,n);d=false}}for(var y=0,B=e.length,Q;y-1;D--){var N=h[D];var T=n.slice(0,N.reStart);var O=n.slice(N.reStart,N.reEnd-8);var _=n.slice(N.reEnd-8,N.reEnd);var M=n.slice(N.reEnd);_+=M;var L=T.split("(").length-1;var F=M;for(y=0;y=0;i--){s=e[i];if(s)break}for(i=0;i>> no match, partial?",e,u,t,h);if(u===a)return true}return false}var g;if(typeof c==="string"){g=l===c;this.debug("string match",c,l,g)}else{g=l.match(c);this.debug("pattern match",c,l,g)}if(!g)return false}if(s===a&&i===A){return true}else if(s===a){return r}else if(i===A){return s===a-1&&e[s]===""}throw new Error("wtf?")};function globUnescape(e){return e.replace(/\\(.)/g,"$1")}function regExpEscape(e){return e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},1257:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoMemoryServer=t.MongoMemoryServerStates=t.MongoMemoryServerEvents=void 0;const n=r(4351);const o=(0,n.__importStar)(r(8517));const s=(0,n.__importDefault)(r(3002));const i=r(1978);const a=r(843);const A=(0,n.__importDefault)(r(8237));const c=r(2361);const l=r(7147);const u=r(5517);const h=r(1383);const d=r(3386);const g=(0,A.default)("MongoMS:MongoMemoryServer");o.setGracefulCleanup();var p;(function(e){e["stateChange"]="stateChange"})(p=t.MongoMemoryServerEvents||(t.MongoMemoryServerEvents={}));var E;(function(e){e["new"]="new";e["starting"]="starting";e["running"]="running";e["stopped"]="stopped"})(E=t.MongoMemoryServerStates||(t.MongoMemoryServerStates={}));class MongoMemoryServer extends c.EventEmitter{constructor(e){super();this._state=E.new;this.opts=Object.assign({},e);if(!(0,i.isNullOrUndefined)(this.opts.auth)){this.auth=(0,i.authDefault)(this.opts.auth)}}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("create: Called .create() method");const t=new MongoMemoryServer(Object.assign({},e));yield t.start();return t}))}start(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start: Called .start() method");switch(this._state){case E.new:case E.stopped:break;case E.running:case E.starting:default:throw new d.StateError([E.new,E.stopped],this.state)}(0,i.assertion)((0,i.isNullOrUndefined)((t=this._instanceInfo)===null||t===void 0?void 0:t.instance.mongodProcess),new Error('Cannot start because "instance.mongodProcess" is already defined!'));this.stateChange(E.starting);yield this._startUpInstance(e).catch((e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!A.default.enabled("MongoMS:MongoMemoryServer")){console.warn("Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n",e)}this.debug("_startUpInstance threw a Error: ",e);yield this.stop({doCleanup:false,force:false});this.stateChange(E.stopped);throw e}))));this.stateChange(E.running);this.debug("start: Instance fully Started")}))}stateChange(e){this._state=e;this.emit(p.stateChange,e)}debug(e,...t){var r,n;const o=(n=(r=this._instanceInfo)===null||r===void 0?void 0:r.port)!==null&&n!==void 0?n:"unknown";g(`Mongo[${o}]: ${e}`,...t)}getNewPort(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield(0,s.default)({port:e});if(e!=t&&typeof e==="number"){this.debug(`getNewPort: starting with port "${t}", since "${e}" was locked`)}return t}))}getStartOptions(e=false){var t,r,s;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`getStartOptions: forceSamePort: ${e}`);const n=(t=this.opts.instance)!==null&&t!==void 0?t:{};let a=true;let A=typeof n.port==="number"?n.port:undefined;if(!e||(0,i.isNullOrUndefined)(A)){A=yield this.getNewPort(A)}const c={port:A,dbName:(0,i.generateDbName)(n.dbName),ip:(r=n.ip)!==null&&r!==void 0?r:"127.0.0.1",storageEngine:(s=n.storageEngine)!==null&&s!==void 0?s:"ephemeralForTest",replSet:n.replSet,dbPath:n.dbPath,tmpDir:undefined};if((0,i.isNullOrUndefined)(this._instanceInfo)){if(!c.dbPath){c.tmpDir=o.dirSync({mode:493,prefix:"mongo-mem-",unsafeCleanup:true});c.dbPath=c.tmpDir.name;a=true}else{this.debug(`getStartOptions: Checking if "${c.dbPath}}" (no new tmpDir) already has data`);const e=yield l.promises.readdir(c.dbPath);a=e.length===0}}else{a=false}const u=(typeof n.auth==="boolean"?n.auth:true)&&!(0,i.isNullOrUndefined)(this.auth)&&!this.auth.disable&&(this.auth.force||a)&&!n.replSet;return{data:c,createAuth:u,mongodOptions:{instance:Object.assign(Object.assign({},c),{args:n.args,auth:u?false:n.auth}),binary:this.opts.binary,spawn:this.opts.spawn}}}))}_startUpInstance(e=false){var t;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("_startUpInstance: Called MongoMemoryServer._startUpInstance() method");if(!(0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');if(!e){const e=yield this.getNewPort(this._instanceInfo.port);this._instanceInfo.instance.instanceOpts.port=e;this._instanceInfo.port=e}yield this._instanceInfo.instance.start();return}const{mongodOptions:r,createAuth:n,data:o}=yield this.getStartOptions(e);this.debug(`_startUpInstance: Creating new MongoDB instance with options:`,r);const s=yield a.MongoInstance.create(r);this.debug(`_startUpInstance: Instance Started, createAuth: "${n}"`);if(!(0,i.isNullOrUndefined)(this.auth)&&n){this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);yield this.createAuth(o);if(o.storageEngine!=="ephemeralForTest"){this.debug("_startUpInstance: Killing No-Auth instance");yield s.stop();this.debug("_startUpInstance: Starting Auth Instance");s.instanceOpts.auth=true;yield s.start()}else{console.warn("Not Restarting MongoInstance for Auth\n"+'Storage engine is "ephemeralForTest", which does not write data on shutdown, and mongodb does not allow changing "auth" runtime')}}else{if((t=this.opts.auth)===null||t===void 0?void 0:t.disable){this.debug('_startUpInstance: AutomaticAuth.disable is set to "true" skipping "createAuth"')}}this._instanceInfo=Object.assign(Object.assign({},o),{dbPath:o.dbPath,instance:s})}))}stop(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop: Called .stop() method");let n={doCleanup:true,force:false};if(typeof e==="boolean"){n.doCleanup=e}if(typeof e==="object"){n=e}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('stop: "instanceInfo" is not defined (never ran?)');return false}if(this._state===E.stopped){this.debug('stop: state is "stopped", trying to stop / kill anyway')}this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${(r=(t=this._instanceInfo.instance)===null||t===void 0?void 0:t.mongodProcess)===null||r===void 0?void 0:r.pid}`);yield this._instanceInfo.instance.stop();this.stateChange(E.stopped);if(n.doCleanup){yield this.cleanup(n)}return true}))}cleanup(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){assertionIsMMSState(E.stopped,this.state);let t={doCleanup:true,force:false};if(typeof e==="boolean"){t.force=e}if(typeof e==="object"){t=e}this.debug(`cleanup:`,t);if(!t.doCleanup){this.debug('cleanup: "doCleanup" is set to false');return}if((0,i.isNullOrUndefined)(this._instanceInfo)){this.debug('cleanup: "instanceInfo" is undefined');return}(0,i.assertion)((0,i.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess),new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));const r=this._instanceInfo.tmpDir;if(!(0,i.isNullOrUndefined)(r)){this.debug(`cleanup: removing tmpDir at ${r.name}`);r.removeCallback()}if(t.force){const e=this._instanceInfo.dbPath;const t=yield(0,i.statPath)(e);if((0,i.isNullOrUndefined)(t)){this.debug(`cleanup: force is true, but path "${e}" dosnt exist anymore`)}else{(0,i.assertion)(t.isDirectory(),new Error("Defined dbPath is not an directory"));if((0,h.lt)(process.version,"14.14.0")){yield l.promises.rmdir(e,{recursive:true,maxRetries:1})}else{yield l.promises.rm(e,{recursive:true,maxRetries:1})}}}this.stateChange(E.new);this._instanceInfo=undefined}))}get instanceInfo(){return this._instanceInfo}get state(){return this._state}ensureInstance(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("ensureInstance: Called .ensureInstance() method");switch(this._state){case E.running:if(this._instanceInfo){return this._instanceInfo}throw new d.EnsureInstanceError(true);case E.new:case E.stopped:break;case E.starting:return new Promise(((e,t)=>this.once(p.stateChange,(r=>{if(r!=E.running){t(new Error(`"ensureInstance" waited for "running" but got an different state: "${r}"`));return}(0,i.assertion)(!(0,i.isNullOrUndefined)(this._instanceInfo),new Error("InstanceInfo is undefined!"));e(this._instanceInfo)}))));default:throw new d.StateError([E.running,E.new,E.stopped,E.starting],this.state)}this.debug('ensureInstance: no running instance, calling "start()" command');yield this.start();this.debug('ensureInstance: "start()" command was succesfully resolved');if(!this._instanceInfo){throw new d.EnsureInstanceError(false)}return this._instanceInfo}))}getUri(e,t){this.debug("getUri:",this.state,e,t);switch(this.state){case E.running:case E.starting:break;case E.stopped:default:throw new d.StateError([E.running,E.starting],this.state)}assertionInstanceInfo(this._instanceInfo);return(0,i.uriTemplate)(t||"127.0.0.1",this._instanceInfo.port,(0,i.generateDbName)(e))}createAuth(e){var t,r,o;return(0,n.__awaiter)(this,void 0,void 0,(function*(){(0,i.assertion)(!(0,i.isNullOrUndefined)(this.auth),new Error('"createAuth" got called, but "this.auth" is undefined!'));this.debug("createAuth: options:",this.auth);const n=yield u.MongoClient.connect((0,i.uriTemplate)(e.ip,e.port,"admin"),{});try{let e=n.db("admin");this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);yield e.command({createUser:this.auth.customRootName,pwd:this.auth.customRootPwd,mechanisms:["SCRAM-SHA-256"],customData:{createdBy:"mongodb-memory-server",as:"ROOTUSER"},roles:["root"],writeConcern:{w:"majority"}});if(this.auth.extraUsers.length>0){this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);this.auth.extraUsers.sort(((e,t)=>{if(e.database==="admin"){return-1}return e.database===t.database?0:1}));for(const s of this.auth.extraUsers){s.database=(0,i.isNullOrUndefined)(s.database)?"admin":s.database;if(s.database!==e.databaseName){e=n.db(s.database)}this.debug("createAuth: Creating User: ",s);yield e.command({createUser:s.createUser,pwd:s.pwd,customData:Object.assign(Object.assign({},s.customData),{createdBy:"mongodb-memory-server",as:"EXTRAUSER"}),roles:s.roles,authenticationRestrictions:(t=s.authenticationRestrictions)!==null&&t!==void 0?t:[],mechanisms:(r=s.mechanisms)!==null&&r!==void 0?r:["SCRAM-SHA-256"],digestPassword:(o=s.digestPassword)!==null&&o!==void 0?o:true})}}}finally{yield n.close()}}))}}t.MongoMemoryServer=MongoMemoryServer;t["default"]=MongoMemoryServer;function assertionInstanceInfo(e){(0,i.assertion)(!(0,i.isNullOrUndefined)(e),new Error('"instanceInfo" is undefined'))}function assertionIsMMSState(e,t){(0,i.assertion)(t===e,new d.StateError([e],t))}},8919:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.DryMongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(8730);const i=r(1978);const a=(0,n.__importStar)(r(1017));const A=r(2037);const c=(0,n.__importDefault)(r(7281));const l=r(8278);const u=r(3386);const h=r(1);const d=(0,o.default)("MongoMS:DryMongoBinary");class DryMongoBinary{static locateBinary(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d(`locateBinary: Trying to locate Binary for version "${e.version}"`);const t=yield this.generateOptions(e);if(!!t.systemBinary){d(`locateBinary: env "SYSTEM_BINARY" was provided with value: "${t.systemBinary}"`);const e=yield this.getSystemPath(t.systemBinary);if((0,i.isNullOrUndefined)(e)){throw new u.NoSystemBinaryFoundError(t.systemBinary)}return e}if(this.binaryCache.has(e.version)){const t=this.binaryCache.get(e.version);d(`locateBinary: Requested Version found in cache: "[${e.version}, ${t}]"`);return t}d("locateBinary: running generateDownloadPath");const r=yield this.generateDownloadPath(t);if(!r[0]){d("locateBinary: could not find a existing binary");return undefined}d(`locateBinary: found binary at "${r[1]}"`);this.binaryCache.set(e.version,r[1]);return r[1]}))}static generateOptions(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generateOptions");const n=(t=(0,s.resolveConfig)(s.ResolveConfigVariables.VERSION))!==null&&t!==void 0?t:s.DEFAULT_VERSION;const o=(0,i.isNullOrUndefined)(e)?{version:n}:e;const c={version:o.version||n,downloadDir:(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR)||o.downloadDir||"",os:(r=o.os)!==null&&r!==void 0?r:yield(0,l.getOS)(),platform:o.platform||(0,A.platform)(),arch:o.arch||(0,A.arch)(),systemBinary:(0,s.resolveConfig)(s.ResolveConfigVariables.SYSTEM_BINARY)||o.systemBinary||""};c.downloadDir=a.dirname((yield this.generateDownloadPath(c))[1]);if((0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME)||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL)||(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);d(`generateOptions: ARCHIVE_NAME or DOWNLOAD_URL defined, generating options based on that (input: "${e}")`);return this.parseArchiveNameRegex(e,c)}return c}))}static parseArchiveNameRegex(e,t){d(`parseArchiveNameRegex (input: "${e}")`);const r=/mongodb-(?linux|win32|osx|macos)(?:-ssl-|-)(?\w{4,})(?:-(?\w+)|)(?:-ssl-|-)(?:v|)(?[\d.]+(?:-latest|))\./gim.exec(e);(0,i.assertion)(!(0,i.isNullOrUndefined)(r),new u.NoRegexMatchError("input"));(0,i.assertion)(!(0,i.isNullOrUndefined)(r.groups),new u.NoRegexMatchError("input","groups"));const n=r.groups;(0,i.assertion)(typeof n.version==="string"&&n.version.length>1,new u.ParseArchiveRegexError("version"));(0,i.assertion)(typeof n.platform==="string"&&n.platform.length>1,new u.ParseArchiveRegexError("platform"));(0,i.assertion)(typeof n.arch==="string"&&n.arch.length>=4,new u.ParseArchiveRegexError("arch"));t.version=n.version;t.arch=n.arch;if(n.platform==="linux"){const e=!!n.dist?/([a-z]+)(\d*)/gim.exec(n.dist):null;t.os={os:"linux",dist:typeof(e===null||e===void 0?void 0:e[1])==="string"?e[1]:"unknown",release:""}}else{t.os={os:n.platform}}return t}static getBinaryName(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getBinaryName");let t;if((0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.USE_ARCHIVE_NAME_FOR_BINARY_NAME))){const r=yield new h.MongoBinaryDownloadUrl(e).getArchiveName();t=a.parse(r).name}else{const r=e.platform==="win32"?".exe":"";const n=(0,l.isLinuxOS)(e.os)?e.os.dist:e.os.os;t=`mongod-${e.arch}-${n}-${e.version}${r}`}return t}))}static combineBinaryName(e,t){d("combineBinaryName");return a.resolve(e,t)}static getSystemPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("getSystempath");try{yield(0,i.checkBinaryPermissions)(e);d(`getSystemPath: found system binary path at "${e}"`);return e}catch(t){d(`getSystemPath: can't find system binary at "${e}".\n${t instanceof Error?t.message:t}`)}return undefined}))}static generatePaths(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("generatePaths",e);const t={legacyHomeCache:"",modulesCache:"",relative:"",resolveConfig:""};const r=yield this.getBinaryName(e);let n=process.env["INIT_CWD"]||process.cwd();while(n.includes(`node_modules${a.sep}mongodb-memory-server`)){n=a.resolve(n,"..","..")}const o=(0,c.default)({name:"mongodb-memory-server",cwd:n});if(!(0,i.isNullOrUndefined)(o)){t.modulesCache=this.combineBinaryName(a.resolve(o),r)}const A=a.resolve(this.homedir(),".cache/mongodb-binaries");t.legacyHomeCache=this.combineBinaryName(A,r);const l=e.downloadDir||(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_DIR);if(!(0,i.isNullOrUndefined)(l)&&l.length>0){d(`generatePaths: resolveConfigValue is not empty`);t.resolveConfig=this.combineBinaryName(l,r)}t.relative=this.combineBinaryName(a.resolve(process.cwd(),"mongodb-binaries"),r);return t}))}static generateDownloadPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.envToBool)((0,s.resolveConfig)(s.ResolveConfigVariables.PREFER_GLOBAL_PATH));d(`generateDownloadPath: Generating Download Path, preferGlobal: "${t}"`);const r=yield this.generatePaths(e);d("generateDownloadPath: Paths:",r,e.systemBinary);if(!!e.systemBinary&&(yield(0,i.pathExists)(e.systemBinary))){const t=yield this.getSystemPath(e.systemBinary);if(!(0,i.isNullOrUndefined)(t)){return[true,t]}}if(yield(0,i.pathExists)(r.resolveConfig)){d(`generateDownloadPath: Found binary in resolveConfig (DOWNLOAD_DIR): "${r.resolveConfig}"`);return[true,r.resolveConfig]}if(yield(0,i.pathExists)(r.legacyHomeCache)){d(`generateDownloadPath: Found binary in legacyHomeCache: "${r.legacyHomeCache}"`);return[true,r.legacyHomeCache]}if(yield(0,i.pathExists)(r.modulesCache)){d(`generateDownloadPath: Found binary in modulesCache: "${r.modulesCache}"`);return[true,r.modulesCache]}if(yield(0,i.pathExists)(r.relative)){d(`generateDownloadPath: Found binary in relative: "${r.relative}"`);return[true,r.relative]}d(`generateDownloadPath: no existing binary for version "${e.version}" was found`);if(r.resolveConfig.length>0){d(`generateDownloadPath: using resolveConfig (DOWNLOAD_DIR) "${r.resolveConfig}"`);return[false,r.resolveConfig]}if(t&&!!r.legacyHomeCache){d(`generateDownloadPath: using global (preferGlobal) "${r.legacyHomeCache}"`);return[false,r.legacyHomeCache]}if(r.modulesCache.length>0){d(`generateDownloadPath: using modulesCache "${r.modulesCache}"`);return[false,r.modulesCache]}d(`generateDownloadPath: using relative "${r.relative}"`);return[false,r.relative]}))}static homedir(){return(0,A.homedir)()}}t.DryMongoBinary=DryMongoBinary;DryMongoBinary.binaryCache=new Map},9125:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinary=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=(0,n.__importDefault)(r(1017));const i=(0,n.__importDefault)(r(229));const a=(0,n.__importStar)(r(8730));const A=(0,n.__importDefault)(r(8237));const c=(0,n.__importStar)(r(1383));const l=r(1978);const u=r(2081);const h=r(4908);const d=r(8919);const g=(0,A.default)("MongoMS:MongoBinary");class MongoBinary{static download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("download");const{downloadDir:t,version:r}=e;yield(0,l.mkdir)(t);const n=s.default.resolve(t,`${r}.lock`);g(`download: Waiting to acquire Download lock for file "${n}"`);const o=yield h.LockFile.lock(n);g("download: Download lock acquired");try{if(!d.DryMongoBinary.binaryCache.has(r)){g(`download: Adding version ${r} to cache`);const t=new i.default(e);d.DryMongoBinary.binaryCache.set(r,yield t.getMongodPath())}}finally{g("download: Removing Download lock");yield o.unlock();g("download: Download lock removed")}const a=d.DryMongoBinary.binaryCache.get(r);(0,l.assertion)(typeof a==="string",new Error(`No Cache Path for version "${r}" found (and download failed silently?)`));return a}))}static getPath(e={}){return(0,n.__awaiter)(this,void 0,void 0,(function*(){g("getPath");const t=Object.assign(Object.assign({},yield d.DryMongoBinary.generateOptions(e)),{platform:e.platform||(0,a.default)(a.ResolveConfigVariables.PLATFORM)||o.default.platform(),checkMD5:e.checkMD5||(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.MD5_CHECK))});g(`getPath: MongoBinary options:`,JSON.stringify(t,null,2));let r=yield d.DryMongoBinary.locateBinary(t);if(!!t.systemBinary){if(!(0,l.isNullOrUndefined)(r)){g(`getPath: Spawning binaryPath "${r}" to get version`);const e=(0,u.spawnSync)(r,["--version"]).stdout.toString().match(/^\s*db\s+version\s+v?(\d+\.\d+\.\d+)(-\d*)?(-[a-zA-Z0-9].*)?\s*$/im);(0,l.assertion)(!(0,l.isNullOrUndefined)(e),new Error("Couldnt find an version from system binary output!"));if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.SYSTEM_BINARY_VERSION_CHECK))){g("getPath: Checking & Warning about version conflicts");const r=e[1];if(c.neq(t.version,r)){console.warn("getPath: MongoMemoryServer: Possible version conflict\n"+` SystemBinary version: "${r}"\n`+` Requested version: "${t.version}"\n\n`+" Using SystemBinary!")}}}else{throw new Error('Option "SYSTEM_BINARY" was set, but binaryPath was empty! (system binary could not be found?) [This Error should normally not be thrown, please report this]')}}(0,l.assertion)(typeof t.version==="string",new Error('"MongoBinary.options.version" is not an string!'));if(!r){if((0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD))){g('getPath: "RUNTIME_DOWNLOAD" is "true", trying to download');r=yield this.download(t)}else{g('getPath: "RUNTIME_DOWNLOAD" is "false", not downloading')}}if(!r){const e=(0,a.envToBool)((0,a.default)(a.ResolveConfigVariables.RUNTIME_DOWNLOAD));throw new Error(`MongoBinary.getPath: could not find an valid binary path! (Got: "${r}", RUNTIME_DOWNLOAD: "${e}")`)}g(`getPath: Mongod binary path: "${r}"`);return r}))}}t.MongoBinary=MongoBinary;t["default"]=MongoBinary},229:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownload=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(2037));const s=r(7310);const i=(0,n.__importDefault)(r(1017));const a=r(7147);const A=(0,n.__importDefault)(r(1446));const c=(0,n.__importDefault)(r(5687));const l=r(9796);const u=(0,n.__importDefault)(r(2283));const h=(0,n.__importDefault)(r(8781));const d=(0,n.__importDefault)(r(1));const g=r(7219);const p=(0,n.__importStar)(r(8730));const E=(0,n.__importDefault)(r(8237));const m=r(1978);const C=r(8919);const I=r(4521);const y=r(3386);const B=(0,E.default)("MongoMS:MongoBinaryDownload");class MongoBinaryDownload{constructor(e){var t,r,n,s,i,a;(0,m.assertion)(typeof e.downloadDir==="string",new Error("An DownloadDir must be specified!"));const A=(t=e.version)!==null&&t!==void 0?t:(0,p.default)(p.ResolveConfigVariables.VERSION);(0,m.assertion)(typeof A==="string",new Error("An MongoDB Binary version must be specified!"));this.binaryOpts={platform:(r=e.platform)!==null&&r!==void 0?r:o.default.platform(),arch:(n=e.arch)!==null&&n!==void 0?n:o.default.arch(),version:A,downloadDir:e.downloadDir,checkMD5:(s=e.checkMD5)!==null&&s!==void 0?s:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.MD5_CHECK)),systemBinary:(i=e.systemBinary)!==null&&i!==void 0?i:"",os:(a=e.os)!==null&&a!==void 0?a:{os:"unknown"}};this.dlProgress={current:0,length:0,totalMb:0,lastPrintedAt:0}}get checkMD5(){return this.binaryOpts.checkMD5}set checkMD5(e){this.binaryOpts.checkMD5=e}get downloadDir(){return this.binaryOpts.downloadDir}set downloadDir(e){this.binaryOpts.downloadDir=e}get arch(){return this.binaryOpts.arch}set arch(e){this.binaryOpts.arch=e}get version(){return this.binaryOpts.version}set version(e){this.binaryOpts.version=e}get platform(){return this.binaryOpts.platform}set platform(e){this.binaryOpts.platform=e}getPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield C.DryMongoBinary.generateOptions(this.binaryOpts);return C.DryMongoBinary.combineBinaryName(this.downloadDir,yield C.DryMongoBinary.getBinaryName(e))}))}getMongodPath(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("getMongodPath");const e=yield this.getPath();if(yield(0,m.pathExists)(e)){B(`getMongodPath: mongod path "${e}" already exists, using this`);return e}const t=yield this.startDownload();yield this.extract(t);yield a.promises.unlink(t);if(yield(0,m.pathExists)(e)){return e}throw new Error(`Cannot find downloaded mongod binary by path "${e}"`)}))}startDownload(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("startDownload");const e=new d.default(this.binaryOpts);yield(0,m.mkdir)(this.downloadDir);try{yield a.promises.access(this.downloadDir,a.constants.X_OK|a.constants.W_OK)}catch(e){console.error(`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n`+"Needed Permissions: Write & Execute (-wx)\n");throw e}const t=yield e.getDownloadUrl();const r=yield this.download(t);yield this.makeMD5check(`${t}.md5`,r);return r}))}makeMD5check(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("makeMD5check: Checking MD5 of downloaded binary...");if(!this.checkMD5){B("makeMD5check: checkMD5 is disabled");return undefined}const r=yield this.download(e);const n=(yield a.promises.readFile(r)).toString("utf-8");const o=n.match(/^\s*([\w\d]+)\s*/i);const s=o?o[1]:null;const i=A.default.sync(t);B(`makeMD5check: Local MD5: ${i}, Remote MD5: ${s}`);if(s!==i){throw new y.Md5CheckFailedError(i,s||"unknown")}yield a.promises.unlink(r);return true}))}download(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("download");const t=process.env["yarn_https-proxy"]||process.env.yarn_proxy||process.env["npm_config_https-proxy"]||process.env.npm_config_proxy||process.env.https_proxy||process.env.http_proxy||process.env.HTTPS_PROXY||process.env.HTTP_PROXY;const r=process.env.npm_config_strict_ssl==="true";const n=new s.URL(e);n.port=n.port||"443";const o={method:"GET",rejectUnauthorized:r,protocol:(0,p.envToBool)((0,p.default)(p.ResolveConfigVariables.USE_HTTP))?"http:":"https:",agent:t?new g.HttpsProxyAgent(t):undefined};const a=n.pathname.split("/").pop();if(!a){throw new Error(`MongoBinaryDownload: missing filename for url "${e}"`)}const A=i.default.resolve(this.downloadDir,a);const c=i.default.resolve(this.downloadDir,`${a}.downloading`);B(`download: Downloading${t?` via proxy "${t}"`:""}: "${e}"`);if(yield(0,m.pathExists)(A)){B("download: Already downloaded archive found, skipping download");return A}this.assignDownloadingURL(n);const l=yield this.httpDownload(n,o,A,c);return l}))}extract(e){var t,r;return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extract");const n=yield this.getPath();B(`extract: archive: "${e}" final: "${n}"`);yield(0,m.mkdir)(i.default.dirname(n));const filter=e=>/(?:bin\/(?:mongod(?:\.exe)?)|(?:.*\.dll))$/i.test(e);if(/(.tar.gz|.tgz)$/.test(e)){yield this.extractTarGz(e,n,filter)}else if(/.zip$/.test(e)){yield this.extractZip(e,n,filter)}else{throw new Error(`MongoBinaryDownload: unsupported archive "${e}" (downloaded from "${(t=this._downloadingUrl)!==null&&t!==void 0?t:"unknown"}"). Broken archive from MongoDB Provider?`)}if(!(yield(0,m.pathExists)(n))){throw new Error(`MongoBinaryDownload: missing mongod binary in "${e}" (downloaded from "${(r=this._downloadingUrl)!==null&&r!==void 0?r:"unknown"}"). Broken archive from MongoDB Provider?`)}return n}))}extractTarGz(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractTarGz");const n=u.default.extract();n.on("entry",((e,n,o)=>{if(r(e.name)){n.pipe((0,a.createWriteStream)(t,{mode:509}))}n.on("end",(()=>o()));n.resume()}));return new Promise(((t,r)=>{(0,a.createReadStream)(e).on("error",(t=>{r("Unable to open tarball "+e+": "+t)})).pipe((0,l.createUnzip)()).on("error",(t=>{r("Error during unzip for "+e+": "+t)})).pipe(n).on("error",(t=>{r("Error during untar for "+e+": "+t)})).on("finish",(e=>{t(e)}))}))}))}extractZip(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("extractZip");return new Promise(((n,o)=>{h.default.open(e,{lazyEntries:true},((e,s)=>{if(e||!s){return o(e)}s.readEntry();s.on("end",(()=>n()));s.on("entry",(e=>{if(!r(e.fileName)){return s.readEntry()}s.openReadStream(e,((e,r)=>{if(e||!r){return o(e)}r.on("end",(()=>s.readEntry()));r.pipe((0,a.createWriteStream)(t,{mode:509}))}))}))}))}))}))}httpDownload(e,t,r,o){return(0,n.__awaiter)(this,void 0,void 0,(function*(){B("httpDownload");const s=this.assignDownloadingURL(e);return new Promise(((i,A)=>{B(`httpDownload: trying to download "${s}"`);c.default.get(e,t,(e=>{if(e.statusCode!=200){if(e.statusCode===403){A(new Error("Status Code is 403 (MongoDB's 404)\n"+"This means that the requested version-platform combination doesn't exist\n"+` Used Url: "${s}"\n`+"Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n"+"List of available versions can be found here:\n"+" https://www.mongodb.org/dl/linux for Linux\n"+" https://www.mongodb.org/dl/osx for OSX\n"+" https://www.mongodb.org/dl/win32 for Windows"));return}A(new Error("Status Code isnt 200!"));return}if(typeof e.headers["content-length"]!="string"){A(new Error('Response header "content-length" is empty!'));return}this.dlProgress.current=0;this.dlProgress.length=parseInt(e.headers["content-length"],10);this.dlProgress.totalMb=Math.round(this.dlProgress.length/1048576*10)/10;const c=(0,a.createWriteStream)(o);e.pipe(c);c.on("finish",(()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){var e;if(this.dlProgress.current{this.printDownloadProgress(e)}))})).on("error",(e=>{console.error(`Couldnt download "${s}"!`,e.message);A(e)}))}))}))}printDownloadProgress(e,t=false){this.dlProgress.current+=e.length;const r=Date.now();if(r-this.dlProgress.lastPrintedAt<2e3&&!t){return}this.dlProgress.lastPrintedAt=r;const n=Math.round(100*this.dlProgress.current/this.dlProgress.length*10)/10;const o=Math.round(this.dlProgress.current/1048576*10)/10;const s=this.platform==="win32"?"":"\r";const i=`Downloading MongoDB "${this.version}": ${n}% (${o}mb / ${this.dlProgress.totalMb}mb)${s}`;if(process.stdout.isTTY){(0,I.clearLine)(process.stdout,0);process.stdout.write(i)}else{console.log(i)}}assignDownloadingURL(e){this._downloadingUrl=e.href;return this._downloadingUrl}}t.MongoBinaryDownload=MongoBinaryDownload;t["default"]=MongoBinaryDownload},1:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoBinaryDownloadUrl=void 0;const n=r(4351);const o=r(8278);const s=r(8730);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1383));const A=r(1978);const c=r(7310);const l=r(3386);const u=r(3837);const h=(0,i.default)("MongoMS:MongoBinaryDownloadUrl");class MongoBinaryDownloadUrl{constructor(e){this.version=e.version;this.platform=this.translatePlatform(e.platform);this.arch=MongoBinaryDownloadUrl.translateArch(e.arch,this.platform);this.os=e.os}getDownloadUrl(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_URL);if(t){h(`Using "${t}" as the Download-URL`);const e=new c.URL(t);return e.toString()}const r=yield this.getArchiveName();h(`Using "${r}" as the Archive String`);const n=(e=(0,s.resolveConfig)(s.ResolveConfigVariables.DOWNLOAD_MIRROR))!==null&&e!==void 0?e:"https://fastdl.mongodb.org";h(`Using "${n}" as the mirror`);const o=new c.URL(n);if(!o.pathname.endsWith("/")){o.pathname=o.pathname+"/"}o.pathname=`${o.pathname}${this.platform}/${r}`;return o.toString()}))}getArchiveName(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=(0,s.resolveConfig)(s.ResolveConfigVariables.ARCHIVE_NAME);if(!!e){return e}switch(this.platform){case"osx":return this.getArchiveNameOsx();case"win32":case"windows":return this.getArchiveNameWin();case"linux":return this.getArchiveNameLinux();default:throw new l.UnknownPlatformError(this.platform)}}))}getArchiveNameWin(){let e=`mongodb-${this.platform}-${this.arch}`;if(!(0,A.isNullOrUndefined)(a.coerce(this.version))){if(a.satisfies(this.version,"4.2.x")){e+="-2012plus"}else if(a.lt(this.version,"4.1.0")){e+="-2008plus-ssl"}}e+=`-${this.version}.zip`;return e}getArchiveNameOsx(){let e=`mongodb-osx`;const t=a.coerce(this.version);if(!(0,A.isNullOrUndefined)(t)&&a.gte(t,"3.2.0")){e+="-ssl"}if((0,A.isNullOrUndefined)(t)||a.gte(t,"4.2.0")){e=`mongodb-macos`}if(this.arch==="arm64"){h('getArchiveNameOsx: Arch is "arm64", using x64 binary');this.arch="x86_64"}e+=`-${this.arch}-${this.version}.tgz`;return e}getArchiveNameLinux(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){let e;if(this.arch!=="i686"){if(!this.os){this.os=yield(0,o.getOS)()}e=this.getLinuxOSVersionString(this.os)}let t=`mongodb-linux-${this.arch}`;if(!!e){t+=`-${e}`}t+=`-${this.version}.tgz`;return t}))}getLinuxOSVersionString(e){var t;if(regexHelper(/ubuntu/i,e)){return this.getUbuntuVersionString(e)}else if(regexHelper(/amzn/i,e)){return this.getAmazonVersionString(e)}else if(regexHelper(/suse/i,e)){return this.getSuseVersionString(e)}else if(regexHelper(/(rhel|centos|scientific)/i,e)){return this.getRhelVersionString(e)}else if(regexHelper(/fedora/i,e)){return this.getFedoraVersionString(e)}else if(regexHelper(/debian/i,e)){return this.getDebianVersionString(e)}else if(regexHelper(/alpine/i,e)){console.warn("There is no offical build of MongoDB for Alpine!")}else if(regexHelper(/(arch|manjaro|arco)(?:linux)?$/i,e)){console.warn(`There is no official build of MongoDB for ArchLinux (${e.dist}). Falling back to Ubuntu 20.04 release.`);return this.getUbuntuVersionString({os:"linux",dist:"Ubuntu Linux",release:"20.04"})}else if(regexHelper(/gentoo/i,e)){console.warn(`There is no official build of MongoDB for Gentoo (${e.dist}). Falling back to Debian.`);return this.getDebianVersionString({os:"linux",dist:"Debian",release:"11"})}else if(regexHelper(/unknown/i,e)){console.warn("Couldnt parse dist information, please report this to https://github.com/nodkz/mongodb-memory-server/issues")}console.warn(`Unknown/unsupported linux "${e.dist}(${(t=e.id_like)===null||t===void 0?void 0:t.join(", ")})". Falling back to legacy MongoDB build!`);return this.getLegacyVersionString()}getDebianVersionString(e){let t="debian";const r=parseFloat(e.release);if(r>=11||["unstable","testing"].includes(e.release)){if(a.lt(this.version,"5.0.8")){h("debian11 detected, but version below 5.0.8 requested, using debian10");t+="10"}else{t+="11"}}else if(r>=10){t+="10"}else if(r>=9){t+="92"}else if(r>=8.1){t+="81"}else if(r>=7.1){t+="71"}if(r>=10){if(a.lt(this.version,"4.2.1")){throw new l.KnownVersionIncompatibilityError(`Debian ${r}`,this.version,">=4.2.1","Mongodb does not provide binaries for versions before 4.2.1 for Debian 10+ and also cannot be mapped to a previous Debian release")}}return t}getFedoraVersionString(e){let t="rhel";const r=parseInt(e.release,10);if(r>=34){t+="80"}if(r<34&&r>=19){t+="70"}if(r<19&&r>=12){t+="62"}if(r<12&&r>=6){t+="55"}return t}getRhelVersionString(e){let t="rhel";const{release:r}=e;if(r){if(/^8/.test(r)){t+="80"}else if(/^7/.test(r)){t+="70"}else if(/^6/.test(r)){t+="62"}else if(/^5/.test(r)){t+="55"}}if(t==="rhel"){h('getRhelVersionString: falling back to "70"');t+="70"}return t}getAmazonVersionString(e){let t="amazon";const r=parseInt(e.release,10);if(r>=2&&r<=3){t+="2"}return t}getLegacyVersionString(){return""}getSuseVersionString(e){const t=e.release.match(/(^11|^12|^15)/);return t?`suse${t[0]}`:""}getUbuntuVersionString(e){let t=undefined;{if(/^linux\s?mint\s*$/i.test(e.dist)){const r={17:"14.04",18:"16.04",19:"18.04",20:"20.04"};t={os:"linux",dist:"ubuntu",release:r[parseInt(e.release.split(".")[0])]||r[20]}}if(/^elementary\s?os\s*$/i.test(e.dist)){const r={3:"14.04",4:"16.04",5:"18.04",6:"20.04"};const[n,o]=e.release.split(".").map((e=>parseInt(e)));const s=n||o;t={os:"linux",dist:"ubuntu",release:r[s]||r[6]}}}if((0,A.isNullOrUndefined)(t)){if(!/^ubuntu(?:| linux)\s*$/i.test(e.dist)){console.warn(`Unmapped distro "${e.dist}" with ID_LIKE "ubuntu", defaulting to highest ubuntu version!\n`+'This means that your distro does not have a internal mapping in MMS or does not have a upstream release file (like "/etc/upstream-release/lsb-release"), but has set a ID_LIKE');t={os:"linux",dist:"ubuntu",release:"20.04"}}else{t=e}}const r=parseInt(t.release.split(".")[0],10);if(this.arch==="arm64"){if(a.satisfies(this.version,"<4.1.10")){this.arch="arm64";return"ubuntu1604"}if(a.satisfies(this.version,">=4.1.10")){this.arch="aarch64";if(a.satisfies(this.version,"<4.4.0")){return"ubuntu1804"}return`ubuntu${r||18}04`}}if(t.release==="14.10"){return"ubuntu1410-clang"}if(r>=18&&a.satisfies(this.version,"3.x.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an 3.x.x version, defaulting to "1604"`);return"ubuntu1604"}if(r>18&&a.satisfies(this.version,"<=4.3.x")){h(`getUbuntuVersionString: ubuntuYear is "${r}", which dosnt have an "<=4.3.x" version, defaulting to "1804"`);return"ubuntu1804"}if(r>=21){return"ubuntu2004"}return`ubuntu${r||14}04`}translatePlatform(e){switch(e){case"darwin":return"osx";case"win32":const t=a.coerce(this.version);if((0,A.isNullOrUndefined)(t)){return"windows"}return a.gte(t,"4.3.0")?"windows":"win32";case"linux":case"elementary OS":return"linux";case"sunos":return"sunos5";default:throw new l.UnknownPlatformError(e)}}static translateArch(e,t){switch(e){case"ia32":(0,u.deprecate)((()=>{}),"mongodb-memory-server will fully drop support for ia32 in 9.0","MMS001")();if(t==="linux"){return"i686"}else if(t==="win32"){return"i386"}throw new l.UnknownArchitectureError(e,t);case"x86_64":case"x64":return"x86_64";case"arm64":return"arm64";case"aarch64":return"aarch64";default:throw new l.UnknownArchitectureError(e)}}}t.MongoBinaryDownloadUrl=MongoBinaryDownloadUrl;t["default"]=MongoBinaryDownloadUrl;function regexHelper(e,t){return e.test(t.dist)||(!(0,A.isNullOrUndefined)(t.id_like)?t.id_like.filter((t=>e.test(t))).length>=1:false)}},843:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.MongoInstance=t.MongoInstanceEvents=void 0;const n=r(4351);const o=r(2081);const s=(0,n.__importStar)(r(1017));const i=r(9125);const a=(0,n.__importDefault)(r(8237));const A=r(1978);const c=r(1383);const l=r(2361);const u=r(5517);const h=r(3386);if((0,c.lt)(process.version,"12.22.0")){console.warn("Using NodeJS below 12.22.0")}const d=(0,a.default)("MongoMS:MongoInstance");var g;(function(e){e["instanceReplState"]="instanceReplState";e["instancePrimary"]="instancePrimary";e["instanceReady"]="instanceReady";e["instanceSTDOUT"]="instanceSTDOUT";e["instanceSTDERR"]="instanceSTDERR";e["instanceClosed"]="instanceClosed";e["instanceRawError"]="instanceRawError";e["instanceError"]="instanceError";e["killerLaunched"]="killerLaunched";e["instanceLaunched"]="instanceLaunched";e["instanceStarted"]="instanceStarted"})(g=t.MongoInstanceEvents||(t.MongoInstanceEvents={}));class MongoInstance extends l.EventEmitter{constructor(e){super();this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;this.instanceOpts=Object.assign({},e.instance);this.binaryOpts=Object.assign({},e.binary);this.spawnOpts=Object.assign({},e.spawn);this.on(g.instanceReady,(()=>{this.isInstanceReady=true;this.debug("constructor: Instance is ready!")}));this.on(g.instanceError,(e=>(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug(`constructor: Instance has thrown an Error: ${e.toString()}`);this.isInstanceReady=false;this.isInstancePrimary=false;yield this.stop()}))))}debug(e,...t){var r;const n=(r=this.instanceOpts.port)!==null&&r!==void 0?r:"unknown";d(`Mongo[${n}]: ${e}`,...t)}static create(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){d("create: Called .create() method");const t=new this(e);yield t.start();return t}))}prepareCommandArgs(){var e;this.debug("prepareCommandArgs");(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.port),new Error('"instanceOpts.port" is required to be set!'));(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.dbPath),new Error('"instanceOpts.dbPath" is required to be set!'));const t=[];t.push("--port",this.instanceOpts.port.toString());t.push("--dbpath",this.instanceOpts.dbPath);if(!!this.instanceOpts.replSet){this.isReplSet=true;t.push("--replSet",this.instanceOpts.replSet)}if(!!this.instanceOpts.storageEngine){t.push("--storageEngine",this.instanceOpts.storageEngine)}if(!!this.instanceOpts.ip){t.push("--bind_ip",this.instanceOpts.ip)}if(this.instanceOpts.auth){t.push("--auth");if(this.isReplSet){(0,A.assertion)(!(0,A.isNullOrUndefined)(this.instanceOpts.keyfileLocation),new h.KeyFileMissingError);t.push("--keyFile",this.instanceOpts.keyfileLocation)}}else{t.push("--noauth")}const r=t.concat((e=this.instanceOpts.args)!==null&&e!==void 0?e:[]);this.debug("prepareCommandArgs: final argument array:"+JSON.stringify(r));return r}start(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("start");this.isInstancePrimary=false;this.isInstanceReady=false;this.isReplSet=false;const e=new Promise(((e,t)=>{this.once(g.instanceReady,e);this.once(g.instanceError,t);this.once(g.instanceClosed,(()=>{t(new Error("Instance Exited before being ready and without throwing an error!"))}))}));const t=yield i.MongoBinary.getPath(this.binaryOpts);yield(0,A.checkBinaryPermissions)(t);this.debug("start: Starting Processes");this.mongodProcess=this._launchMongod(t);(0,A.assertion)(!(0,A.isNullOrUndefined)(this.mongodProcess.pid),new Error("MongoD Process failed to spawn"));this.killerProcess=this._launchKiller(process.pid,this.mongodProcess.pid);yield e;this.emit(g.instanceStarted);this.debug("start: Processes Started")}))}stop(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){this.debug("stop");if(!this.mongodProcess&&!this.killerProcess){this.debug("stop: nothing to shutdown, returning");return false}if(!(0,A.isNullOrUndefined)(this.mongodProcess)){if(this.isReplSet){let e;try{this.debug("stop: trying shutdownServer");const t=this.instanceOpts.port;const r=this.instanceOpts.ip;(0,A.assertion)(!(0,A.isNullOrUndefined)(t),new Error('Cannot shutdown replset gracefully, no "port" is provided'));(0,A.assertion)(!(0,A.isNullOrUndefined)(r),new Error('Cannot shutdown replset gracefully, no "ip" is provided'));e=yield u.MongoClient.connect((0,A.uriTemplate)(r,t,"admin"),Object.assign(Object.assign({},this.extraConnectionOptions),{directConnection:true}));const n=e.db("admin");yield n.command({shutdown:1,force:true,timeoutSecs:1});this.debug("stop: after admin shutdown command")}catch(e){if(!(e instanceof u.MongoNetworkError&&/^connection \d+ to [\d.]+:\d+ closed$/i.test(e.message))){console.warn(e)}}finally{if(!(0,A.isNullOrUndefined)(e)){yield e.close()}}}yield(0,A.killProcess)(this.mongodProcess,"mongodProcess",this.instanceOpts.port);this.mongodProcess=undefined}else{this.debug("stop: mongodProcess: nothing to shutdown, skipping")}if(!(0,A.isNullOrUndefined)(this.killerProcess)){yield(0,A.killProcess)(this.killerProcess,"killerProcess",this.instanceOpts.port);this.killerProcess=undefined}else{this.debug("stop: killerProcess: nothing to shutdown, skipping")}this.debug("stop: Instance Finished Shutdown");return true}))}_launchMongod(e){var t,r;this.debug("_launchMongod: Launching Mongod Process");const n=(0,o.spawn)(s.resolve(e),this.prepareCommandArgs(),Object.assign(Object.assign({},this.spawnOpts),{stdio:"pipe"}));(t=n.stderr)===null||t===void 0?void 0:t.on("data",this.stderrHandler.bind(this));(r=n.stdout)===null||r===void 0?void 0:r.on("data",this.stdoutHandler.bind(this));n.on("close",this.closeHandler.bind(this));n.on("error",this.errorHandler.bind(this));if((0,A.isNullOrUndefined)(n.pid)){throw new h.StartBinaryFailedError(s.resolve(e))}this.emit(g.instanceLaunched);return n}_launchKiller(e,t){this.debug(`_launchKiller: Launching Killer Process (parent: ${e}, child: ${t})`);const r=(0,o.fork)(s.resolve(__dirname,"../../scripts/mongo_killer.js"),[e.toString(),t.toString()],{detached:true,stdio:"ignore"});r.unref();this.emit(g.killerLaunched);return r}errorHandler(e){this.emit(g.instanceRawError,e);this.emit(g.instanceError,e)}closeHandler(e,t){if(process.platform==="win32"&&e!=12&&e!=0||e!=0){this.debug("closeHandler: Mongod instance closed with an non-0 (or non 12 on windows) code!")}this.debug(`closeHandler: "${e}" "${t}"`);this.emit(g.instanceClosed,e,t)}stderrHandler(e){const t=e.toString().trim();this.debug(`stderrHandler: ""${t}""`);this.emit(g.instanceSTDERR,t);this.checkErrorInLine(t)}stdoutHandler(e){var t,r;const n=e.toString().trim();this.debug(`stdoutHandler: ""${n}""`);this.emit(g.instanceSTDOUT,n);if(/waiting for connections/i.test(n)){this.emit(g.instanceReady)}this.checkErrorInLine(n);if(/transition to \w+ from \w+/i.test(n)){const e=(r=(t=/transition to (\w+) from \w+/i.exec(n))===null||t===void 0?void 0:t[1])!==null&&r!==void 0?r:"UNKNOWN";this.emit(g.instanceReplState,e);if(e!=="PRIMARY"){this.isInstancePrimary=false}}if(/transition to primary complete; database writes are now permitted/i.test(n)){this.isInstancePrimary=true;this.debug('stdoutHandler: emitting "instancePrimary"');this.emit(g.instancePrimary)}}checkErrorInLine(e){var t,r;if(/address already in use/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError(`Port "${this.instanceOpts.port}" already in use`))}if(/exception in initAndListen: \w+[^:]: .+[^,], terminating/i.test(e)){const t=/exception in initAndListen: (\w+[^:]): (.+[^,]), terminating/i.exec(e);const{1:r,2:n}=t||[];this.emit(g.instanceError,new h.StdoutInstanceError(`Instance Failed to start with "${r}". Original Error:\n`+n))}if(/CURL_OPENSSL_3['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl3 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You should manually install libcurl3 or try to use an newer version of MongoDB"))}if(/CURL_OPENSSL_4['\s]+not found/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("libcurl4 is not available on your system. Mongod requires it and cannot be started without it.\n"+"You need to manually install libcurl4"))}if(/lib[^:]+(?=: cannot open shared object)/i.test(e)){const n=(r=(t=e.match(/(lib[^:]+)(?=: cannot open shared object)/i))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown";this.emit(g.instanceError,new h.StdoutInstanceError(`Instance failed to start because a library is missing or cannot be opened: "${n}"`))}if(/\*\*\*aborting after/i.test(e)){this.emit(g.instanceError,new h.StdoutInstanceError("Mongod internal error"))}}}t.MongoInstance=MongoInstance;t["default"]=MongoInstance},3386:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.StdoutInstanceError=t.KnownVersionIncompatibilityError=t.NoRegexMatchError=t.ParseArchiveRegexError=t.ReplsetCountLowError=t.AssertionFallbackError=t.BinaryNotFoundError=t.InsufficientPermissionsError=t.AuthNotObjectError=t.KeyFileMissingError=t.InstanceInfoError=t.StartBinaryFailedError=t.Md5CheckFailedError=t.NoSystemBinaryFoundError=t.EnsureInstanceError=t.WaitForPrimaryTimeoutError=t.UnknownArchitectureError=t.UnknownPlatformError=t.UnableToUnlockLockfileError=t.UnknownLockfileStatusError=t.StateError=void 0;const n=r(1978);class StateError extends Error{constructor(e,t){super(`Incorrect State for operation: "${t}", allowed States: "[${e.join(",")}]"\n`+"This may be because of using a v6.x way of calling functions, look at the following guide if anything applies:\n"+"https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7#no-function-other-than-start-create-ensureinstance-will-be-starting-anything");this.wantedStates=e;this.gotState=t}}t.StateError=StateError;class UnknownLockfileStatusError extends Error{constructor(e){super(`Unknown LockFile Status: "${e}"`);this.status=e}}t.UnknownLockfileStatusError=UnknownLockfileStatusError;class UnableToUnlockLockfileError extends Error{constructor(e,t){super(`Cannot unlock file "${t}", because it is not locked by this ${e?"instance":"process"}`);this.thisInstance=e;this.file=t}}t.UnableToUnlockLockfileError=UnableToUnlockLockfileError;class UnknownPlatformError extends Error{constructor(e){super(`Unknown Platform: "${e}"`);this.platform=e}}t.UnknownPlatformError=UnknownPlatformError;class UnknownArchitectureError extends Error{constructor(e,t){super();this.arch=e;this.platform=t;if(!(0,n.isNullOrUndefined)(t)){this.message=`Unsupported Architecture-Platform combination: arch: "${e}", platform: "${t}"`}else{this.message=`Unsupported Architecture: "${e}"`}}}t.UnknownArchitectureError=UnknownArchitectureError;class WaitForPrimaryTimeoutError extends Error{constructor(e,t){super(`Timed out after ${e}ms while waiting for a Primary (where: "${t}")`);this.timeout=e;this.where=t}}t.WaitForPrimaryTimeoutError=WaitForPrimaryTimeoutError;class EnsureInstanceError extends Error{constructor(e){super();this.isRunning=e;const t='"ensureInstance" failed, because';if(e){this.message=`${t} state was "running" but "instanceInfo" was undefined!`}else{this.message=`${t} "instanceInfo" was undefined after running "start"`}}}t.EnsureInstanceError=EnsureInstanceError;class NoSystemBinaryFoundError extends Error{constructor(e){super(`Config option "SYSTEM_BINARY" was provided with value "${e}", but no binary could be found!`);this.binaryPath=e}}t.NoSystemBinaryFoundError=NoSystemBinaryFoundError;class Md5CheckFailedError extends Error{constructor(e,t){super(`MD5 check failed! Binary MD5 is "${e}", Checkfile MD5 is "${t}"`);this.binarymd5=e;this.checkfilemd5=t}}t.Md5CheckFailedError=Md5CheckFailedError;class StartBinaryFailedError extends Error{constructor(e){super(`Starting the Binary Failed (PID is undefined)! Binary: "${e}"`);this.binary=e}}t.StartBinaryFailedError=StartBinaryFailedError;class InstanceInfoError extends Error{constructor(e){super(`"instanceInfo" was undefined when expected to be defined! (where: "${e}")`);this.where=e}}t.InstanceInfoError=InstanceInfoError;class KeyFileMissingError extends Error{constructor(){super(`"keyfileLocation" was undefined when expected!`)}}t.KeyFileMissingError=KeyFileMissingError;class AuthNotObjectError extends Error{constructor(){super('"auth" was not a object when it was expected!')}}t.AuthNotObjectError=AuthNotObjectError;class InsufficientPermissionsError extends Error{constructor(e){super(`File "${e}" does not have the required Permissions, required Permissions: "--x"`);this.path=e}}t.InsufficientPermissionsError=InsufficientPermissionsError;class BinaryNotFoundError extends Error{constructor(e){super(`No Binary at path "${e}" was found! (ENOENT)`);this.path=e}}t.BinaryNotFoundError=BinaryNotFoundError;class AssertionFallbackError extends Error{constructor(){super("Assert failed - no custom error")}}t.AssertionFallbackError=AssertionFallbackError;class ReplsetCountLowError extends Error{constructor(e){super(`ReplSet Count needs to be 1 or higher! (specified count: "${e}")`);this.count=e}}t.ReplsetCountLowError=ReplsetCountLowError;class ParseArchiveRegexError extends Error{constructor(e){super(`Expected "${e}" to be found in regex groups`);this.key=e}}t.ParseArchiveRegexError=ParseArchiveRegexError;class NoRegexMatchError extends Error{constructor(e,t){super();this.name=e;this.extra=t;const r=!!t?`(${t})`:"";this.message=`Expected "${e}" to have Regex Matches${r}`}}t.NoRegexMatchError=NoRegexMatchError;class KnownVersionIncompatibilityError extends Error{constructor(e,t,r,n){super();this.dist=e;this.requested_version=t;this.available_versions=r;this.extra=n;const o=!!n?`\n${n}`:"";this.message=`Requested Version "${t}" is not available for "${e}"! Available Versions: "${r}"${o}`}}t.KnownVersionIncompatibilityError=KnownVersionIncompatibilityError;class StdoutInstanceError extends Error{constructor(e){super(e)}}t.StdoutInstanceError=StdoutInstanceError},8278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.parseOS=t.parseLSB=t.getOS=t.isLinuxOS=void 0;const n=r(4351);const o=r(2037);const s=(0,n.__importDefault)(r(8237));const i=r(1978);const a=(0,s.default)("MongoMS:getos");const A={name:/^(?:distributor id:|DISTRIB_ID=)\s*(.*)$/im,codename:/^(?:codename:|DISTRIB_CODENAME=)\s*(.*)$/im,release:/^(?:release:|DISTRIB_RELEASE=)\s*(.*)$/im};const c={name:/^id\s*=\s*"?(\w*)"?$/im,codename:/^version_codename\s*=\s*(.*)$/im,release:/^version_id\s*=\s*"?(\d*(?:\.\d*)?)"?$/im,id_like:/^id_like\s*=\s*"?([\w\s]*)"?$/im};function isLinuxOS(e){return e.os==="linux"}t.isLinuxOS=isLinuxOS;let l;function getOS(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){if(!l){const e=(0,o.platform)();if(e==="linux"){l=yield getLinuxInformation()}else{l={os:e}}}return l}))}t.getOS=getOS;function getLinuxInformation(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){const e=yield(0,i.tryReleaseFile)("/etc/upstream-release/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(e)){a("getLinuxInformation: Using UpstreamLSB");return e}const t=yield(0,i.tryReleaseFile)("/etc/os-release",parseOS);if(!(0,i.isNullOrUndefined)(t)){a("getLinuxInformation: Using etcOsRelease");return t}const r=yield(0,i.tryReleaseFile)("/usr/lib/os-release",parseOS);if(!(0,i.isNullOrUndefined)(r)){a("getLinuxInformation: Using usrOsRelease");return r}const n=yield(0,i.tryReleaseFile)("/etc/lsb-release",parseLSB);if(!(0,i.isNullOrUndefined)(n)){a("getLinuxInformation: Using etcLSBRelease");return n}console.warn("Could not find any Release File, using fallback binary");return{os:"linux",dist:"unknown",release:""}}))}function parseLSB(e){var t,r,n,o,s;return{os:"linux",dist:(r=(t=e.match(A.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(A.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(A.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:""}}t.parseLSB=parseLSB;function parseOS(e){var t,r,n,o,s,i;return{os:"linux",dist:(r=(t=e.match(c.name))===null||t===void 0?void 0:t[1].toLocaleLowerCase())!==null&&r!==void 0?r:"unknown",codename:(n=e.match(c.codename))===null||n===void 0?void 0:n[1].toLocaleLowerCase(),release:(s=(o=e.match(c.release))===null||o===void 0?void 0:o[1].toLocaleLowerCase())!==null&&s!==void 0?s:"",id_like:(i=e.match(c.id_like))===null||i===void 0?void 0:i[1].toLocaleLowerCase().split(" ")}}t.parseOS=parseOS},4908:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.LockFile=t.LockFileEvents=t.LockFileStatus=void 0;const n=r(4351);const o=r(2361);const s=(0,n.__importStar)(r(1978));const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(4038);const l=r(5840);const u=r(3386);const h=(0,i.default)("MongoMS:LockFile");class RepeatError extends Error{constructor(e){super();this.repeat=e}}var d;(function(e){e[e["available"]=0]="available";e[e["availableInstance"]=1]="availableInstance";e[e["lockedSelf"]=2]="lockedSelf";e[e["lockedDifferent"]=3]="lockedDifferent"})(d=t.LockFileStatus||(t.LockFileStatus={}));var g;(function(e){e["lock"]="lock";e["unlock"]="unlock"})(g=t.LockFileEvents||(t.LockFileEvents={}));class LockFileEventsClass extends o.EventEmitter{}class LockFile{constructor(e,t){this.file=e;this.uuid=t}static lock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`lock: Locking file "${e}"`);const t=a.resolve(e.trim());s.assertion(t.length>0,new Error("Provided Path for lock file is length of 0"));const r=yield this.checkLock(t);switch(r){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(t);case d.available:return this.createLock(t);default:throw new u.UnknownLockfileStatusError(r)}}))}static checkLock(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`checkLock: for file "${e}" with uuid: "${t}"`);if(!(yield s.pathExists(e))){return d.available}try{const r=(yield A.promises.readFile(e)).toString().trim().split(" ");const n=parseInt(r[0]);if(n===process.pid){h(`checkLock: Lock File Already exists, and is for *this* process, with uuid: "${r[1]}"`);if(!this.files.has(e)){return d.available}if(!s.isNullOrUndefined(t)){return t===r[1]?d.availableInstance:d.lockedSelf}return d.lockedSelf}h(`checkLock: Lock File Aready exists, for a different process: "${n}"`);return s.isAlive(n)?d.lockedDifferent:d.available}catch(e){if(s.errorWithCode(e)&&e.code==="ENOENT"){h("checkLock: reading file failed with ENOENT");return d.available}throw e}}))}static waitForLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`waitForLock: Starting to wait for file "${e}"`);let t=undefined;let r=undefined;yield new Promise((o=>{r=t=>{if(t===e){o()}};t=setInterval((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){const t=yield this.checkLock(e);h(`waitForLock: Interval for file "${e}" with status "${t}"`);if(t===d.available){o()}}))),1e3*3);this.events.on(g.unlock,r)}));if(t){clearInterval(t)}if(r){this.events.removeListener(g.unlock,r)}h(`waitForLock: File became available "${e}"`);yield s.ensureAsync();const o=yield this.checkLock(e);h(`waitForLock: Lock File Status reassessment for file "${e}": ${o}`);switch(o){case d.lockedDifferent:case d.lockedSelf:return this.waitForLock(e);case d.available:return this.createLock(e);default:throw new u.UnknownLockfileStatusError(o)}}))}static createLock(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`createLock: trying to create a lock file for "${e}"`);const t=(0,l.v4)();try{yield this.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){if(this.files.has(e)){h(`createLock: Map already has file "${e}"`);throw new RepeatError(true)}yield s.mkdir(a.dirname(e));yield A.promises.writeFile(e,`${process.pid.toString()} ${t}`);this.files.add(e);this.events.emit(g.lock,e)}))))}catch(t){if(t instanceof RepeatError&&t.repeat){return this.waitForLock(e)}}h(`createLock: Lock File Created for file "${e}"`);return new this(e,t)}))}unlock(){var e;return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.ensureAsync();h(`unlock: Unlocking file "${this.file}"`);if(s.isNullOrUndefined(this.file)||((e=this.file)===null||e===void 0?void 0:e.length)<=0){h("unlock: invalid file, returning");return}switch(yield LockFile.checkLock(this.file,this.uuid)){case d.available:h(`unlock: Lock Status was already "available" for file "${this.file}"`);yield this.unlockCleanup(false);return;case d.availableInstance:h(`unlock: Lock Status was "availableInstance" for file "${this.file}"`);yield this.unlockCleanup(true);return;case d.lockedSelf:throw new u.UnableToUnlockLockfileError(true,this.file);default:throw new u.UnableToUnlockLockfileError(false,this.file)}}))}unlockCleanup(e=true){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return yield LockFile.mutex.runExclusive((()=>(0,n.__awaiter)(this,void 0,void 0,(function*(){h(`unlockCleanup: for file "${this.file}"`);if(s.isNullOrUndefined(this.file)){return}if(e){yield A.promises.unlink(this.file).catch((e=>{h(`unlockCleanup: lock file unlink failed: "${e}"`)}))}LockFile.files.delete(this.file);LockFile.events.emit(g.unlock,this.file);this.file=undefined;this.uuid=undefined}))))}))}}t.LockFile=LockFile;LockFile.files=new Set;LockFile.events=new LockFileEventsClass;LockFile.mutex=new c.Mutex},8730:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.envToBool=t.envName=t.resolveConfig=t.processConfigOption=t.findPackageJson=t.setDefaultValue=t.defaultValues=t.DEFAULT_VERSION=t.ENV_CONFIG_PREFIX=t.ResolveConfigVariables=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(1362));const s=r(1156);const i=(0,n.__importDefault)(r(8237));const a=(0,n.__importStar)(r(1017));const A=r(7147);const c=r(1978);const l=(0,i.default)("MongoMS:ResolveConfig");var u;(function(e){e["DOWNLOAD_DIR"]="DOWNLOAD_DIR";e["PLATFORM"]="PLATFORM";e["ARCH"]="ARCH";e["VERSION"]="VERSION";e["DEBUG"]="DEBUG";e["DOWNLOAD_MIRROR"]="DOWNLOAD_MIRROR";e["DOWNLOAD_URL"]="DOWNLOAD_URL";e["PREFER_GLOBAL_PATH"]="PREFER_GLOBAL_PATH";e["DISABLE_POSTINSTALL"]="DISABLE_POSTINSTALL";e["SYSTEM_BINARY"]="SYSTEM_BINARY";e["MD5_CHECK"]="MD5_CHECK";e["ARCHIVE_NAME"]="ARCHIVE_NAME";e["RUNTIME_DOWNLOAD"]="RUNTIME_DOWNLOAD";e["USE_HTTP"]="USE_HTTP";e["SYSTEM_BINARY_VERSION_CHECK"]="SYSTEM_BINARY_VERSION_CHECK";e["USE_ARCHIVE_NAME_FOR_BINARY_NAME"]="USE_ARCHIVE_NAME_FOR_BINARY_NAME"})(u=t.ResolveConfigVariables||(t.ResolveConfigVariables={}));t.ENV_CONFIG_PREFIX="MONGOMS_";t.DEFAULT_VERSION="5.0.8";t.defaultValues=new Map([[u.VERSION,t.DEFAULT_VERSION],[u.PREFER_GLOBAL_PATH,"true"],[u.RUNTIME_DOWNLOAD,"true"],[u.USE_HTTP,"false"],[u.SYSTEM_BINARY_VERSION_CHECK,"true"],[u.USE_ARCHIVE_NAME_FOR_BINARY_NAME,"false"]]);function setDefaultValue(e,r){t.defaultValues.set(e,r)}t.setDefaultValue=setDefaultValue;let h=undefined;function findPackageJson(e){var t;for(const r of(0,s.findSync)(e||process.cwd())){l(`findPackageJson: Found package.json at "${r}"`);const e=JSON.parse((0,A.readFileSync)(r).toString());const n=(t=e===null||e===void 0?void 0:e.config)===null||t===void 0?void 0:t.mongodbMemoryServer;if(!(0,c.isNullOrUndefined)(n)&&Object.keys(n!==null&&n!==void 0?n:{}).length>0){l(`findPackageJson: Found package with non-empty config field at "${r}"`);const e=a.dirname(r);h={filePath:e,config:processConfigOption(n,e)};break}}return h}t.findPackageJson=findPackageJson;function processConfigOption(e,t){l("processConfigOption",e,t);if(typeof e!=="object"){l("processConfigOptions: input was not a object");return{}}const r=e;const n=(0,o.default)(u.DOWNLOAD_DIR);const s=(0,o.default)(u.SYSTEM_BINARY);if(n in r){r[n]=a.resolve(t,r[n])}if(s in r){r[s]=a.resolve(t,r[s])}return r}t.processConfigOption=processConfigOption;function resolveConfig(e){var r,n,s;return(s=(n=(r=process.env[envName(e)])!==null&&r!==void 0?r:h===null||h===void 0?void 0:h.config[(0,o.default)(e)])!==null&&n!==void 0?n:t.defaultValues.get(e))===null||s===void 0?void 0:s.toString()}t.resolveConfig=resolveConfig;t["default"]=resolveConfig;function envName(e){return`${t.ENV_CONFIG_PREFIX}${e}`}t.envName=envName;function envToBool(e=""){if(typeof e!=="string"){l("envToBool: input was not a string!");return false}return["1","on","yes","true"].indexOf(e.toLowerCase())!==-1}t.envToBool=envToBool;if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through Environment Variable")}findPackageJson();if(envToBool(resolveConfig(u.DEBUG))){i.default.enable("MongoMS:*");l("Debug Mode Enabled, through package.json")}},1978:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.mkdir=t.checkBinaryPermissions=t.ManagerAdvanced=t.ManagerBase=t.tryReleaseFile=t.pathExists=t.statPath=t.authDefault=t.ensureAsync=t.isAlive=t.killProcess=t.assertion=t.isNullOrUndefined=t.uriTemplate=t.getHost=t.generateDbName=t.errorWithCode=void 0;const n=r(4351);const o=(0,n.__importDefault)(r(8237));const s=r(7147);const i=r(3386);const a=(0,o.default)("MongoMS:utils");function errorWithCode(e){return e instanceof Error&&"code"in e}t.errorWithCode=errorWithCode;function generateDbName(e){return e||""}t.generateDbName=generateDbName;function getHost(e){return e.replace(/(?:^mongodb:\/{2})|(?:\/.*$)|(?:.*@)/gim,"")}t.getHost=getHost;function uriTemplate(e,t,r,n){const o=!isNullOrUndefined(t)?`${e}:${t}`:e;return`mongodb://${o}/${r}`+(!isNullOrUndefined(n)?`?${n.join("&")}`:"")}t.uriTemplate=uriTemplate;function isNullOrUndefined(e){return e===null||e===undefined}t.isNullOrUndefined=isNullOrUndefined;function assertion(e,t){if(!e){throw t!==null&&t!==void 0?t:new i.AssertionFallbackError}}t.assertion=assertion;function killProcess(e,t,r){return(0,n.__awaiter)(this,void 0,void 0,(function*(){function ilog(e){a(`Mongo[${r||"unknown"}] killProcess: ${e}`)}if(!isAlive(e.pid)){ilog("given childProcess's PID was not alive anymore");return}const n=1e3*10;yield new Promise(((r,s)=>{let i=setTimeout((()=>{ilog("killProcess: timeout triggered, trying SIGKILL");if(!o.default.enabled("MongoMS:utils")){console.warn('An Process didnt exit with signal "SIGINT" within 10 seconds, using "SIGKILL"!\n'+"Enable debug logs for more information")}e.kill("SIGKILL");i=setTimeout((()=>{ilog("killProcess: timeout triggered again, rejecting");s(new Error(`Process "${t}" didnt exit, enable debug for more information.`))}),n)}),n);e.once(`exit`,((e,n)=>{ilog(`killProcess: ${t}: got exit signal, Code: ${e}, Signal: ${n}`);clearTimeout(i);r()}));ilog(`killProcess: ${t}: sending "SIGINT"`);e.kill("SIGINT")}))}))}t.killProcess=killProcess;function isAlive(e){if(isNullOrUndefined(e)){return false}try{process.kill(e,0);return true}catch(e){return false}}t.isAlive=isAlive;function ensureAsync(){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return new Promise((e=>process.nextTick(e)))}))}t.ensureAsync=ensureAsync;function authDefault(e){return Object.assign({force:false,disable:false,customRootName:"mongodb-memory-server-root",customRootPwd:"rootuser",extraUsers:[],keyfileContent:"0123456789"},e)}t.authDefault=authDefault;function statPath(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(["ENOENT","EACCES"].includes(e.code)){return undefined}throw e}))}))}t.statPath=statPath;function pathExists(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){return!isNullOrUndefined(yield statPath(e))}))}t.pathExists=pathExists;function tryReleaseFile(e,t){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{const r=yield s.promises.readFile(e);return t(r.toString())}catch(t){if(errorWithCode(t)&&!["ENOENT","EACCES"].includes(t.code)){throw t}a(`tryReleaseFile: "${e}" does not exist`);return undefined}}))}t.tryReleaseFile=tryReleaseFile;class ManagerBase{}t.ManagerBase=ManagerBase;class ManagerAdvanced extends ManagerBase{}t.ManagerAdvanced=ManagerAdvanced;function checkBinaryPermissions(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){try{yield s.promises.access(e,s.constants.X_OK)}catch(t){if(errorWithCode(t)){if(t.code==="EACCES"){throw new i.InsufficientPermissionsError(e)}if(t.code==="ENOENT"){throw new i.BinaryNotFoundError(e)}}throw t}}))}t.checkBinaryPermissions=checkBinaryPermissions;function mkdir(e){return(0,n.__awaiter)(this,void 0,void 0,(function*(){yield s.promises.mkdir(e,{recursive:true})}))}t.mkdir=mkdir},5517:(e,t,r)=>{"use strict";const n=r(3994);const o=r(2138);const s=r(1545).connect;s.MongoError=n.MongoError;s.MongoNetworkError=n.MongoNetworkError;s.MongoTimeoutError=n.MongoTimeoutError;s.MongoServerSelectionError=n.MongoServerSelectionError;s.MongoParseError=n.MongoParseError;s.MongoWriteConcernError=n.MongoWriteConcernError;s.MongoBulkWriteError=r(4239).BulkWriteError;s.BulkWriteError=s.MongoBulkWriteError;s.ServerApiVersion=n.ServerApiVersion;s.Admin=r(3238);s.MongoClient=r(1545);s.Db=r(6662);s.Collection=r(5193);s.Server=r(8421);s.ReplSet=r(382);s.Mongos=r(2048);s.ReadPreference=n.ReadPreference;s.GridStore=r(9406);s.Chunk=r(3890);s.Logger=n.Logger;s.AggregationCursor=r(7429);s.CommandCursor=r(538);s.Cursor=r(7159);s.GridFSBucket=r(2573);s.CoreServer=n.Server;s.CoreConnection=n.Connection;s.Binary=n.BSON.Binary;s.Code=n.BSON.Code;s.Map=n.BSON.Map;s.DBRef=n.BSON.DBRef;s.Double=n.BSON.Double;s.Int32=n.BSON.Int32;s.Long=n.BSON.Long;s.MinKey=n.BSON.MinKey;s.MaxKey=n.BSON.MaxKey;s.ObjectID=n.BSON.ObjectID;s.ObjectId=n.BSON.ObjectID;s.Symbol=n.BSON.Symbol;s.Timestamp=n.BSON.Timestamp;s.BSONRegExp=n.BSON.BSONRegExp;s.Decimal128=n.BSON.Decimal128;s.connect=s;s.instrument=function(e,t){if(typeof e==="function"){t=e;e={}}const r=new o;r.instrument(s.MongoClient,t);return r};e.exports=s},3238:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(7057);const s=r(1681);const i=r(1969);const a=r(9263);const A=r(9929);const c=r(2548);function Admin(e,t,r){if(!(this instanceof Admin))return new Admin(e,t);this.s={db:e,topology:t,promiseLibrary:r}}Admin.prototype.command=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():{};const o=new s(this.s.db,e,t);return c(this.s.db.s.topology,o,r)};Admin.prototype.buildInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverInfo=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={buildinfo:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.serverStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{serverStatus:1},e);return c(this.s.db.s.topology,r,t)};Admin.prototype.ping=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={ping:1};const n=new s(this.s.db,r,e);return c(this.s.db.s.topology,n,t)};Admin.prototype.addUser=function(e,t,r,s){const i=Array.prototype.slice.call(arguments,2);s=typeof i[i.length-1]==="function"?i.pop():undefined;if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}r=i.length?i.shift():{};r=Object.assign({},r);r=n(r,{db:this.s.db});r.dbName="admin";const a=new o(this.s.db,e,t,r);return c(this.s.db.s.topology,a,s)};Admin.prototype.removeUser=function(e,t,r){const o=Array.prototype.slice.call(arguments,1);r=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():{};t=Object.assign({},t);t=n(t,{db:this.s.db});t.dbName="admin";const s=new i(this.s.db,e,t);return c(this.s.db.s.topology,s,r)};Admin.prototype.validateCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new a(this,e,t);return c(this.s.db.s.topology,n,r)};Admin.prototype.listDatabases=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return c(this.s.db.s.topology,new A(this.s.db,e),t)};Admin.prototype.replSetGetStatus=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new s(this.s.db,{replSetGetStatus:1},e);return c(this.s.db.s.topology,r,t)};e.exports=Admin},7429:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(7159);const s=r(4847).CursorState;class AggregationCursor extends o{constructor(e,t,r){super(e,t,r)}batchSize(e){if(this.s.state===s.CLOSED||this.isDead()){throw n.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw n.create({message:"batchSize requires an integer",driver:true})}this.operation.options.batchSize=e;this.setCursorBatchSize(e);return this}geoNear(e){this.operation.addToPipeline({$geoNear:e});return this}group(e){this.operation.addToPipeline({$group:e});return this}limit(e){this.operation.addToPipeline({$limit:e});return this}match(e){this.operation.addToPipeline({$match:e});return this}maxTimeMS(e){this.operation.options.maxTimeMS=e;return this}out(e){this.operation.addToPipeline({$out:e});return this}project(e){this.operation.addToPipeline({$project:e});return this}lookup(e){this.operation.addToPipeline({$lookup:e});return this}redact(e){this.operation.addToPipeline({$redact:e});return this}skip(e){this.operation.addToPipeline({$skip:e});return this}sort(e){this.operation.addToPipeline({$sort:e});return this}unwind(e){this.operation.addToPipeline({$unwind:e});return this}getLogger(){return this.logger}}AggregationCursor.prototype.get=AggregationCursor.prototype.toArray;e.exports=AggregationCursor},2138:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;class Instrumentation extends n{constructor(){super()}instrument(e,t){this.$MongoClient=e;const r=this.$prototypeConnect=e.prototype.connect;const n=this;e.prototype.connect=function(e){this.s.options.monitorCommands=true;this.on("commandStarted",(e=>n.emit("started",e)));this.on("commandSucceeded",(e=>n.emit("succeeded",e)));this.on("commandFailed",(e=>n.emit("failed",e)));return r.call(this,e)};if(typeof t==="function")t(null,this)}uninstrument(){this.$MongoClient.prototype.connect=this.$prototypeConnect}}e.exports=Instrumentation},1749:(e,t)=>{"use strict";function asyncIterator(){const e=this;return{next:function(){return Promise.resolve().then((()=>e.next())).then((t=>{if(!t){return e.close().then((()=>({value:t,done:true})))}return{value:t,done:false}}))}}}t.asyncIterator=asyncIterator},4239:(e,t,r)=>{"use strict";const n=r(3994).BSON.Long;const o=r(3994).MongoError;const s=r(3994).BSON.ObjectID;const i=r(3994).BSON;const a=r(3994).MongoWriteConcernError;const A=r(1371).emitWarningOnce;const c=r(1371).toError;const l=r(1371).handleCallback;const u=r(1371).applyRetryableWrites;const h=r(1371).applyWriteConcern;const d=r(1371).executeLegacyOperation;const g=r(1371).isPromiseLike;const p=r(1371).hasAtomicOperators;const E=r(1178).maxWireVersion;const m=64;const C=1;const I=2;const y=3;const B=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 Batch{constructor(e,t){this.originalZeroIndex=t;this.currentIndex=0;this.originalIndexes=[];this.batchType=e;this.operations=[];this.size=0;this.sizeBytes=0}}const Q=Symbol("upsertedIds");const b=Symbol("insertedIds");class BulkWriteResult{constructor(e){this.result=e;this[Q]=undefined;this[b]=undefined}get insertedCount(){return typeof this.result.nInserted!=="number"?0:this.result.nInserted}get matchedCount(){return typeof this.result.nMatched!=="number"?0:this.result.nMatched}get modifiedCount(){return typeof this.result.nModified!=="number"?0:this.result.nModified}get deletedCount(){return typeof this.result.nRemoved!=="number"?0:this.result.nRemoved}get upsertedCount(){return!this.result.upserted?0:this.result.upserted.length}get upsertedIds(){if(this[Q]){return this[Q]}this[Q]={};for(const e of this.result.upserted||[]){this[Q][e.index]=e._id}return this[Q]}get insertedIds(){if(this[b]){return this[b]}this[b]={};for(const e of this.result.insertedIds||[]){this[b][e.index]=e._id}return this[b]}get n(){return this.result.insertedCount}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){if(ee.multi))}if(e.batch.batchType===y){r.retryWrites=r.retryWrites&&!e.batch.operations.some((e=>e.limit===0))}}try{if(e.batch.batchType===C){this.s.topology.insert(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===I){this.s.topology.update(this.s.namespace,e.batch.operations,r,e.resultHandler)}else if(e.batch.batchType===y){this.s.topology.remove(this.s.namespace,e.batch.operations,r,e.resultHandler)}}catch(r){r.ok=0;l(t,null,mergeBatchResults(e.batch,this.s.bulkResult,r,null))}}handleWriteError(e,t){if(this.s.bulkResult.writeErrors.length>0){const r=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";l(e,new BulkWriteError(c({message:r,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors}),t),null);return true}if(t.getWriteConcernError()){l(e,new BulkWriteError(c(t.getWriteConcernError()),t),null);return true}}}Object.defineProperty(BulkOperationBase.prototype,"length",{enumerable:true,get:function(){return this.s.currentIndex}});e.exports={Batch:Batch,BulkOperationBase:BulkOperationBase,mergeBatchResults:mergeBatchResults,bson:B,INSERT:C,UPDATE:I,REMOVE:y,BulkWriteError:BulkWriteError,BulkWriteResult:BulkWriteResult}},5035:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);const a=e.s.maxKeySize;if(e.s.currentBatchSize+1>=e.s.maxWriteBatchSize||e.s.currentBatchSize>0&&e.s.currentBatchSizeBytes+a+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}if(t===n.INSERT){e.s.bulkResult.insertedIds.push({index:e.s.currentIndex,_id:r._id})}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentBatch.operations.push(r);e.s.currentBatchSize+=1;e.s.currentBatchSizeBytes+=a+o;e.s.currentIndex+=1;return e}class OrderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,true)}}function initializeOrderedBulkOp(e,t,r){return new OrderedBulkOperation(e,t,r)}initializeOrderedBulkOp.OrderedBulkOperation=OrderedBulkOperation;e.exports=initializeOrderedBulkOp;e.exports.Bulk=OrderedBulkOperation},325:(e,t,r)=>{"use strict";const n=r(4239);const o=n.BulkOperationBase;const s=n.Batch;const i=n.bson;const a=r(1371);const A=a.toError;function addToOperationsList(e,t,r){const o=i.calculateObjectSize(r,{checkKeys:false,ignoreUndefined:false});if(o>=e.s.maxBsonObjectSize)throw A("document is larger than the maximum size "+e.s.maxBsonObjectSize);e.s.currentBatch=null;if(t===n.INSERT){e.s.currentBatch=e.s.currentInsertBatch}else if(t===n.UPDATE){e.s.currentBatch=e.s.currentUpdateBatch}else if(t===n.REMOVE){e.s.currentBatch=e.s.currentRemoveBatch}const a=e.s.maxKeySize;if(e.s.currentBatch==null)e.s.currentBatch=new s(t,e.s.currentIndex);if(e.s.currentBatch.size+1>=e.s.maxWriteBatchSize||e.s.currentBatch.size>0&&e.s.currentBatch.sizeBytes+a+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)}if(Array.isArray(r)){throw A("operation passed in cannot be an Array")}e.s.currentBatch.operations.push(r);e.s.currentBatch.originalIndexes.push(e.s.currentIndex);e.s.currentIndex=e.s.currentIndex+1;if(t===n.INSERT){e.s.currentInsertBatch=e.s.currentBatch;e.s.bulkResult.insertedIds.push({index:e.s.bulkResult.insertedIds.length,_id:r._id})}else if(t===n.UPDATE){e.s.currentUpdateBatch=e.s.currentBatch}else if(t===n.REMOVE){e.s.currentRemoveBatch=e.s.currentBatch}e.s.currentBatch.size+=1;e.s.currentBatch.sizeBytes+=a+o;return e}class UnorderedBulkOperation extends o{constructor(e,t,r){r=r||{};r=Object.assign(r,{addToOperationsList:addToOperationsList});super(e,t,r,false)}handleWriteError(e,t){if(this.s.batches.length){return false}return super.handleWriteError(e,t)}}function initializeUnorderedBulkOp(e,t,r){return new UnorderedBulkOperation(e,t,r)}initializeUnorderedBulkOp.UnorderedBulkOperation=UnorderedBulkOperation;e.exports=initializeUnorderedBulkOp;e.exports.Bulk=UnorderedBulkOperation},1117:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(9386).isResumableError;const i=r(3994).MongoError;const a=r(7159);const A=r(1178).relayEvents;const c=r(1178).maxWireVersion;const l=r(1371).maybePromise;const u=r(1371).now;const h=r(1371).calculateDurationInMs;const d=r(1554);const g=Symbol("resumeQueue");const p=["resumeAfter","startAfter","startAtOperationTime","fullDocument"];const E=["batchSize","maxAwaitTimeMS","collation","readPreference"].concat(p);const m={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")};class ChangeStream extends o{constructor(e,t,o){super();const s=r(5193);const i=r(6662);const a=r(1545);this.pipeline=t||[];this.options=o||{};this.parent=e;this.namespace=e.s.namespace;if(e instanceof s){this.type=m.COLLECTION;this.topology=e.s.db.serverConfig}else if(e instanceof i){this.type=m.DATABASE;this.topology=e.serverConfig}else if(e instanceof a){this.type=m.CLUSTER;this.topology=e.topology}else{throw new TypeError("parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient")}this.promiseLibrary=e.s.promiseLibrary;if(!this.options.readPreference&&e.s.readPreference){this.options.readPreference=e.s.readPreference}this[g]=new n;this.cursor=createChangeStreamCursor(this,o);this.closed=false;this.on("newListener",(e=>{if(e==="change"&&this.cursor&&this.listenerCount("change")===0){this.cursor.on("data",(e=>processNewChange(this,e)))}}));this.on("removeListener",(e=>{if(e==="change"&&this.listenerCount("change")===0&&this.cursor){this.cursor.removeAllListeners("data")}}))}get resumeToken(){return this.cursor.resumeToken}hasNext(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.hasNext(e)}))}))}next(e){return l(this.parent,e,(e=>{getCursor(this,((t,r)=>{if(t)return e(t);r.next(((t,r)=>{if(t){this[g].push((()=>this.next(e)));processError(this,t,e);return}processNewChange(this,r,e)}))}))}))}isClosed(){return this.closed||this.cursor&&this.cursor.isClosed()}close(e){return l(this.parent,e,(e=>{if(this.closed)return e();this.closed=true;if(!this.cursor)return e();const t=this.cursor;return t.close((r=>{["data","close","end","error"].forEach((e=>t.removeAllListeners(e)));this.cursor=undefined;return e(r)}))}))}pipe(e,t){if(!this.pipeDestinations){this.pipeDestinations=[]}this.pipeDestinations.push(e);return this.cursor.pipe(e,t)}unpipe(e){if(this.pipeDestinations&&this.pipeDestinations.indexOf(e)>-1){this.pipeDestinations.splice(this.pipeDestinations.indexOf(e),1)}return this.cursor.unpipe(e)}stream(e){this.streamOptions=e;return this.cursor.stream(e)}pause(){return this.cursor.pause()}resume(){return this.cursor.resume()}}class ChangeStreamCursor extends a{constructor(e,t,r){super(e,t,r);r=r||{};this._resumeToken=null;this.startAtOperationTime=r.startAtOperationTime;if(r.startAfter){this.resumeToken=r.startAfter}else if(r.resumeAfter){this.resumeToken=r.resumeAfter}}set resumeToken(e){this._resumeToken=e;this.emit("resumeTokenChanged",e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={};for(const t of E){if(this.options[t])e[t]=this.options[t]}if(this.resumeToken||this.startAtOperationTime){["resumeAfter","startAfter","startAtOperationTime"].forEach((t=>delete e[t]));if(this.resumeToken){const t=this.options.startAfter&&!this.hasReceived?"startAfter":"resumeAfter";e[t]=this.resumeToken}else if(this.startAtOperationTime&&c(this.server)>=7){e.startAtOperationTime=this.startAtOperationTime}}return e}cacheResumeToken(e){if(this.bufferedCount()===0&&this.cursorState.postBatchResumeToken){this.resumeToken=this.cursorState.postBatchResumeToken}else{this.resumeToken=e}this.hasReceived=true}_processBatch(e,t){const r=t.cursor;if(r.postBatchResumeToken){this.cursorState.postBatchResumeToken=r.postBatchResumeToken;if(r[e].length===0){this.resumeToken=r.postBatchResumeToken}}}_initializeCursor(e){super._initializeCursor(((t,r)=>{if(t||r==null){e(t,r);return}const n=r.documents[0];if(this.startAtOperationTime==null&&this.resumeAfter==null&&this.startAfter==null&&c(this.server)>=7){this.startAtOperationTime=n.operationTime}this._processBatch("firstBatch",n);this.emit("init",r);this.emit("response");e(t,r)}))}_getMore(e){super._getMore(((t,r)=>{if(t){e(t);return}this._processBatch("nextBatch",r);this.emit("more",r);this.emit("response");e(t,r)}))}}function createChangeStreamCursor(e,t){const r={fullDocument:t.fullDocument||"default"};applyKnownOptions(r,t,p);if(e.type===m.CLUSTER){r.allChangesForCluster=true}const n=[{$changeStream:r}].concat(e.pipeline);const o=applyKnownOptions({},t,E);const s=new ChangeStreamCursor(e.topology,new d(e.parent,n,t),o);A(s,e,["resumeTokenChanged","end","close"]);if(e.listenerCount("change")>0){s.on("data",(function(t){processNewChange(e,t)}))}s.on("error",(function(t){processError(e,t)}));if(e.pipeDestinations){const t=s.stream(e.streamOptions);for(let r of e.pipeDestinations){t.pipe(r)}}return s}function applyKnownOptions(e,t,r){r.forEach((r=>{if(t[r]){e[r]=t[r]}}));return e}const C=3e4;function waitForTopologyConnected(e,t,r){setTimeout((()=>{if(t&&t.start==null){t.start=u()}const n=t.start||u();const o=t.timeout||C;const s=t.readPreference;if(e.isConnected({readPreference:s})){return r()}if(h(n)>o){return r(new i("Timed out waiting for connection"))}waitForTopologyConnected(e,t,r)}),500)}function processNewChange(e,t,r){const n=e.cursor;if(t==null){e.closed=true}if(e.closed){if(r)r(new i("ChangeStream is closed"));return}if(t&&!t._id){const t=new Error("A change stream document has been received that lacks a resume token (_id).");if(!r)return e.emit("error",t);return r(t)}n.cacheResumeToken(t._id);e.options.startAtOperationTime=undefined;if(!r)return e.emit("change",t);return r(undefined,t)}function processError(e,t,r){const n=e.topology;const o=e.cursor;if(e.closed){if(r)r(new i("ChangeStream is closed"));return}function resumeWithCursor(t){e.cursor=t;processResumeQueue(e)}function unresumableError(t){if(!r){e.emit("error",t);e.emit("close")}processResumeQueue(e,t);e.closed=true}if(o&&s(t,c(o.server))){e.cursor=undefined;["data","close","end","error"].forEach((e=>o.removeAllListeners(e)));o.close();waitForTopologyConnected(n,{readPreference:o.options.readPreference},(t=>{if(t)return unresumableError(t);const n=createChangeStreamCursor(e,o.resumeOptions);if(!r)return resumeWithCursor(n);n.hasNext((e=>{if(e)return unresumableError(e);resumeWithCursor(n)}))}));return}if(!r)return e.emit("error",t);return r(t)}function getCursor(e,t){if(e.isClosed()){t(new i("ChangeStream is closed."));return}if(e.cursor){t(undefined,e.cursor);return}e[g].push(t)}function processResumeQueue(e,t){while(e[g].length){const r=e[g].pop();if(e.isClosed()&&!t){r(new i("Change Stream is not open."));return}r(t,e.cursor)}}e.exports=ChangeStream},9820:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2425);const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(3111).MongoNetworkTimeoutError;const A=r(3111).MongoWriteConcernError;const c=r(2337);const l=r(6292).StreamDescription;const u=r(9206);const h=r(9815);const d=r(5474).updateSessionFromResponse;const g=r(1178).uuidV4;const p=r(1371).now;const E=r(1371).calculateDurationInMs;const m=Symbol("stream");const C=Symbol("queue");const I=Symbol("messageStream");const y=Symbol("generation");const B=Symbol("lastUseTime");const Q=Symbol("clusterTime");const b=Symbol("description");const w=Symbol("ismaster");const S=Symbol("autoEncrypter");class Connection extends n{constructor(e,t){super(t);this.id=t.id;this.address=streamIdentifier(e);this.bson=t.bson;this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.host=t.host||"localhost";this.port=t.port||27017;this.monitorCommands=typeof t.monitorCommands==="boolean"?t.monitorCommands:false;this.serverApi=t.serverApi;this.closed=false;this.destroyed=false;this[b]=new l(this.address,t);this[y]=t.generation;this[B]=p();if(t.autoEncrypter){this[S]=t.autoEncrypter}this[C]=new Map;this[I]=new o(t);this[I].on("message",messageHandler(this));this[m]=e;e.on("error",(()=>{}));this[I].on("error",(e=>this.handleIssue({destroy:e})));e.on("close",(()=>this.handleIssue({isClose:true})));e.on("timeout",(()=>this.handleIssue({isTimeout:true,destroy:true})));e.pipe(this[I]);this[I].pipe(e)}get description(){return this[b]}get ismaster(){return this[w]}set ismaster(e){this[b].receiveResponse(e);this[w]=e}get generation(){return this[y]||0}get idleTime(){return E(this[B])}get clusterTime(){return this[Q]}get stream(){return this[m]}markAvailable(){this[B]=p()}handleIssue(e){if(this.closed){return}if(e.destroy){this[m].destroy(typeof e.destroy==="boolean"?undefined:e.destroy)}this.closed=true;for(const t of this[C]){const r=t[1];if(e.isTimeout){r.cb(new a(`connection ${this.id} to ${this.address} timed out`,{beforeHandshake:this.ismaster==null}))}else if(e.isClose){r.cb(new i(`connection ${this.id} to ${this.address} closed`))}else{r.cb(typeof e.destroy==="boolean"?undefined:e.destroy)}}this[C].clear();this.emit("close")}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(this[m]==null||this.destroyed){this.destroyed=true;if(typeof t==="function"){t()}return}if(e.force){this[m].destroy();this.destroyed=true;if(typeof t==="function"){t()}return}this[m].end((e=>{this.destroyed=true;if(typeof t==="function"){t(e)}}))}applyApiVersion(e){if(this.serverApi){e.serverApi=this.serverApi}return e}command(e,t,r,n){if(typeof r==="function"){n=r;r={}}u.command(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}query(e,t,r,n,o){u.query(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}getMore(e,t,r,n,o){u.getMore(makeServerTrampoline(this),e,t,r,this.applyApiVersion(n),o)}killCursors(e,t,r){u.killCursors(makeServerTrampoline(this),e,t,this.applyApiVersion({}),r)}insert(e,t,r,n){u.insert(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}update(e,t,r,n){u.update(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}remove(e,t,r,n){u.remove(makeServerTrampoline(this),e,t,this.applyApiVersion(r),n)}}function makeServerTrampoline(e){const t={description:e.description,clusterTime:e[Q],s:{bson:e.bson,pool:{write:write.bind(e),isConnected:()=>true}}};if(e[S]){t.autoEncrypter=e[S]}return t}function messageHandler(e){return function messageHandler(t){e.emit("message",t);if(!e[C].has(t.responseTo)){return}const r=e[C].get(t.responseTo);const n=r.cb;e[C].delete(t.responseTo);if(t.moreToCome){e[C].set(t.requestId,r)}else if(r.socketTimeoutOverride){e[m].setTimeout(e.socketTimeout)}try{t.parse(r)}catch(e){n(new s(e));return}if(t.documents[0]){const o=t.documents[0];const i=r.session;if(i){d(i,o)}if(o.$clusterTime){e[Q]=o.$clusterTime;e.emit("clusterTimeReceived",o.$clusterTime)}if(r.command){if(o.writeConcernError){n(new A(o.writeConcernError,o));return}if(o.ok===0||o.$err||o.errmsg||o.code){n(new s(o));return}}}n(undefined,new c(r.fullResult?t:t.documents[0],e,t))}}function streamIdentifier(e){if(typeof e.address==="function"){return`${e.remoteAddress}:${e.remotePort}`}return g().toString("hex")}function write(e,t,r){if(typeof t==="function"){r=t}t=t||{};const n={requestId:e.requestId,cb:r,session:t.session,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false,noResponse:typeof t.noResponse==="boolean"?t.noResponse:false,documentsReturnedIn:t.documentsReturnedIn,command:!!t.command,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,raw:typeof t.raw==="boolean"?t.raw:false};if(this[b]&&this[b].compressor){n.agreedCompressor=this[b].compressor;if(this[b].zlibCompressionLevel){n.zlibCompressionLevel=this[b].zlibCompressionLevel}}if(typeof t.socketTimeout==="number"){n.socketTimeoutOverride=true;this[m].setTimeout(t.socketTimeout)}if(this.monitorCommands){this.emit("commandStarted",new h.CommandStartedEvent(this,e));n.started=p();n.cb=(t,o)=>{if(t){this.emit("commandFailed",new h.CommandFailedEvent(this,e,t,n.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){this.emit("commandFailed",new h.CommandFailedEvent(this,e,o.result,n.started))}else{this.emit("commandSucceeded",new h.CommandSucceededEvent(this,e,o,n.started))}}if(typeof r==="function"){r(t,o)}}}if(!n.noResponse){this[C].set(n.requestId,n)}try{this[I].writeCommand(e,n)}catch(e){if(!n.noResponse){this[C].delete(n.requestId);n.cb(e);return}}if(n.noResponse){n.cb()}}e.exports={Connection:Connection}},2529:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361).EventEmitter;const s=r(104);const i=r(1371).makeCounter;const a=r(3111).MongoError;const A=r(9820).Connection;const c=r(1178).eachAsync;const l=r(6573);const u=r(1178).relayEvents;const h=r(2926);const d=h.PoolClosedError;const g=h.WaitQueueTimeoutError;const p=r(897);const E=p.ConnectionPoolCreatedEvent;const m=p.ConnectionPoolClosedEvent;const C=p.ConnectionCreatedEvent;const I=p.ConnectionReadyEvent;const y=p.ConnectionClosedEvent;const B=p.ConnectionCheckOutStartedEvent;const Q=p.ConnectionCheckOutFailedEvent;const b=p.ConnectionCheckedOutEvent;const w=p.ConnectionCheckedInEvent;const S=p.ConnectionPoolClearedEvent;const v=Symbol("logger");const R=Symbol("connections");const k=Symbol("permits");const D=Symbol("minPoolSizeTimer");const N=Symbol("generation");const T=Symbol("connectionCounter");const O=Symbol("cancellationToken");const _=Symbol("waitQueue");const M=Symbol("cancelled");const L=new Set(["ssl","bson","connectionType","serverApi","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 resolveOptions(e,t){const r=Array.from(L).reduce(((t,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){t[r]=e[r]}return t}),{});return Object.freeze(Object.assign({},t,r))}class ConnectionPool extends o{constructor(e){super();e=e||{};this.closed=false;this.options=resolveOptions(e,{connectionType:A,maxPoolSize:typeof e.maxPoolSize==="number"?e.maxPoolSize:100,minPoolSize:typeof e.minPoolSize==="number"?e.minPoolSize:0,maxIdleTimeMS:typeof e.maxIdleTimeMS==="number"?e.maxIdleTimeMS:0,waitQueueTimeoutMS:typeof e.waitQueueTimeoutMS==="number"?e.waitQueueTimeoutMS:0,autoEncrypter:e.autoEncrypter,metadata:e.metadata,useUnifiedTopology:e.useUnifiedTopology});if(e.minSize>e.maxSize){throw new TypeError("Connection pool minimum size must not be greater than maximum pool size")}this[v]=s("ConnectionPool",e);this[R]=new n;this[k]=this.options.maxPoolSize;this[D]=undefined;this[N]=0;this[T]=i(1);this[O]=new o;this[O].setMaxListeners(Infinity);this[_]=new n;process.nextTick((()=>{this.emit("connectionPoolCreated",new E(this));ensureMinPoolSize(this)}))}get address(){return`${this.options.host}:${this.options.port}`}get generation(){return this[N]}get totalConnectionCount(){return this[R].length+(this.options.maxPoolSize-this[k])}get availableConnectionCount(){return this[R].length}get waitQueueSize(){return this[_].length}checkOut(e){this.emit("connectionCheckOutStarted",new B(this));if(this.closed){this.emit("connectionCheckOutFailed",new Q(this,"poolClosed"));e(new d(this));return}const t={callback:e};const r=this;const n=this.options.waitQueueTimeoutMS;if(n){t.timer=setTimeout((()=>{t[M]=true;t.timer=undefined;r.emit("connectionCheckOutFailed",new Q(r,"timeout"));t.callback(new g(r))}),n)}this[_].push(t);process.nextTick((()=>processWaitQueue(this)))}checkIn(e){const t=this.closed;const r=connectionIsStale(this,e);const n=!!(t||r||e.closed);if(!n){e.markAvailable();this[R].push(e)}this.emit("connectionCheckedIn",new w(this,e));if(n){const r=e.closed?"error":t?"poolClosed":"stale";destroyConnection(this,e,r)}process.nextTick((()=>processWaitQueue(this)))}clear(){this[N]+=1;this.emit("connectionPoolCleared",new S(this))}close(e,t){if(typeof e==="function"){t=e}e=Object.assign({force:false},e);if(this.closed){return t()}this[O].emit("cancel");while(this.waitQueueSize){const e=this[_].pop();clearTimeout(e.timer);if(!e[M]){e.callback(new a("connection pool closed"))}}if(this[D]){clearTimeout(this[D])}if(typeof this[T].return==="function"){this[T].return()}this.closed=true;c(this[R].toArray(),((t,r)=>{this.emit("connectionClosed",new y(this,t,"poolClosed"));t.destroy(e,r)}),(e=>{this[R].clear();this.emit("connectionPoolClosed",new m(this));t(e)}))}withConnection(e,t){this.checkOut(((r,n)=>{e(r,n,((e,r)=>{if(typeof t==="function"){if(e){t(e)}else{t(undefined,r)}}if(n){this.checkIn(n)}}))}))}}function ensureMinPoolSize(e){if(e.closed||e.options.minPoolSize===0){return}const t=e.options.minPoolSize;for(let r=e.totalConnectionCount;rensureMinPoolSize(e)),10)}function connectionIsStale(e,t){return t.generation!==e[N]}function connectionIsIdle(e,t){return!!(e.options.maxIdleTimeMS&&t.idleTime>e.options.maxIdleTimeMS)}function createConnection(e,t){const r=Object.assign({id:e[T].next().value,generation:e[N]},e.options);e[k]--;l(r,e[O],((r,n)=>{if(r){e[k]++;e[v].debug(`connection attempt failed with error [${JSON.stringify(r)}]`);if(typeof t==="function"){t(r)}return}if(e.closed){n.destroy({force:true});return}u(n,e,["commandStarted","commandFailed","commandSucceeded","clusterTimeReceived"]);e.emit("connectionCreated",new C(e,n));n.markAvailable();e.emit("connectionReady",new I(e,n));if(typeof t==="function"){t(undefined,n);return}e[R].push(n);process.nextTick((()=>processWaitQueue(e)))}))}function destroyConnection(e,t,r){e.emit("connectionClosed",new y(e,t,r));e[k]++;process.nextTick((()=>t.destroy()))}function processWaitQueue(e){if(e.closed){return}while(e.waitQueueSize){const t=e[_].peekFront();if(t[M]){e[_].shift();continue}if(!e.availableConnectionCount){break}const r=e[R].shift();const n=connectionIsStale(e,r);const o=connectionIsIdle(e,r);if(!n&&!o&&!r.closed){e.emit("connectionCheckedOut",new b(e,r));clearTimeout(t.timer);e[_].shift();t.callback(undefined,r);return}const s=r.closed?"error":n?"stale":"idle";destroyConnection(e,r,s)}const t=e.options.maxPoolSize;if(e.waitQueueSize&&(t<=0||e.totalConnectionCount{const n=e[_].shift();if(n==null||n[M]){if(t==null){e[R].push(r)}return}if(t){e.emit("connectionCheckOutFailed",new Q(e,t))}else{e.emit("connectionCheckedOut",new b(e,r))}clearTimeout(n.timer);n.callback(t,r)}));return}}e.exports={ConnectionPool:ConnectionPool}},2926:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class PoolClosedError extends n{constructor(e){super("Attempted to check out a connection from closed connection pool");this.name="MongoPoolClosedError";this.address=e.address}}class WaitQueueTimeoutError extends n{constructor(e){super("Timed out while checking out a connection from connection pool");this.name="MongoWaitQueueTimeoutError";this.address=e.address}}e.exports={PoolClosedError:PoolClosedError,WaitQueueTimeoutError:WaitQueueTimeoutError}},897:e=>{"use strict";class ConnectionPoolMonitoringEvent{constructor(e){this.time=new Date;this.address=e.address}}class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e);this.options=e.options}}class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t,r){super(e);this.connectionId=t.id;this.reason=r||"unknown"}}class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.reason=t}}class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent{constructor(e,t){super(e);this.connectionId=t.id}}class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent{constructor(e){super(e)}}const t=["connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];e.exports={CMAP_EVENT_NAMES:t,ConnectionPoolCreatedEvent:ConnectionPoolCreatedEvent,ConnectionPoolClosedEvent:ConnectionPoolClosedEvent,ConnectionCreatedEvent:ConnectionCreatedEvent,ConnectionReadyEvent:ConnectionReadyEvent,ConnectionClosedEvent:ConnectionClosedEvent,ConnectionCheckOutStartedEvent:ConnectionCheckOutStartedEvent,ConnectionCheckOutFailedEvent:ConnectionCheckOutFailedEvent,ConnectionCheckedOutEvent:ConnectionCheckedOutEvent,ConnectionCheckedInEvent:ConnectionCheckedInEvent,ConnectionPoolClearedEvent:ConnectionPoolClearedEvent}},2425:(e,t,r)=>{"use strict";const n=r(2781).Duplex;const o=r(336);const s=r(3111).MongoParseError;const i=r(7793).decompress;const a=r(9814).Response;const A=r(8988).BinMsg;const c=r(3111).MongoError;const l=r(7272).opcodes.OP_COMPRESSED;const u=r(7272).opcodes.OP_MSG;const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(8988).Msg;const I=1024*1024*16*4;const y=Symbol("buffer");class MessageStream extends n{constructor(e){e=e||{};super(e);this.bson=e.bson;this.maxBsonMessageSize=e.maxBsonMessageSize||I;this[y]=new o}_write(e,t,r){const n=this[y];n.append(e);processIncomingData(this,r)}_read(){return}writeCommand(e,t){const r=t&&!!t.agreedCompressor;if(!r||!canCompress(e)){const t=e.toBin();this.push(Array.isArray(t)?Buffer.concat(t):t);return}const n=Buffer.concat(e.toBin());const o=n.slice(h);const s=n.readInt32LE(12);p({options:t},o,((r,n)=>{if(r){t.cb(r,null);return}const i=Buffer.alloc(h);i.writeInt32LE(h+d+n.length,0);i.writeInt32LE(e.requestId,4);i.writeInt32LE(0,8);i.writeInt32LE(g.OP_COMPRESSED,12);const a=Buffer.alloc(d);a.writeInt32LE(s,0);a.writeInt32LE(o.length,4);a.writeUInt8(E[t.agreedCompressor],8);this.push(Buffer.concat([i,a,n]))}))}}function canCompress(e){const t=e instanceof C?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function processIncomingData(e,t){const r=e[y];if(r.length<4){t();return}const n=r.readInt32LE(0);if(n<0){t(new s(`Invalid message size: ${n}`));return}if(n>e.maxBsonMessageSize){t(new s(`Invalid message size: ${n}, max allowed: ${e.maxBsonMessageSize}`));return}if(n>r.length){t();return}const o=r.slice(0,n);r.consume(n);const d={length:o.readInt32LE(0),requestId:o.readInt32LE(4),responseTo:o.readInt32LE(8),opCode:o.readInt32LE(12)};let g=d.opCode===u?A:a;const p=e.responseOptions;if(d.opCode!==l){const n=o.slice(h);e.emit("message",new g(e.bson,o,d,n,p));if(r.length>=4){processIncomingData(e,t)}else{t()}return}d.fromCompressed=true;d.opCode=o.readInt32LE(h);d.length=o.readInt32LE(h+4);const E=o[h+8];const m=o.slice(h+9);g=d.opCode===u?A:a;i(E,m,((n,s)=>{if(n){t(n);return}if(s.length!==d.length){t(new c("Decompressing a compressed message from the server failed. The message is corrupt."));return}e.emit("message",new g(e.bson,o,d,s,p));if(r.length>=4){processIncomingData(e,t)}else{t()}}))}e.exports=MessageStream},6292:(e,t,r)=>{"use strict";const n=r(750).parseServerType;const o=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","__nodejs_mock_server__"];class StreamDescription{constructor(e,t){this.address=e;this.type=n(null);this.minWireVersion=undefined;this.maxWireVersion=undefined;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=n(e);o.forEach((t=>{if(typeof e[t]!=="undefined"){this[t]=e[t]}}));if(e.compression){this.compressor=this.compressors.filter((t=>e.compression.indexOf(t)!==-1))[0]}}}e.exports={StreamDescription:StreamDescription}},5193:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(1371).deprecateOptions;const s=r(1371).emitWarningOnce;const i=r(1371).checkCollectionName;const a=r(3994).BSON.ObjectID;const A=r(3994).MongoError;const c=r(1371).normalizeHintField;const l=r(1371).decorateCommand;const u=r(1371).decorateWithCollation;const h=r(1371).decorateWithReadConcern;const d=r(1371).formattedOrderClause;const g=r(3994).ReadPreference;const p=r(325);const E=r(5035);const m=r(1117);const C=r(1371).executeLegacyOperation;const I=r(2481);const y=r(7289);const B=r(1371).MongoDBNamespace;const Q=r(7429);const b=r(538);const w=r(6716).ensureIndex;const S=r(6716).group;const v=r(6716).parallelCollectionScan;const R=r(2296).removeDocuments;const k=r(6716).save;const D=r(2296).updateDocuments;const N=r(1554);const T=r(6976);const O=r(5131);const _=r(6394);const M=r(323);const L=r(6352);const F=r(6469);const U=r(2360).DropCollectionOperation;const P=r(3560);const G=r(5328);const Y=r(4451);const V=r(9961);const W=r(4497);const J=r(711);const q=r(5841);const j=r(4316);const z=r(1925);const $=r(8169);const K=r(4218);const X=r(7809);const Z=r(4245);const ee=r(3592);const te=r(9915);const re=r(4956);const ne=r(28);const oe=r(2779);const se=r(43);const ie=r(2808);const ae=r(6331);const Ae=r(2508);const ce=r(968);const le=r(9350);const ue=r(9068);const fe=r(2548);const he=["ignoreUndefined"];function Collection(e,t,r,n,o,s){i(n);const A=null;const c=s==null||s.slaveOk==null?e.slaveOk:s.slaveOk;const l=s==null||s.serializeFunctions==null?e.s.options.serializeFunctions:s.serializeFunctions;const u=s==null||s.raw==null?e.s.options.raw:s.raw;const h=s==null||s.promoteLongs==null?e.s.options.promoteLongs:s.promoteLongs;const d=s==null||s.promoteValues==null?e.s.options.promoteValues:s.promoteValues;const p=s==null||s.promoteBuffers==null?e.s.options.promoteBuffers:s.promoteBuffers;const E=s==null||s.bsonRegExp==null?e.s.options.bsonRegExp:s.bsonRegExp;const m=null;const C=new B(r,n);const Q=s.promiseLibrary||Promise;o=o==null?a:o;this.s={pkFactory:o,db:e,topology:t,options:s,namespace:C,readPreference:g.fromOptions(s),slaveOk:c,serializeFunctions:l,raw:u,promoteLongs:h,promoteValues:d,promoteBuffers:p,bsonRegExp:E,internalHint:A,collectionHint:m,promiseLibrary:Q,readConcern:y.fromOptions(s),writeConcern:I.fromOptions(s)}}Object.defineProperty(Collection.prototype,"dbName",{enumerable:true,get:function(){return this.s.namespace.db}});Object.defineProperty(Collection.prototype,"collectionName",{enumerable:true,get:function(){return this.s.namespace.collection}});Object.defineProperty(Collection.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Object.defineProperty(Collection.prototype,"readConcern",{enumerable:true,get:function(){if(this.s.readConcern==null){return this.s.db.readConcern}return this.s.readConcern}});Object.defineProperty(Collection.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return this.s.db.readPreference}return this.s.readPreference}});Object.defineProperty(Collection.prototype,"writeConcern",{enumerable:true,get:function(){if(this.s.writeConcern==null){return this.s.db.writeConcern}return this.s.writeConcern}});Object.defineProperty(Collection.prototype,"hint",{enumerable:true,get:function(){return this.s.collectionHint},set:function(e){this.s.collectionHint=c(e)}});const de=["maxScan","fields","snapshot","oplogReplay"];Collection.prototype.find=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `find()` must be a callback or undefined")}let n=e;if(typeof r!=="function"){if(typeof t==="function"){r=t;t=undefined}else if(t==null){r=typeof n==="function"?n:undefined;n=typeof n==="object"?n:undefined}}n=n==null?{}:n;const o=n;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+"]");t.name="MongoError";throw t}}if(n!=null&&n._bsontype==="ObjectID"){n={_id:n}}if(!t)t={};let i=t.projection||t.fields;if(i&&!Buffer.isBuffer(i)&&Array.isArray(i)){i=i.length?i.reduce(((e,t)=>{e[t]=1;return e}),{}):{_id:1}}let a=Object.assign({},t);for(let e in this.s.options){if(he.indexOf(e)!==-1){a[e]=this.s.options[e]}}a.skip=t.skip?t.skip:0;a.limit=t.limit?t.limit:0;a.raw=typeof t.raw==="boolean"?t.raw:this.s.raw;a.hint=t.hint!=null?c(t.hint):this.s.collectionHint;a.timeout=typeof t.timeout==="undefined"?undefined:t.timeout;a.slaveOk=t.slaveOk!=null?t.slaveOk:this.s.db.slaveOk;a.readPreference=g.resolve(this,a);if(a.readPreference!=null&&(a.readPreference!=="primary"||a.readPreference.mode!=="primary")){a.slaveOk=true}if(n!=null&&typeof n!=="object"){throw A.create({message:"query selector must be an object",driver:true})}const p={find:this.s.namespace.toString(),limit:a.limit,skip:a.skip,query:n};if(typeof t.allowDiskUse==="boolean"){p.allowDiskUse=t.allowDiskUse}if(typeof a.awaitdata==="boolean"){a.awaitData=a.awaitdata}if(typeof a.timeout==="boolean")a.noCursorTimeout=!a.timeout;l(p,a,["session","collation"]);if(i)p.fields=i;a.db=this.s.db;a.promiseLibrary=this.s.promiseLibrary;if(a.raw==null&&typeof this.s.raw==="boolean")a.raw=this.s.raw;if(a.promoteLongs==null&&typeof this.s.promoteLongs==="boolean")a.promoteLongs=this.s.promoteLongs;if(a.promoteValues==null&&typeof this.s.promoteValues==="boolean")a.promoteValues=this.s.promoteValues;if(a.promoteBuffers==null&&typeof this.s.promoteBuffers==="boolean")a.promoteBuffers=this.s.promoteBuffers;if(a.bsonRegExp==null&&typeof this.s.bsonRegExp==="boolean")a.bsonRegExp=this.s.bsonRegExp;if(p.sort){p.sort=d(p.sort)}h(p,this,t);try{u(p,this,t)}catch(e){if(typeof r==="function")return r(e,null);throw e}const E=this.s.topology.cursor(new V(this,this.s.namespace,p,a),a);if(typeof r==="function"){r(null,E);return}return E}));Collection.prototype.insertOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new te(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insertMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{ordered:true};const n=new ee(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.bulkWrite=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:true};if(!Array.isArray(e)){throw A.create({message:"operations must be an array of documents",driver:true})}const n=new T(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.insert=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{ordered:false};e=!Array.isArray(e)?[e]:e;if(t.keepGoing===true){t.ordered=false}return this.insertMany(e,t,r)}),"collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.");Collection.prototype.updateOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new ue(this,e,t,r),n)};Collection.prototype.replaceOne=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new Ae(this,e,t,r),n)};Collection.prototype.updateMany=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r);if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new le(this,e,t,r),n)};Collection.prototype.update=n((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,D,[this,e,t,r,n])}),"collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.");Collection.prototype.deleteOne=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new L(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeOne=Collection.prototype.deleteOne;Collection.prototype.deleteMany=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}const n=new M(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.removeMany=Collection.prototype.deleteMany;Collection.prototype.remove=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,R,[this,e,t,r])}),"collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.");Collection.prototype.save=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return C(this.s.topology,k,[this,e,t,r])}),"collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.");Collection.prototype.findOne=o({name:"collection.find",deprecatedOptions:de,optionsIndex:1},(function(e,t,r){if(typeof r==="object"){s("Third parameter to `findOne()` must be a callback or undefined")}if(typeof e==="function")r=e,e={},t={};if(typeof t==="function")r=t,t={};e=e||{};t=t||{};const n=new W(this,e,t);return fe(this.s.topology,n,r)}));Collection.prototype.rename=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t,{readPreference:g.PRIMARY});const n=new ie(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.drop=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new U(this.s.db,this.collectionName,e);return fe(this.s.topology,r,t)};Collection.prototype.options=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new se(this,e);return fe(this.s.topology,r,t)};Collection.prototype.isCapped=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new re(this,e);return fe(this.s.topology,r,t)};Collection.prototype.createIndex=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.createIndexes=function(e,t,r){if(typeof t==="function")r=t,t={};t=t?Object.assign({},t):{};if(typeof t.maxTimeMS!=="number")delete t.maxTimeMS;const n=new _(this,this.collectionName,e,t);return fe(this.s.topology,n,r)};Collection.prototype.dropIndex=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift()||{}:{};t.readPreference=g.PRIMARY;const o=new P(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.dropIndexes=function(e,t){if(typeof e==="function")t=e,e={};e=e?Object.assign({},e):{};if(typeof e.maxTimeMS!=="number")delete e.maxTimeMS;const r=new G(this,e);return fe(this.s.topology,r,t)};Collection.prototype.dropAllIndexes=n(Collection.prototype.dropIndexes,"collection.dropAllIndexes is deprecated. Use dropIndexes instead.");Collection.prototype.reIndex=n((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new ae(this,e);return fe(this.s.topology,r,t)}),"collection.reIndex is deprecated. Use db.command instead.");Collection.prototype.listIndexes=function(e){const t=new b(this.s.topology,new ne(this,e),e);return t};Collection.prototype.ensureIndex=n((function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return C(this.s.topology,w,[this,e,t,r])}),"collection.ensureIndex is deprecated. Use createIndexes instead.");Collection.prototype.indexExists=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new X(this,e,t);return fe(this.s.topology,n,r)};Collection.prototype.indexInformation=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new Z(this.s.db,this.collectionName,e);return fe(this.s.topology,n,t)};Collection.prototype.count=n((function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};if(typeof t==="function")r=t,t={};t=t||{};return fe(this.s.topology,new Y(this,Object.assign({query:e},t)),r)}),"collection.count is deprecated, and will be removed in a future version."+" Use Collection.countDocuments or Collection.estimatedDocumentCount instead");Collection.prototype.estimatedDocumentCount=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new Y(this,e);return fe(this.s.topology,r,t)};Collection.prototype.countDocuments=function(e,t,r){const n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift()||{}:{};t=n.length?n.shift()||{}:{};const o=new O(this,e,t);return fe(this.s.topology,o,r)};Collection.prototype.distinct=function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;const s=o.length?o.shift()||{}:{};const i=o.length?o.shift()||{}:{};const a=new F(this,e,s,i);return fe(this.s.topology,a,n)};Collection.prototype.indexes=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new K(this,e);return fe(this.s.topology,r,t)};Collection.prototype.stats=function(e,t){const r=Array.prototype.slice.call(arguments,0);t=typeof r[r.length-1]==="function"?r.pop():undefined;e=r.length?r.shift()||{}:{};const n=new ce(this,e);return fe(this.s.topology,n,t)};Collection.prototype.findOneAndDelete=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};if(this.s.options.ignoreUndefined){t=Object.assign({},t);t.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new q(this,e,t),r)};Collection.prototype.findOneAndReplace=o({name:"collection.findOneAndReplace",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new j(this,e,t,r),n)}));Collection.prototype.findOneAndUpdate=o({name:"collection.findOneAndUpdate",deprecatedOptions:["returnOriginal"],optionsIndex:2},(function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(this.s.options.ignoreUndefined){r=Object.assign({},r);r.ignoreUndefined=this.s.options.ignoreUndefined}return fe(this.s.topology,new z(this,e,t,r),n)}));Collection.prototype.findAndModify=n(_findAndModify,"collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.");Collection.prototype._findAndModify=_findAndModify;function _findAndModify(e,t,r,n,o){const s=Array.prototype.slice.call(arguments,1);o=typeof s[s.length-1]==="function"?s.pop():undefined;t=s.length?s.shift()||[]:[];r=s.length?s.shift():null;n=s.length?s.shift()||{}:{};n=Object.assign({},n);n.readPreference=g.PRIMARY;return fe(this.s.topology,new J(this,e,t,r,n),o)}Collection.prototype.findAndRemove=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift()||[]:[];r=o.length?o.shift()||{}:{};r.remove=true;return fe(this.s.topology,new J(this,e,t,null,r),n)}),"collection.findAndRemove is deprecated. Use findOneAndDelete instead.");Collection.prototype.aggregate=function(e,t,r){if(Array.isArray(e)){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}}else{const n=Array.prototype.slice.call(arguments,0);r=n.pop();const o=n[n.length-1];t=o&&(o.readPreference||o.explain||o.cursor||o.out||o.maxTimeMS||o.hint||o.allowDiskUse)?n.pop():{};e=n}const n=new Q(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Collection.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Collection.prototype.parallelCollectionScan=n((function(e,t){if(typeof e==="function")t=e,e={numCursors:1};e.numCursors=e.numCursors||1;e.batchSize=e.batchSize||1e3;e=Object.assign({},e);e.readPreference=g.resolve(this,e);e.promiseLibrary=this.s.promiseLibrary;if(e.session){e.session=undefined}return C(this.s.topology,v,[this,e,t],{skipSessions:true})}),"parallelCollectionScan is deprecated in MongoDB v4.1");Collection.prototype.geoHaystackSearch=n((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift()||{}:{};const s=new $(this,e,t,r);return fe(this.s.topology,s,n)}),"geoHaystackSearch is deprecated, and will be removed in a future version.");Collection.prototype.group=n((function(e,t,r,n,o,s,i,a){const A=Array.prototype.slice.call(arguments,3);a=typeof A[A.length-1]==="function"?A.pop():undefined;n=A.length?A.shift():null;o=A.length?A.shift():null;s=A.length?A.shift():null;i=A.length?A.shift()||{}:{};if(!(typeof o==="function")){s=o;o=null}if(!Array.isArray(e)&&e instanceof Object&&typeof e!=="function"&&!(e._bsontype==="Code")){e=Object.keys(e)}if(typeof n==="function"){n=n.toString()}if(typeof o==="function"){o=o.toString()}s=s==null?true:s;return C(this.s.topology,S,[this,e,t,r,n,o,s,i,a])}),"MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.");Collection.prototype.mapReduce=function(e,t,r,n){if("function"===typeof r)n=r,r={};if(null==r.out){throw new Error("the out option parameter must be defined, see mongodb docs for possible values")}if("function"===typeof e){e=e.toString()}if("function"===typeof t){t=t.toString()}if("function"===typeof r.finalize){r.finalize=r.finalize.toString()}const o=new oe(this,e,t,r);return fe(this.s.topology,o,n)};Collection.prototype.initializeUnorderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return p(this.s.topology,this,e)};Collection.prototype.initializeOrderedBulkOp=function(e){e=e||{};if(e.ignoreUndefined==null){e.ignoreUndefined=this.s.options.ignoreUndefined}e.promiseLibrary=this.s.promiseLibrary;return E(this.s.topology,this,e)};Collection.prototype.getLogger=function(){return this.s.db.s.logger};e.exports=Collection},538:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(3994).MongoError;const s=r(7159);const i=r(4847).CursorState;class CommandCursor extends s{constructor(e,t,r,n){super(e,t,r,n)}setReadPreference(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(this.s.state!==i.INIT){throw o.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof n){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new n(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}batchSize(e){if(this.s.state===i.CLOSED||this.isDead()){throw o.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw o.create({message:"batchSize requires an integer",driver:true})}if(this.cmd.cursor){this.cmd.cursor.batchSize=e}this.setCursorBatchSize(e);return this}maxTimeMS(e){if(this.topology.lastIsMaster().minWireVersion>2){this.cmd.maxTimeMS=e}return this}getLogger(){return this.logger}}CommandCursor.prototype.get=CommandCursor.prototype.toArray;e.exports=CommandCursor},7703:(e,t,r)=>{"use strict";const n=r(8988).Msg;const o=r(9814).KillCursor;const s=r(9814).GetMore;const i=r(1371).deepCopy;const a=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const A=new Set(["hello","ismaster","isMaster"]);const c={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"};const l={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldsSelector:"projection"};const u=["tailable","oplogReplay","noCursorTimeout","awaitData","partial","exhaust"];const collectionName=e=>e.ns.split(".")[1];const shouldRedactCommand=(e,t)=>a.has(e)||A.has(e)&&!!t.speculativeAuthenticate;const extractCommand=e=>{let t;if(e instanceof s){t={getMore:i(e.cursorId),collection:collectionName(e),batchSize:e.numberToReturn}}else if(e instanceof o){t={killCursors:collectionName(e),cursors:i(e.cursorIds)}}else if(e instanceof n){t=i(e.command)}else if(e.query&&e.query.$query){let r;if(e.ns==="admin.$cmd"){r=Object.assign({},e.query.$query)}else{r={find:collectionName(e)};Object.keys(c).forEach((t=>{if(typeof e.query[t]!=="undefined")r[c[t]]=i(e.query[t])}))}Object.keys(l).forEach((t=>{if(typeof e[t]!=="undefined")r[l[t]]=i(e[t])}));u.forEach((t=>{if(e[t])r[t]=e[t]}));if(typeof e.pre32Limit!=="undefined"){r.limit=e.pre32Limit}if(e.query.$explain){t={explain:r}}else{t=r}}else{t=i(e.query||e)}const r=Object.keys(t)[0];return{cmd:t,name:r,shouldRedact:shouldRedactCommand(r,t)}};e.exports={extractCommand:extractCommand}},147:e=>{"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"}},557:e=>{"use strict";class AuthContext{constructor(e,t,r){this.connection=e;this.credentials=t;this.options=r}}class AuthProvider{constructor(e){this.bson=e}prepare(e,t,r){r(undefined,e)}auth(e,t){t(new TypeError("`auth` method must be overridden by subclass"))}}e.exports={AuthContext:AuthContext,AuthProvider:AuthProvider}},2192:(e,t,r)=>{"use strict";const n=r(4228);const o=r(7324);const s=r(8728);const i=r(2640);const a=r(864).ScramSHA1;const A=r(864).ScramSHA256;const c=r(8857);function defaultAuthProviders(e){return{"mongodb-aws":new c(e),mongocr:new n(e),x509:new o(e),plain:new s(e),gssapi:new i(e),"scram-sha-1":new a(e),"scram-sha-256":new A(e)}}e.exports={defaultAuthProviders:defaultAuthProviders}},2640:(e,t,r)=>{"use strict";const n=r(7578);const o=r(557).AuthProvider;const s=r(1178).retrieveKerberos;const i=r(3111).MongoError;let a;class GSSAPI extends o{auth(e,t){const r=e.connection;const n=e.credentials;if(n==null)return t(new i("credentials required"));const o=n.username;function externalCommand(e,t){return r.command("$external.$cmd",e,t)}makeKerberosClient(e,((e,r)=>{if(e)return t(e);if(r==null)return t(new i("gssapi client missing"));r.step("",((e,n)=>{if(e)return t(e);externalCommand(saslStart(n),((e,n)=>{if(e)return t(e);const s=n.result;negotiate(r,10,s.payload,((e,n)=>{if(e)return t(e);externalCommand(saslContinue(n,s.conversationId),((e,n)=>{if(e)return t(e);const s=n.result;finalize(r,o,s.payload,((e,r)=>{if(e)return t(e);externalCommand({saslContinue:1,conversationId:s.conversationId,payload:r},((e,r)=>{if(e)return t(e);t(undefined,r)}))}))}))}))}))}))}))}}e.exports=GSSAPI;function makeKerberosClient(e,t){const r=e.options.host;const n=e.options.port;const o=e.credentials;if(!r||!n||!o){return t(new i(`Connection must specify: ${r?"host":""}, ${n?"port":""}, ${o?"host":"credentials"}.`))}if(a==null){try{a=s()}catch(e){return t(e)}}const A=o.username;const c=o.password;const l=o.mechanismProperties;const u=l["gssapiservicename"]||l["gssapiServiceName"]||"mongodb";performGssapiCanonicalizeHostName(r,l,((e,r)=>{if(e)return t(e);const n={};if(c!=null){Object.assign(n,{user:A,password:c})}a.initializeClient(`${u}${process.platform==="win32"?"/":"@"}${r}`,n,((e,r)=>{if(e)return t(new i(e));t(null,r)}))}))}function saslStart(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}function saslContinue(e,t){return{saslContinue:1,conversationId:t,payload:e}}function negotiate(e,t,r,n){e.step(r,((o,s)=>{if(o&&t===0)return n(o);if(o)return negotiate(e,t-1,r,n);n(undefined,s||"")}))}function finalize(e,t,r,n){e.unwrap(r,((r,o)=>{if(r)return n(r);e.wrap(o||"",{user:t},((e,t)=>{if(e)return n(e);n(undefined,t)}))}))}function performGssapiCanonicalizeHostName(e,t,r){const o=typeof t.gssapiCanonicalizeHostName==="boolean"?t.gssapiCanonicalizeHostName:false;if(!o)return r(undefined,e);n.resolveCname(e,((t,n)=>{if(t)return r(t);if(Array.isArray(n)&&n.length>0){return r(undefined,n[0])}r(undefined,e)}))}},2222:e=>{"use strict";function getDefaultAuthMechanism(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 MongoCredentials{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||{};if(/MONGODB-AWS/i.test(this.mechanism)){if(!this.username&&process.env.AWS_ACCESS_KEY_ID){this.username=process.env.AWS_ACCESS_KEY_ID}if(!this.password&&process.env.AWS_SECRET_ACCESS_KEY){this.password=process.env.AWS_SECRET_ACCESS_KEY}if(this.mechanismProperties.AWS_SESSION_TOKEN==null&&process.env.AWS_SESSION_TOKEN!=null){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){if(/DEFAULT/i.test(this.mechanism)){return new MongoCredentials({username:this.username,password:this.password,source:this.source,mechanism:getDefaultAuthMechanism(e),mechanismProperties:this.mechanismProperties})}return this}}e.exports={MongoCredentials:MongoCredentials}},4228:(e,t,r)=>{"use strict";const n=r(6113);const o=r(557).AuthProvider;class MongoCR extends o{auth(e,t){const r=e.connection;const o=e.credentials;const s=o.username;const i=o.password;const a=o.source;r.command(`${a}.$cmd`,{getnonce:1},((e,o)=>{let A=null;let c=null;if(e==null){const e=o.result;A=e.nonce;let t=n.createHash("md5");t.update(s+":mongo:"+i,"utf8");const r=t.digest("hex");t=n.createHash("md5");t.update(A+s+r,"utf8");c=t.digest("hex")}const l={authenticate:1,user:s,nonce:A,key:c};r.command(`${a}.$cmd`,l,t)}))}}e.exports=MongoCR},8857:(e,t,r)=>{"use strict";const n=r(557).AuthProvider;const o=r(2222).MongoCredentials;const s=r(3111).MongoError;const i=r(6113);const a=r(3685);const A=r(1178).maxWireVersion;const c=r(7310);let l;try{l=r(3847)}catch(e){}const u=110;const h="http://169.254.170.2";const d="http://169.254.169.254";const g="/latest/meta-data/iam/security-credentials";class MongoDBAWS extends n{auth(e,t){const r=e.connection;const n=e.credentials;if(A(r)<9){t(new s("MONGODB-AWS authentication requires MongoDB version 4.4 or later"));return}if(l==null){t(new s("MONGODB-AWS authentication requires the `aws4` module, please install it as a dependency of your project"));return}if(n.username==null){makeTempCredentials(n,((r,n)=>{if(r)return t(r);e.credentials=n;this.auth(e,t)}));return}const o=n.source;const a=this.bson;const c=n.username;const h=n.password;const d=n.mechanismProperties.AWS_SESSION_TOKEN;const g=c&&h&&d?{accessKeyId:c,secretAccessKey:h,sessionToken:d}:c&&h?{accessKeyId:c,secretAccessKey:h}:undefined;i.randomBytes(32,((e,n)=>{if(e){t(e);return}const i={saslStart:1,mechanism:"MONGODB-AWS",payload:a.serialize({r:n,p:u})};r.command(`${o}.$cmd`,i,((e,i)=>{if(e)return t(e);const A=i.result;const c=a.deserialize(A.payload.buffer);const u=c.h;const h=c.s.buffer;if(h.length!==64){t(new s(`Invalid server nonce length ${h.length}, expected 64`));return}if(h.compare(n,0,n.length,0,n.length)!==0){t(new s("Server nonce does not begin with client nonce"));return}if(u.length<1||u.length>255||u.indexOf("..")!==-1){t(new s(`Server returned an invalid host: "${u}"`));return}const p="Action=GetCallerIdentity&Version=2011-06-15";const E=l.sign({method:"POST",host:u,region:deriveRegion(c.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":p.length,"X-MongoDB-Server-Nonce":h.toString("base64"),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:p},g);const m=E.headers.Authorization;const C=E.headers["X-Amz-Date"];const I={a:m,d:C};if(d){I.t=d}const y={saslContinue:1,conversationId:1,payload:a.serialize(I)};r.command(`${o}.$cmd`,y,(e=>{if(e)return t(e);t()}))}))}))}}function makeTempCredentials(e,t){function done(r){if(r.AccessKeyId==null||r.SecretAccessKey==null||r.Token==null){t(new s("Could not obtain temporary MONGODB-AWS credentials"));return}t(undefined,new o({username:r.AccessKeyId,password:r.SecretAccessKey,source:e.source,mechanism:"MONGODB-AWS",mechanismProperties:{AWS_SESSION_TOKEN:r.Token}}))}if(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI){request(`${h}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`,undefined,((e,r)=>{if(e)return t(e);done(r)}));return}request(`${d}/latest/api/token`,{method:"PUT",json:false,headers:{"X-aws-ec2-metadata-token-ttl-seconds":30}},((e,r)=>{if(e)return t(e);request(`${d}/${g}`,{json:false,headers:{"X-aws-ec2-metadata-token":r}},((e,n)=>{if(e)return t(e);request(`${d}/${g}/${n}`,{headers:{"X-aws-ec2-metadata-token":r}},((e,r)=>{if(e)return t(e);done(r)}))}))}))}function deriveRegion(e){const t=e.split(".");if(t.length===1||t[1]==="amazonaws"){return"us-east-1"}return t[1]}function request(e,t,r){t=Object.assign({method:"GET",timeout:1e4,json:true},c.parse(e),t);const n=a.request(t,(e=>{e.setEncoding("utf8");let n="";e.on("data",(e=>n+=e));e.on("end",(()=>{if(t.json===false){r(undefined,n);return}try{const e=JSON.parse(n);r(undefined,e)}catch(e){r(new s(`Invalid JSON response: "${n}"`))}}))}));n.on("error",(e=>r(e)));n.end()}e.exports=MongoDBAWS},8728:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(557).AuthProvider;const s=n();const i=s.Binary;class Plain extends o{auth(e,t){const r=e.connection;const n=e.credentials;const o=n.username;const s=n.password;const a=new i(`\0${o}\0${s}`);const A={saslStart:1,mechanism:"PLAIN",payload:a,autoAuthorize:1};r.command("$external.$cmd",A,t)}}e.exports=Plain},864:(e,t,r)=>{"use strict";const n=r(6113);const o=r(1867).Buffer;const s=r(7746).retrieveBSON;const i=r(3111).MongoError;const a=r(557).AuthProvider;const A=r(1371).emitWarning;const c=s();const l=c.Binary;let u;try{u=r(9178)}catch(e){}class ScramSHA extends a{constructor(e,t){super(e);this.cryptoMethod=t||"sha1"}prepare(e,t,r){const o=this.cryptoMethod;if(o==="sha256"&&typeof u!=="function"){A("Warning: no saslprep library specified. Passwords will not be sanitized")}n.randomBytes(24,((n,s)=>{if(n){return r(n)}Object.assign(t,{nonce:s});const i=t.credentials;const a=Object.assign({},e,{speculativeAuthenticate:Object.assign(makeFirstMessage(o,i,s),{db:i.source})});r(undefined,a)}))}auth(e,t){const r=e.response;if(r&&r.speculativeAuthenticate){continueScramConversation(this.cryptoMethod,r.speculativeAuthenticate,e,t);return}executeScram(this.cryptoMethod,e,t)}}function cleanUsername(e){return e.replace("=","=3D").replace(",","=2C")}function clientFirstMessageBare(e,t){return o.concat([o.from("n=","utf8"),o.from(e,"utf8"),o.from(",r=","utf8"),o.from(t.toString("base64"),"utf8")])}function makeFirstMessage(e,t,r){const n=cleanUsername(t.username);const s=e==="sha1"?"SCRAM-SHA-1":"SCRAM-SHA-256";return{saslStart:1,mechanism:s,payload:new l(o.concat([o.from("n,,","utf8"),clientFirstMessageBare(n,r)])),autoAuthorize:1,options:{skipEmptyExchange:true}}}function executeScram(e,t,r){const n=t.connection;const o=t.credentials;const s=t.nonce;const i=o.source;const a=makeFirstMessage(e,o,s);n.command(`${i}.$cmd`,a,((n,o)=>{const s=resolveError(n,o);if(s){return r(s)}continueScramConversation(e,o.result,t,r)}))}function continueScramConversation(e,t,r,n){const s=r.connection;const a=r.credentials;const A=r.nonce;const c=a.source;const h=cleanUsername(a.username);const d=a.password;let g;if(e==="sha256"){g=typeof u==="function"?u(d):d}else{try{g=passwordDigest(h,d)}catch(e){return n(e)}}const p=o.isBuffer(t.payload)?new l(t.payload):t.payload;const E=parsePayload(p.value());const m=parseInt(E.i,10);if(m&&m<4096){n(new i(`Server returned an invalid iteration count ${m}`),false);return}const C=E.s;const I=E.r;if(I.startsWith("nonce")){n(new i(`Server returned an invalid nonce: ${I}`),false);return}const y=`c=biws,r=${I}`;const B=HI(g,o.from(C,"base64"),m,e);const Q=HMAC(e,B,"Client Key");const b=HMAC(e,B,"Server Key");const w=H(e,Q);const S=[clientFirstMessageBare(h,A),p.value().toString("base64"),y].join(",");const v=HMAC(e,w,S);const R=`p=${xor(Q,v)}`;const k=[y,R].join(",");const D=HMAC(e,b,S);const N={saslContinue:1,conversationId:t.conversationId,payload:new l(o.from(k))};s.command(`${c}.$cmd`,N,((e,t)=>{const r=resolveError(e,t);if(r){return n(r)}const a=t.result;const A=parsePayload(a.payload.value());if(!compareDigest(o.from(A.v,"base64"),D)){n(new i("Server returned an invalid signature"));return}if(!a||a.done!==false){return n(r,a)}const l={saslContinue:1,conversationId:a.conversationId,payload:o.alloc(0)};s.command(`${c}.$cmd`,l,n)}))}function parsePayload(e){const t={};const r=e.split(",");for(let e=0;e=200){_hiCachePurge()}h[s]=i;d+=1;return i}function compareDigest(e,t){if(e.length!==t.length){return false}if(typeof n.timingSafeEqual==="function"){return n.timingSafeEqual(e,t)}let r=0;for(let n=0;n{"use strict";const n=r(557).AuthProvider;class X509 extends n{prepare(e,t,r){const n=t.credentials;Object.assign(e,{speculativeAuthenticate:x509AuthenticateCommand(n)});r(undefined,e)}auth(e,t){const r=e.connection;const n=e.credentials;const o=e.response;if(o.speculativeAuthenticate){return t()}r.command("$external.$cmd",x509AuthenticateCommand(n),t)}}function x509AuthenticateCommand(e){const t={authenticate:1,mechanism:"MONGODB-X509"};if(e.username){Object.assign(t,{user:e.username})}return t}e.exports=X509},9815:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(9814).GetMore;const s=r(1371).calculateDurationInMs;const i=r(7703).extractCommand;const namespace=e=>e.ns;const databaseName=e=>e.ns.split(".")[0];const generateConnectionId=e=>e.options?`${e.options.host}:${e.options.port}`:e.address;const isLegacyPool=e=>e.s&&e.queue;const extractReply=(e,t)=>{if(e instanceof o){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),nextBatch:t.message.documents}}}if(e instanceof n){return{ok:1,cursorsUnknown:e.cursorIds}}if(e.query&&typeof e.query.$query!=="undefined"){return{ok:1,cursor:{id:t.message.cursorId,ns:namespace(e),firstBatch:t.message.documents}}}return t&&t.result?t.result:t};const extractConnectionDetails=e=>{if(isLegacyPool(e)){return{connectionId:generateConnectionId(e)}}const t=e;return{address:t.address,connectionId:t.id}};class CommandStartedEvent{constructor(e,t){const r=i(t);const n=r.name;const o=extractConnectionDetails(e);Object.assign(this,o,{requestId:t.requestId,databaseName:databaseName(t),commandName:n,command:r.shouldRedact?{}:r.cmd})}}class CommandSucceededEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),reply:o.shouldRedact?{}:extractReply(t,r)})}}class CommandFailedEvent{constructor(e,t,r,n){const o=i(t);const a=o.name;const A=extractConnectionDetails(e);Object.assign(this,A,{requestId:t.requestId,commandName:a,duration:s(n),failure:o.shouldRedact?{}:r})}}e.exports={CommandStartedEvent:CommandStartedEvent,CommandSucceededEvent:CommandSucceededEvent,CommandFailedEvent:CommandFailedEvent}},2337:e=>{"use strict";var CommandResult=function(e,t,r){this.result=e;this.connection=t;this.message=r};CommandResult.prototype.toJSON=function(){let e=Object.assign({},this,this.result);delete e.message;return e};CommandResult.prototype.toString=function(){return JSON.stringify(this.toJSON())};e.exports=CommandResult},9814:(e,t,r)=>{"use strict";var n=r(7746).retrieveBSON;var o=n();var s=o.Long;const i=r(1867).Buffer;var a=0;var A=r(7272).opcodes;var c=2;var l=4;var u=8;var h=16;var d=32;var g=64;var p=128;var E=1;var m=2;var C=4;var I=8;var Query=function(e,t,r,n){var o=this;if(t==null)throw new Error("ns must be specified for query");if(r==null)throw new Error("query must be specified for query");if(t.indexOf("\0")!==-1){throw new Error("namespace cannot contain a null character")}this.bson=e;this.ns=t;this.query=r;this.numberToSkip=n.numberToSkip||0;this.numberToReturn=n.numberToReturn||0;this.returnFieldSelector=n.returnFieldSelector||null;this.requestId=Query.getRequestId();this.pre32Limit=n.pre32Limit;this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:true;this.batchSize=o.numberToReturn;this.tailable=false;this.slaveOk=typeof n.slaveOk==="boolean"?n.slaveOk:false;this.oplogReplay=false;this.noCursorTimeout=false;this.awaitData=false;this.exhaust=false;this.partial=false};Query.prototype.incRequestId=function(){this.requestId=a++};Query.nextRequestId=function(){return a+1};Query.prototype.toBin=function(){var e=this;var t=[];var r=null;var n=0;if(this.tailable){n|=c}if(this.slaveOk){n|=l}if(this.oplogReplay){n|=u}if(this.noCursorTimeout){n|=h}if(this.awaitData){n|=d}if(this.exhaust){n|=g}if(this.partial){n|=p}if(e.batchSize!==e.numberToReturn)e.numberToReturn=e.batchSize;var o=i.alloc(4*4+4+i.byteLength(e.ns)+1+4+4);t.push(o);var s=e.bson.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(s);if(e.returnFieldSelector&&Object.keys(e.returnFieldSelector).length>0){r=e.bson.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});t.push(r)}var a=o.length+s.length+(r?r.length:0);var E=4;o[3]=a>>24&255;o[2]=a>>16&255;o[1]=a>>8&255;o[0]=a&255;o[E+3]=this.requestId>>24&255;o[E+2]=this.requestId>>16&255;o[E+1]=this.requestId>>8&255;o[E]=this.requestId&255;E=E+4;o[E+3]=0>>24&255;o[E+2]=0>>16&255;o[E+1]=0>>8&255;o[E]=0&255;E=E+4;o[E+3]=A.OP_QUERY>>24&255;o[E+2]=A.OP_QUERY>>16&255;o[E+1]=A.OP_QUERY>>8&255;o[E]=A.OP_QUERY&255;E=E+4;o[E+3]=n>>24&255;o[E+2]=n>>16&255;o[E+1]=n>>8&255;o[E]=n&255;E=E+4;E=E+o.write(this.ns,E,"utf8")+1;o[E-1]=0;o[E+3]=this.numberToSkip>>24&255;o[E+2]=this.numberToSkip>>16&255;o[E+1]=this.numberToSkip>>8&255;o[E]=this.numberToSkip&255;E=E+4;o[E+3]=this.numberToReturn>>24&255;o[E+2]=this.numberToReturn>>16&255;o[E+1]=this.numberToReturn>>8&255;o[E]=this.numberToReturn&255;E=E+4;return t};Query.getRequestId=function(){return++a};var GetMore=function(e,t,r,n){n=n||{};this.numberToReturn=n.numberToReturn||0;this.requestId=a++;this.bson=e;this.ns=t;this.cursorId=r};GetMore.prototype.toBin=function(){var e=4+i.byteLength(this.ns)+1+4+8+4*4;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_GETMORE>>24&255;r[t+2]=A.OP_GETMORE>>16&255;r[t+1]=A.OP_GETMORE>>8&255;r[t]=A.OP_GETMORE&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;t=t+r.write(this.ns,t,"utf8")+1;r[t-1]=0;r[t+3]=this.numberToReturn>>24&255;r[t+2]=this.numberToReturn>>16&255;r[t+1]=this.numberToReturn>>8&255;r[t]=this.numberToReturn&255;t=t+4;r[t+3]=this.cursorId.getLowBits()>>24&255;r[t+2]=this.cursorId.getLowBits()>>16&255;r[t+1]=this.cursorId.getLowBits()>>8&255;r[t]=this.cursorId.getLowBits()&255;t=t+4;r[t+3]=this.cursorId.getHighBits()>>24&255;r[t+2]=this.cursorId.getHighBits()>>16&255;r[t+1]=this.cursorId.getHighBits()>>8&255;r[t]=this.cursorId.getHighBits()&255;t=t+4;return r};var KillCursor=function(e,t,r){this.ns=t;this.requestId=a++;this.cursorIds=r};KillCursor.prototype.toBin=function(){var e=4+4+4*4+this.cursorIds.length*8;var t=0;var r=i.alloc(e);r[t+3]=e>>24&255;r[t+2]=e>>16&255;r[t+1]=e>>8&255;r[t]=e&255;t=t+4;r[t+3]=this.requestId>>24&255;r[t+2]=this.requestId>>16&255;r[t+1]=this.requestId>>8&255;r[t]=this.requestId&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=A.OP_KILL_CURSORS>>24&255;r[t+2]=A.OP_KILL_CURSORS>>16&255;r[t+1]=A.OP_KILL_CURSORS>>8&255;r[t]=A.OP_KILL_CURSORS&255;t=t+4;r[t+3]=0>>24&255;r[t+2]=0>>16&255;r[t+1]=0>>8&255;r[t]=0&255;t=t+4;r[t+3]=this.cursorIds.length>>24&255;r[t+2]=this.cursorIds.length>>16&255;r[t+1]=this.cursorIds.length>>8&255;r[t]=this.cursorIds.length&255;t=t+4;for(var n=0;n>24&255;r[t+2]=this.cursorIds[n].getLowBits()>>16&255;r[t+1]=this.cursorIds[n].getLowBits()>>8&255;r[t]=this.cursorIds[n].getLowBits()&255;t=t+4;r[t+3]=this.cursorIds[n].getHighBits()>>24&255;r[t+2]=this.cursorIds[n].getHighBits()>>16&255;r[t+1]=this.cursorIds[n].getHighBits()>>8&255;r[t]=this.cursorIds[n].getHighBits()&255;t=t+4}return r};var Response=function(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.cursorId=new s(n.readInt32LE(4),n.readInt32LE(8));this.startingFrom=n.readInt32LE(12);this.numberReturned=n.readInt32LE(16);this.documents=new Array(this.numberReturned);this.cursorNotFound=(this.responseFlags&E)!==0;this.queryFailure=(this.responseFlags&m)!==0;this.shardConfigStale=(this.responseFlags&C)!==0;this.awaitCapable=(this.responseFlags&I)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false};Response.prototype.isParsed=function(){return this.parsed};Response.prototype.parse=function(e){if(this.parsed)return;e=e||{};var t=e.raw||false;var r=e.documentsReturnedIn||null;var n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;var o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;var s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;var i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;var a,A;A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};this.index=20;for(var c=0;c{"use strict";const n=r(1808);const o=r(4404);const s=r(6096);const i=r(3111).MongoError;const a=r(3111).MongoNetworkError;const A=r(3111).MongoNetworkTimeoutError;const c=r(2192).defaultAuthProviders;const l=r(557).AuthContext;const u=r(7161);const h=r(1178).makeClientMetadata;const d=u.MAX_SUPPORTED_WIRE_VERSION;const g=u.MAX_SUPPORTED_SERVER_VERSION;const p=u.MIN_SUPPORTED_WIRE_VERSION;const E=u.MIN_SUPPORTED_SERVER_VERSION;let m;function connect(e,t,r){if(typeof t==="function"){r=t;t=undefined}const n=e&&e.connectionType?e.connectionType:s;if(m==null){m=c(e.bson)}const o=e.family!==void 0?e.family:0;makeConnection(o,e,t,((t,o)=>{if(t){r(t,o);return}performInitialHandshake(new n(o,e),e,r)}))}function isModernConnectionType(e){return!(e instanceof s)}function checkSupportedServer(e,t){const r=e&&typeof e.maxWireVersion==="number"&&e.maxWireVersion>=p;const n=e&&typeof e.minWireVersion==="number"&&e.minWireVersion<=d;if(r){if(n){return null}const r=`Server at ${t.host}:${t.port} reports minimum wire version ${e.minWireVersion}, but this version of the Node.js Driver requires at most ${d} (MongoDB ${g})`;return new i(r)}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 ${p} (MongoDB ${E})`;return new i(o)}function performInitialHandshake(e,t,r){const callback=function(t,n){if(t&&e){e.destroy()}r(t,n)};const n=t.credentials;if(n){if(!n.mechanism.match(/DEFAULT/i)&&!m[n.mechanism]){callback(new i(`authMechanism '${n.mechanism}' not supported`));return}}const o=new l(e,n,t);prepareHandshakeDocument(o,((r,s)=>{if(r){return callback(r)}const a=Object.assign({},t);if(t.connectTimeoutMS||t.connectionTimeout){a.socketTimeout=t.connectTimeoutMS||t.connectionTimeout}s.helloOk=!!t.useUnifiedTopology;const A=(new Date).getTime();e.command("admin.$cmd",s,a,((r,a)=>{if(r){callback(r);return}const c=a.result;if(c.ok===0){callback(new i(c));return}if("isWritablePrimary"in c){c.ismaster=c.isWritablePrimary}if(t.useUnifiedTopology&&c.helloOk){e.helloOk=true}const l=checkSupportedServer(c,t);if(l){callback(l);return}if(!isModernConnectionType(e)){if(c.compression){const r=s.compression.filter((e=>c.compression.indexOf(e)!==-1));if(r.length){e.agreedCompressor=r[0]}if(t.compression&&t.compression.zlibCompressionLevel){e.zlibCompressionLevel=t.compression.zlibCompressionLevel}}}e.ismaster=c;e.lastIsMasterMS=(new Date).getTime()-A;if(!c.arbiterOnly&&n){Object.assign(o,{response:c});const t=n.resolveAuthMechanism(c);const r=m[t.mechanism];r.auth(o,(t=>{if(t)return callback(t);callback(undefined,e)}));return}callback(undefined,e)}))}))}function prepareHandshakeDocument(e,t){const r=e.options;const n=e.connection.serverApi;const o=r.compression&&r.compression.compressors?r.compression.compressors:[];const s={[n?"hello":"ismaster"]:true,client:r.metadata||h(r),compression:o};const a=e.credentials;if(a){if(a.mechanism.match(/DEFAULT/i)&&a.username){Object.assign(s,{saslSupportedMechs:`${a.source}.${a.username}`});m["scram-sha-256"].prepare(s,e,t);return}const r=m[a.mechanism];if(r==null){return t(new i(`No AuthProvider for ${a.mechanism} defined.`))}r.prepare(s,e,t);return}t(undefined,s)}const C=["pfx","key","passphrase","cert","ca","ciphers","NPNProtocols","ALPNProtocols","servername","ecdhCurve","secureProtocol","secureContext","session","minDHSize","crl","rejectUnauthorized"];function parseConnectOptions(e,t){const r=typeof t.host==="string"?t.host:"localhost";if(r.indexOf("/")!==-1){return{path:r}}const n={family:e,host:r,port:typeof t.port==="number"?t.port:27017,rejectUnauthorized:false};return n}function parseSslOptions(e,t){const r=parseConnectOptions(e,t);for(const e in t){if(t[e]!=null&&C.indexOf(e)!==-1){r[e]=t[e]}}if(t.checkServerIdentity===false){r.checkServerIdentity=function(){return undefined}}else if(typeof t.checkServerIdentity==="function"){r.checkServerIdentity=t.checkServerIdentity}if(r.servername==null&&!n.isIP(r.host)){r.servername=r.host}return r}const I=new Set(["error","close","timeout","parseError"]);function makeConnection(e,t,r,s){const i=typeof t.ssl==="boolean"?t.ssl:false;const a=typeof t.keepAlive==="boolean"?t.keepAlive:true;let A=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;const c=typeof t.noDelay==="boolean"?t.noDelay:true;const l=typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:3e4;const u=typeof t.socketTimeoutMS==="number"?t.socketTimeoutMS:typeof t.socketTimeout==="number"?t.socketTimeout:0;const h=typeof t.rejectUnauthorized==="boolean"?t.rejectUnauthorized:true;if(A>u){A=Math.round(u/2)}let d;const callback=function(e,t){if(e&&d){d.destroy()}s(e,t)};try{if(i){d=o.connect(parseSslOptions(e,t));if(typeof d.disableRenegotiation==="function"){d.disableRenegotiation()}}else{d=n.createConnection(parseConnectOptions(e,t))}}catch(e){return callback(e)}d.setKeepAlive(a,A);d.setTimeout(l);d.setNoDelay(c);const g=i?"secureConnect":"connect";let p;function errorHandler(e){return t=>{I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}d.removeListener(g,connectHandler);callback(connectionFailureError(e,t))}}function connectHandler(){I.forEach((e=>d.removeAllListeners(e)));if(p){r.removeListener("cancel",p)}if(d.authorizationError&&h){return callback(d.authorizationError)}d.setTimeout(u);callback(null,d)}I.forEach((e=>d.once(e,errorHandler(e))));if(r){p=errorHandler("cancel");r.once("cancel",p)}d.once(g,connectHandler)}function connectionFailureError(e,t){switch(e){case"error":return new a(t);case"timeout":return new A(`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.exports=connect},6096:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(6113);const s=r(7746).debugOptions;const i=r(7272).parseHeader;const a=r(7793).decompress;const A=r(9814).Response;const c=r(8988).BinMsg;const l=r(3111).MongoNetworkError;const u=r(3111).MongoNetworkTimeoutError;const h=r(3111).MongoError;const d=r(104);const g=r(7272).opcodes.OP_COMPRESSED;const p=r(7272).opcodes.OP_MSG;const E=r(7272).MESSAGE_HEADER_SIZE;const m=r(1867).Buffer;const C=r(9814).Query;const I=r(2337);let y=0;const B=1024*1024*16*4;const Q=["host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","socketTimeout","ssl","ca","crl","cert","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","checkServerIdentity"];let b=undefined;let w=false;let S={};class Connection extends n{constructor(e,t){super();t=t||{};if(!t.bson){throw new TypeError("must pass in valid bson parser")}this.id=y++;this.options=t;this.logger=d("Connection",t);this.bson=t.bson;this.tag=t.tag;this.maxBsonMessageSize=t.maxBsonMessageSize||B;this.helloOk=undefined;this.port=t.port||27017;this.host=t.host||"localhost";this.socketTimeout=typeof t.socketTimeout==="number"?t.socketTimeout:0;this.keepAlive=typeof t.keepAlive==="boolean"?t.keepAlive:true;this.keepAliveInitialDelay=typeof t.keepAliveInitialDelay==="number"?t.keepAliveInitialDelay:12e4;this.connectionTimeout=typeof t.connectionTimeout==="number"?t.connectionTimeout:3e4;if(this.keepAliveInitialDelay>this.socketTimeout){this.keepAliveInitialDelay=Math.round(this.socketTimeout/2)}if(this.logger.isDebug()){this.logger.debug(`creating connection ${this.id} with options [${JSON.stringify(s(Q,t))}]`)}this.responseOptions={promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false};this.flushing=false;this.queue=[];this.writeStream=null;this.destroyed=false;this.timedOut=false;const r=o.createHash("sha1");r.update(this.address);this.hashedName=r.digest("hex");this.workItems=[];this.socket=e;this.socket.once("error",errorHandler(this));this.socket.once("timeout",timeoutHandler(this));this.socket.once("close",closeHandler(this));this.socket.on("data",dataHandler(this));if(w){addConnection(this.id,this)}}setSocketTimeout(e){if(this.socket){this.socket.setTimeout(e)}}resetSocketTimeout(){if(this.socket){this.socket.setTimeout(this.socketTimeout)}}static enableConnectionAccounting(e){if(e){b=e}w=true;S={}}static disableConnectionAccounting(){w=false;b=undefined}static connections(){return S}get address(){return`${this.host}:${this.port}`}unref(){if(this.socket==null){this.once("connect",(()=>this.socket.unref()));return}this.socket.unref()}flush(e){while(this.workItems.length>0){const t=this.workItems.shift();if(t.cb){t.cb(e)}}}destroy(e,t){if(typeof e==="function"){t=e;e={}}e=Object.assign({force:false},e);if(w){deleteConnection(this.id)}if(this.socket==null){this.destroyed=true;return}if(e.force||this.timedOut){this.socket.destroy();this.destroyed=true;if(typeof t==="function")t(null,null);return}this.socket.end((e=>{this.destroyed=true;if(typeof t==="function")t(e,null)}))}write(e){if(this.logger.isDebug()){if(!Array.isArray(e)){this.logger.debug(`writing buffer [ ${e.length} ] to ${this.address}`)}else{for(let t=0;t{};function _callback(e,t){n(e,t);n=noop}function errorHandler(e){o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);if(e==null){e=new h(`runCommand failed for connection to '${o.address}'`)}o.on("error",noop);_callback(e)}function messageHandler(e){if(e.responseTo!==a.requestId){return}o.resetSocketTimeout();v.forEach((e=>o.removeListener(e,errorHandler)));o.removeListener("message",messageHandler);e.parse({promoteValues:true});const t=e.documents[0];if(t.ok===0||t.$err||t.errmsg||t.code){_callback(new h(t));return}_callback(undefined,new I(t,this,e))}o.setSocketTimeout(s);v.forEach((e=>o.once(e,errorHandler)));o.on("message",messageHandler);o.write(a.toBin())}}const v=["error","close","timeout","parseError"];function deleteConnection(e){delete S[e];if(b){b.deleteConnection(e)}}function addConnection(e,t){S[e]=t;if(b){b.addConnection(e,t)}}function errorHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] errored out with [${JSON.stringify(t)}]`)}e.emit("error",new l(t),e)}}function timeoutHandler(e){return function(){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} for [${e.address}] timed out`)}e.timedOut=true;e.emit("timeout",new u(`connection ${e.id} to ${e.address} timed out`,{beforeHandshake:e.ismaster==null}),e)}}function closeHandler(e){return function(t){if(w)deleteConnection(e.id);if(e.logger.isDebug()){e.logger.debug(`connection ${e.id} with for [${e.address}] closed`)}if(!t){e.emit("close",new l(`connection ${e.id} to ${e.address} closed`),e)}}}function processMessage(e,t){const r=i(t);if(r.opCode!==g){const n=r.opCode===p?c:A;e.emit("message",new n(e.bson,t,r,t.slice(E),e.responseOptions),e);return}r.fromCompressed=true;let n=E;r.opCode=t.readInt32LE(n);n+=4;r.length=t.readInt32LE(n);n+=4;const o=t[n];n++;a(o,t.slice(n),((n,o)=>{if(n){e.emit("error",n);return}if(o.length!==r.length){e.emit("error",new h("Decompressing a compressed message from the server failed. The message is corrupt."));return}const s=r.opCode===p?c:A;e.emit("message",new s(e.bson,t,r,o,e.responseOptions),e)}))}function dataHandler(e){return function(t){while(t.length>0){if(e.bytesRead>0&&e.sizeOfMessage>0){const r=e.sizeOfMessage-e.bytesRead;if(r>t.length){t.copy(e.buffer,e.bytesRead);e.bytesRead=e.bytesRead+t.length;t=m.alloc(0)}else{t.copy(e.buffer,e.bytesRead,0,r);t=t.slice(r);const n=e.buffer;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;processMessage(e,n)}}else{if(e.stubBuffer!=null&&e.stubBuffer.length>0){if(e.stubBuffer.length+t.length>4){const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=r;e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null}else{const r=m.alloc(e.stubBuffer.length+t.length);e.stubBuffer.copy(r,0);t.copy(r,e.stubBuffer.length);t=m.alloc(0)}}else{if(t.length>4){const r=t[0]|t[1]<<8|t[2]<<16|t[3]<<24;if(r<0||r>e.maxBsonMessageSize){const t={err:"socketHandler",trace:"",bin:e.buffer,parseState:{sizeOfMessage:r,bytesRead:e.bytesRead,stubBuffer:e.stubBuffer}};e.emit("parseError",t,e);return}if(r>4&&rt.length){e.buffer=m.alloc(r);t.copy(e.buffer,0);e.bytesRead=t.length;e.sizeOfMessage=r;e.stubBuffer=null;t=m.alloc(0)}else if(r>4&&re.maxBsonMessageSize){const n={err:"socketHandler",trace:null,bin:t,parseState:{sizeOfMessage:r,bytesRead:0,buffer:null,stubBuffer:null}};e.emit("parseError",n,e);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=m.alloc(0)}else{const n=t.slice(0,r);e.buffer=null;e.sizeOfMessage=0;e.bytesRead=0;e.stubBuffer=null;t=t.slice(r);processMessage(e,n)}}else{e.stubBuffer=m.alloc(t.length);t.copy(e.stubBuffer,0);t=m.alloc(0)}}}}}}e.exports=Connection},104:(e,t,r)=>{"use strict";var n=r(3837).format,o=r(3111).MongoError;var s={};var i={};var a=null;var A=process.pid;var c=null;var Logger=function(e,t){if(!(this instanceof Logger))return new Logger(e,t);t=t||{};this.className=e;if(t.logger){c=t.logger}else if(c==null){c=console.log}if(t.loggerLevel){a=t.loggerLevel||"error"}if(i[this.className]==null)s[this.className]=true};Logger.prototype.debug=function(e,t){if(this.isDebug()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","DEBUG",this.className,A,r,e);var a={type:"debug",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}};Logger.prototype.warn=function(e,t){if(this.isWarn()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","WARN",this.className,A,r,e);var a={type:"warn",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.info=function(e,t){if(this.isInfo()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","INFO",this.className,A,r,e);var a={type:"info",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.error=function(e,t){if(this.isError()&&(Object.keys(i).length>0&&i[this.className]||Object.keys(i).length===0&&s[this.className])){var r=(new Date).getTime();var o=n("[%s-%s:%s] %s %s","ERROR",this.className,A,r,e);var a={type:"error",message:e,className:this.className,pid:A,date:r};if(t)a.meta=t;c(o,a)}},Logger.prototype.isInfo=function(){return a==="info"||a==="debug"},Logger.prototype.isError=function(){return a==="error"||a==="info"||a==="debug"},Logger.prototype.isWarn=function(){return a==="error"||a==="warn"||a==="info"||a==="debug"},Logger.prototype.isDebug=function(){return a==="debug"};Logger.reset=function(){a="error";i={}};Logger.currentLogger=function(){return c};Logger.setCurrentLogger=function(e){if(typeof e!=="function")throw new o("current logger must be a function");c=e};Logger.filter=function(e,t){if(e==="class"&&Array.isArray(t)){i={};t.forEach((function(e){i[e]=true}))}};Logger.setLevel=function(e){if(e!=="info"&&e!=="error"&&e!=="debug"&&e!=="warn"){throw new Error(n("%s is an illegal logging level",e))}a=e};e.exports=Logger},8988:(e,t,r)=>{"use strict";const n=r(1867).Buffer;const o=r(7272).opcodes;const s=r(7272).databaseNamespace;const i=r(4485);const a=r(3111).MongoError;let A=0;const c=1;const l=2;const u=1<<16;class Msg{constructor(e,t,r,n){if(r==null)throw new Error("query must be specified for query");this.bson=e;this.ns=t;this.command=r;this.command.$db=s(t);if(n.readPreference&&n.readPreference.mode!==i.PRIMARY){this.command.$readPreference=n.readPreference.toJSON()}this.options=n||{};this.requestId=n.requestId?n.requestId:Msg.getRequestId();this.serializeFunctions=typeof n.serializeFunctions==="boolean"?n.serializeFunctions:false;this.ignoreUndefined=typeof n.ignoreUndefined==="boolean"?n.ignoreUndefined:false;this.checkKeys=typeof n.checkKeys==="boolean"?n.checkKeys:false;this.maxBsonSize=n.maxBsonSize||1024*1024*16;this.checksumPresent=false;this.moreToCome=n.moreToCome||false;this.exhaustAllowed=typeof n.exhaustAllowed==="boolean"?n.exhaustAllowed:false}toBin(){const e=[];let t=0;if(this.checksumPresent){t|=c}if(this.moreToCome){t|=l}if(this.exhaustAllowed){t|=u}const r=n.alloc(4*4+4);e.push(r);let s=r.length;const i=this.command;s+=this.makeDocumentSegment(e,i);r.writeInt32LE(s,0);r.writeInt32LE(this.requestId,4);r.writeInt32LE(0,8);r.writeInt32LE(o.OP_MSG,12);r.writeUInt32LE(t,16);return e}makeDocumentSegment(e,t){const r=n.alloc(1);r[0]=0;const o=this.serializeBson(t);e.push(r);e.push(o);return r.length+o.length}serializeBson(e){return this.bson.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}}Msg.getRequestId=function(){A=A+1&2147483647;return A};class BinMsg{constructor(e,t,r,n,o){o=o||{promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false};this.parsed=false;this.raw=t;this.data=n;this.bson=e;this.opts=o;this.length=r.length;this.requestId=r.requestId;this.responseTo=r.responseTo;this.opCode=r.opCode;this.fromCompressed=r.fromCompressed;this.responseFlags=n.readInt32LE(0);this.checksumPresent=(this.responseFlags&c)!==0;this.moreToCome=(this.responseFlags&l)!==0;this.exhaustAllowed=(this.responseFlags&u)!==0;this.promoteLongs=typeof o.promoteLongs==="boolean"?o.promoteLongs:true;this.promoteValues=typeof o.promoteValues==="boolean"?o.promoteValues:true;this.promoteBuffers=typeof o.promoteBuffers==="boolean"?o.promoteBuffers:false;this.bsonRegExp=typeof o.bsonRegExp==="boolean"?o.bsonRegExp:false;this.documents=[]}isParsed(){return this.parsed}parse(e){if(this.parsed)return;e=e||{};this.index=4;const t=e.raw||false;const r=e.documentsReturnedIn||null;const n=typeof e.promoteLongs==="boolean"?e.promoteLongs:this.opts.promoteLongs;const o=typeof e.promoteValues==="boolean"?e.promoteValues:this.opts.promoteValues;const s=typeof e.promoteBuffers==="boolean"?e.promoteBuffers:this.opts.promoteBuffers;const i=typeof e.bsonRegExp==="boolean"?e.bsonRegExp:this.opts.bsonRegExp;const A={promoteLongs:n,promoteValues:o,promoteBuffers:s,bsonRegExp:i};while(this.index{"use strict";const n=r(3837).inherits;const o=r(2361).EventEmitter;const s=r(3111).MongoError;const i=r(3111).MongoTimeoutError;const a=r(3111).MongoWriteConcernError;const A=r(104);const c=r(3837).format;const l=r(8988).Msg;const u=r(2337);const h=r(7272).MESSAGE_HEADER_SIZE;const d=r(7272).COMPRESSION_DETAILS_SIZE;const g=r(7272).opcodes;const p=r(7793).compress;const E=r(7793).compressorIDs;const m=r(7793).uncompressibleCommands;const C=r(9815);const I=r(1867).Buffer;const y=r(6573);const B=r(5474).updateSessionFromResponse;const Q=r(1178).eachAsync;const b=r(1178).makeStateMachine;const w=r(1371).now;const S="disconnected";const v="connecting";const R="connected";const k="draining";const D="destroying";const N="destroyed";const T=b({[S]:[v,k,S],[v]:[v,R,k,S],[R]:[R,S,k],[k]:[k,D,N],[D]:[D,N],[N]:[N]});const O=new Set(["error","close","timeout","parseError","connect","message"]);var _=0;var Pool=function(e,t){o.call(this);this.topology=e;this.s={state:S,cancellationToken:new o};this.s.cancellationToken.setMaxListeners(Infinity);this.options=Object.assign({host:"localhost",port:27017,size:5,minSize:0,connectionTimeout:3e4,socketTimeout:0,keepAlive:true,keepAliveInitialDelay:12e4,noDelay:true,ssl:false,checkServerIdentity:true,ca:null,crl:null,cert:null,key:null,passphrase:null,rejectUnauthorized:false,promoteLongs:true,promoteValues:true,promoteBuffers:false,bsonRegExp:false,reconnect:true,reconnectInterval:1e3,reconnectTries:30,domainsEnabled:false,legacyCompatMode:true},t);this.id=_++;this.retriesLeft=this.options.reconnectTries;this.reconnectId=null;this.reconnectError=null;if(!t.bson||t.bson&&(typeof t.bson.serialize!=="function"||typeof t.bson.deserialize!=="function")){throw new Error("must pass in valid bson parser")}this.logger=A("Pool",t);this.availableConnections=[];this.inUseConnections=[];this.connectingConnections=0;this.executing=false;this.queue=[];this.numberOfConsecutiveTimeouts=0;this.connectionIndex=0;const r=this;this._messageHandler=messageHandler(this);this._connectionCloseHandler=function(e){const t=this;connectionFailureHandler(r,"close",e,t)};this._connectionErrorHandler=function(e){const t=this;connectionFailureHandler(r,"error",e,t)};this._connectionTimeoutHandler=function(e){const t=this;connectionFailureHandler(r,"timeout",e,t)};this._connectionParseErrorHandler=function(e){const t=this;connectionFailureHandler(r,"parseError",e,t)}};n(Pool,o);Object.defineProperty(Pool.prototype,"size",{enumerable:true,get:function(){return this.options.size}});Object.defineProperty(Pool.prototype,"minSize",{enumerable:true,get:function(){return this.options.minSize}});Object.defineProperty(Pool.prototype,"connectionTimeout",{enumerable:true,get:function(){return this.options.connectionTimeout}});Object.defineProperty(Pool.prototype,"socketTimeout",{enumerable:true,get:function(){return this.options.socketTimeout}});Object.defineProperty(Pool.prototype,"state",{enumerable:true,get:function(){return this.s.state}});function resetPoolState(e){e.inUseConnections=[];e.availableConnections=[];e.connectingConnections=0;e.executing=false;e.numberOfConsecutiveTimeouts=0;e.connectionIndex=0;e.retriesLeft=e.options.reconnectTries;e.reconnectId=null}function connectionFailureHandler(e,t,r,n){if(n){if(n._connectionFailHandled){return}n._connectionFailHandled=true;n.destroy();removeConnection(e,n);n.flush(r)}if(t==="timeout"){e.numberOfConsecutiveTimeouts=e.numberOfConsecutiveTimeouts+1;if(e.numberOfConsecutiveTimeouts>e.options.reconnectTries){e.numberOfConsecutiveTimeouts=0;e.destroy(true);return e.emit("close",e)}}if(e.socketCount()===0){if(e.state!==N&&e.state!==D&&e.state!==k){if(e.options.reconnect){T(e,S)}}t=t==="error"?"close":t;e.emit(t,r)}if(!e.reconnectId&&e.options.reconnect){e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e),e.options.reconnectInterval)}const o=totalConnectionCount(e);if(o{if(r==null){e.reconnectId=null;e.retriesLeft=e.options.reconnectTries;e.emit("reconnect",e)}if(typeof t==="function"){t(r,n)}}))}}function moveConnectionBetween(e,t,r){var n=t.indexOf(e);if(n!==-1){t.splice(n,1);r.push(e)}}function messageHandler(e){return function(t,r){var n=null;for(var o=0;o{if(t){if(typeof e==="function"){this.destroy();e(t);return}if(this.state===v){this.emit("error",t)}this.destroy();return}T(this,R);if(this.minSize){for(let e=0;e{for(const t of O){e.removeAllListeners(t)}e.on("error",(()=>{}));e.destroy(r,t)}),(t=>{if(t){if(typeof n==="function")n(t,null);return}resetPoolState(e);e.queue=[];T(e,N);if(typeof n==="function")n(null,null)}))}Pool.prototype.destroy=function(e,t){var r=this;if(typeof e==="function"){t=e;e=false}if(this.state===N||r.state===D){if(typeof t==="function")t(null,null);return}T(this,k);if(e){var n=r.availableConnections.concat(r.inUseConnections);while(r.queue.length>0){var o=r.queue.shift();if(typeof o.cb==="function"){o.cb(new s("Pool was force destroyed"))}}return destroy(r,n,{force:true},t)}if(this.reconnectId){clearTimeout(this.reconnectId)}function checkStatus(){if(r.state===N||r.state===D){if(typeof t==="function"){t()}return}flushMonitoringOperations(r.queue);if(r.queue.length===0){var e=r.availableConnections.concat(r.inUseConnections);for(var n=0;n0){return setTimeout(checkStatus,1)}}destroy(r,e,{force:false},t)}else{_execute(r)();setTimeout(checkStatus,1)}}checkStatus()};Pool.prototype.reset=function(e){if(this.s.state!==R){if(typeof e==="function"){e(new s("pool is not connected, reset aborted"))}return}this.s.cancellationToken.emit("cancel");const t=this.availableConnections.concat(this.inUseConnections);Q(t,((e,t)=>{for(const t of O){e.removeAllListeners(t)}e.destroy({force:true},t)}),(t=>{if(t){if(typeof e==="function"){e(t,null);return}}resetPoolState(this);createConnection(this,(()=>{if(typeof e==="function"){e(null,null)}}))}))};function serializeCommand(e,t,r){const n=t.toBin();const o=!!e.options.agreedCompressor;if(!o||!canCompress(t)){return r(null,n)}const s=I.concat(n);const i=s.slice(h);const a=s.readInt32LE(12);p(e,i,(function(n,o){if(n)return r(n,null);const s=I.alloc(h);s.writeInt32LE(h+d+o.length,0);s.writeInt32LE(t.requestId,4);s.writeInt32LE(0,8);s.writeInt32LE(g.OP_COMPRESSED,12);const A=I.alloc(d);A.writeInt32LE(a,0);A.writeInt32LE(i.length,4);A.writeUInt8(E[e.options.agreedCompressor],8);return r(null,[s,A,o])}))}Pool.prototype.write=function(e,t,r){var n=this;if(typeof t==="function"){r=t}t=t||{};if(!(typeof r==="function")&&!t.noResponse){throw new s("write method must provide a callback")}if(this.state===N||this.state===D){r(new s("pool destroyed"));return}if(this.state===k){r(new s("pool is draining, new operations prohibited"));return}if(this.options.domainsEnabled&&process.domain&&typeof r==="function"){var o=r;r=process.domain.bind((function(){var e=new Array(arguments.length);for(var t=0;t{if(t){n.emit("commandFailed",new C.CommandFailedEvent(this,e,t,i.started))}else{if(o&&o.result&&(o.result.ok===0||o.result.$err)){n.emit("commandFailed",new C.CommandFailedEvent(this,e,o.result,i.started))}else{n.emit("commandSucceeded",new C.CommandSucceededEvent(this,e,o,i.started))}}if(typeof r==="function")r(t,o)}}serializeCommand(n,e,((e,r)=>{if(e)throw e;i.buffer=r;if(t.monitoring){n.queue.unshift(i)}else{n.queue.push(i)}if(!n.executing){process.nextTick((function(){_execute(n)()}))}}))};function canCompress(e){const t=e instanceof l?e.command:e.query;const r=Object.keys(t)[0];return!m.has(r)}function remove(e,t){for(var r=0;r{e.connectingConnections--;if(r){if(e.logger.isDebug()){e.logger.debug(`connection attempt failed with error [${JSON.stringify(r)}]`)}if(!e.reconnectId&&e.options.reconnect){if(e.state===v&&e.options.legacyCompatMode){t(r);return}e.reconnectError=r;e.reconnectId=setTimeout(attemptReconnect(e,t),e.options.reconnectInterval);return}if(typeof t==="function"){t(r)}return}if(e.state===N||e.state===D){if(typeof t==="function"){t(new s("Pool was destroyed after connection creation"))}n.destroy();return}n.on("error",e._connectionErrorHandler);n.on("close",e._connectionCloseHandler);n.on("timeout",e._connectionTimeoutHandler);n.on("parseError",e._connectionParseErrorHandler);n.on("message",e._messageHandler);e.availableConnections.push(n);if(typeof t==="function"){t(null,n)}_execute(e)()}))}function flushMonitoringOperations(e){for(var t=0;t0){e.executing=false;return}while(true){const i=totalConnectionCount(e);if(e.availableConnections.length===0){flushMonitoringOperations(e.queue);if(i0){createConnection(e)}break}if(e.queue.length===0){break}var t=null;const a=e.availableConnections.filter((e=>e.workItems.length===0));if(a.length===0){t=e.availableConnections[e.connectionIndex++%e.availableConnections.length]}else{t=a[e.connectionIndex++%a.length]}if(!t.isConnected()){removeConnection(e,t);flushMonitoringOperations(e.queue);break}var r=e.queue.shift();if(r.monitoring){var n=false;for(let r=0;r0){createConnection(e)}setTimeout((()=>_execute(e)()),10);break}}if(i0){e.queue.unshift(r);createConnection(e);break}}var o=r.buffer;if(r.monitoring){moveConnectionBetween(t,e.availableConnections,e.inUseConnections)}if(!r.noResponse){t.workItems.push(r)}if(!r.immediateRelease&&typeof r.socketTimeout==="number"){t.setSocketTimeout(r.socketTimeout)}var s=true;if(Array.isArray(o)){for(let e=0;e{"use strict";const n=r(1371).parsePackageVersion;const o=r(3111).MongoError;const s=r(3182)(require);function debugOptions(e,t){const r={};e.forEach((function(e){r[e]=t[e]}));return r}function retrieveBSON(){const e=r(4044);e.native=false;const t=s("bson-ext");const i=n(s("bson-ext/package.json")||{version:"0.0.0"});if(t){if(i.major>=4){throw new o("bson-ext version 4 and above does not work with the 3.x version of the mongodb driver")}t.native=true;return t}return e}function noSnappyWarning(){throw new Error("Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.")}const i=Symbol("kPkgVersion");function retrieveSnappy(){const e=s("snappy");if(!e){return{compress:noSnappyWarning,uncompress:noSnappyWarning,compressSync:noSnappyWarning,uncompressSync:noSnappyWarning}}const t=s("snappy/package.json")||{version:"0.0.0"};const r=n(t);e[i]=r;if(r.major>=7){const t=e.compress;const r=e.uncompress;e.compress=(e,r)=>{t(e).then((e=>r(undefined,e))).catch((e=>r(e)))};e.uncompress=(e,t)=>{r(e).then((e=>t(undefined,e))).catch((e=>t(e)))}}return e}e.exports={PKG_VERSION:i,debugOptions:debugOptions,retrieveBSON:retrieveBSON,retrieveSnappy:retrieveSnappy}},4847:(e,t,r)=>{"use strict";const n=r(104);const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=r(1178).collationNotSupported;const A=r(4485);const c=r(1178).isUnifiedTopology;const l=r(2548);const u=r(2781).Readable;const h=r(1371).SUPPORTS;const d=r(1371).MongoDBNamespace;const g=r(1371).mergeOptions;const p=r(1018).OperationBase;const E=o();const m=E.Long;const C={INIT:0,OPEN:1,CLOSED:2,GET_MORE:3};function handleCallback(e,t,r){try{e(t,r)}catch(t){process.nextTick((function(){throw t}))}}class CoreCursor extends u{constructor(e,t,r,o){super({objectMode:true});o=o||{};if(t instanceof p){this.operation=t;t=this.operation.ns.toString();o=this.operation.options;r=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=d.fromString(t);this.cmd=r;this.options=o;this.topology=e;this.cursorState={cursorId:null,cmd:r,documents:o.documents||[],cursorIndex:0,dead:false,killed:false,init:false,notified:false,limit:o.limit||r.limit||0,skip:o.skip||r.skip||0,batchSize:o.batchSize||r.batchSize||1e3,currentLimit:0,transforms:o.transforms,raw:o.raw||r&&r.raw};if(typeof o.session==="object"){this.cursorState.session=o.session}const s=e.s.options;if(typeof s.promoteLongs==="boolean"){this.cursorState.promoteLongs=s.promoteLongs}else if(typeof o.promoteLongs==="boolean"){this.cursorState.promoteLongs=o.promoteLongs}if(typeof s.promoteValues==="boolean"){this.cursorState.promoteValues=s.promoteValues}else if(typeof o.promoteValues==="boolean"){this.cursorState.promoteValues=o.promoteValues}if(typeof s.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=s.promoteBuffers}else if(typeof o.promoteBuffers==="boolean"){this.cursorState.promoteBuffers=o.promoteBuffers}if(typeof s.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=s.bsonRegExp}else if(typeof o.bsonRegExp==="boolean"){this.cursorState.bsonRegExp=o.bsonRegExp}if(s.reconnect){this.cursorState.reconnect=s.reconnect}this.logger=n("Cursor",s);if(typeof r==="number"){this.cursorState.cursorId=m.fromNumber(r);this.cursorState.lastCursorId=this.cursorState.cursorId}else if(r instanceof m){this.cursorState.cursorId=r;this.cursorState.lastCursorId=r}if(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){nextFunction(this,e)}clone(){const e=g({},this.options);delete e.session;return this.topology.cursor(this.ns,this.cmd,e)}isDead(){return this.cursorState.dead===true}isKilled(){return this.cursorState.killed===true}isNotified(){return this.cursorState.notified===true}bufferedCount(){return this.cursorState.documents.length-this.cursorState.cursorIndex}readBufferedDocuments(e){const t=this.cursorState.documents.length-this.cursorState.cursorIndex;const r=e0&&this.cursorState.currentLimit+n.length>this.cursorState.limit){n=n.slice(0,this.cursorState.limit-this.cursorState.currentLimit);this.kill()}this.cursorState.currentLimit=this.cursorState.currentLimit+n.length;this.cursorState.cursorIndex=this.cursorState.cursorIndex+n.length;return n}kill(e){this.cursorState.dead=true;this.cursorState.killed=true;this.cursorState.documents=[];if(this.cursorState.cursorId==null||this.cursorState.cursorId.isZero()||this.cursorState.init===false){if(e)e(null,null);return}this.server.killCursors(this.ns,this.cursorState,e)}rewind(){if(this.cursorState.init){if(!this.cursorState.dead){this.kill()}this.cursorState.currentLimit=0;this.cursorState.init=false;this.cursorState.dead=false;this.cursorState.killed=false;this.cursorState.notified=false;this.cursorState.documents=[];this.cursorState.cursorId=null;this.cursorState.cursorIndex=0}}_read(){if(this.s&&this.s.state===C.CLOSED||this.isDead()){return this.push(null)}this._next(((e,t)=>{if(e){if(this.listeners("error")&&this.listeners("error").length>0){this.emit("error",e)}if(!this.isDead())this.close();this.emit("end");return this.emit("finish")}if(this.cursorState.streamOptions&&typeof this.cursorState.streamOptions.transform==="function"&&t!=null){return this.push(this.cursorState.streamOptions.transform(t))}this.push(t);if(t===null&&this.isDead()){this.once("end",(()=>{this.close();this.emit("finish")}))}}))}_endSession(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};const r=this.cursorState.session;if(r&&(e.force||r.owner===this)){this.cursorState.session=undefined;if(this.operation){this.operation.clearSession()}r.endSession(t);return true}if(t){t()}return false}_getMore(e){if(this.logger.isDebug()){this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`)}let t=this.cursorState.batchSize;if(this.cursorState.limit>0&&this.cursorState.currentLimit+t>this.cursorState.limit){t=this.cursorState.limit-this.cursorState.currentLimit}const r=this.cursorState;this.server.getMore(this.ns,r,t,this.options,((t,n,o)=>{if(t||r.cursorId&&r.cursorId.isZero()){this._endSession()}e(t,n,o)}))}_initializeCursor(e){const t=this;if(c(t.topology)&&t.topology.shouldCheckForSessionSupport()){t.topology.selectServer(A.primaryPreferred,(t=>{if(t){e(t);return}this._initializeCursor(e)}));return}function done(r,n){const o=t.cursorState;if(r||o.cursorId&&o.cursorId.isZero()){t._endSession()}if(o.documents.length===0&&o.cursorId&&o.cursorId.isZero()&&!t.cmd.tailable&&!t.cmd.awaitData){return setCursorNotified(t,e)}e(r,n)}const queryCallback=(e,r)=>{if(e){return done(e)}const n=r.message;if(Array.isArray(n.documents)&&n.documents.length===1){const e=n.documents[0];if(n.queryFailure){return done(new s(e),null)}if(!t.cmd.find||t.cmd.find&&t.cmd.virtual===false){if(e.$err||e.errmsg){return done(new s(e),null)}if(e.cursor!=null&&typeof e.cursor!=="string"){const r=e.cursor.id;if(e.cursor.ns){t.ns=e.cursor.ns}t.cursorState.cursorId=typeof r==="number"?m.fromNumber(r):r;t.cursorState.lastCursorId=t.cursorState.cursorId;t.cursorState.operationTime=e.operationTime;if(Array.isArray(e.cursor.firstBatch)){t.cursorState.documents=e.cursor.firstBatch}return done(null,n)}}}const o=n.cursorId||0;t.cursorState.cursorId=o instanceof m?o:m.fromNumber(o);t.cursorState.documents=n.documents;t.cursorState.lastCursorId=n.cursorId;if(t.cursorState.transforms&&typeof t.cursorState.transforms.query==="function"){t.cursorState.documents=t.cursorState.transforms.query(n)}done(null,n)};if(t.operation){if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}l(t.topology,t.operation,((e,r)=>{if(e){done(e);return}t.server=t.operation.server;t.cursorState.init=true;if(t.cursorState.cursorId!=null){return done()}queryCallback(e,r)}));return}const r={};if(t.cursorState.session){r.session=t.cursorState.session}if(t.operation){r.readPreference=t.operation.readPreference}else if(t.options.readPreference){r.readPreference=t.options.readPreference}return t.topology.selectServer(r,((r,n)=>{if(r){const n=t.disconnectHandler;if(n!=null){return n.addObjectAndMethod("cursor",t,"next",[e],e)}return e(r)}t.server=n;t.cursorState.init=true;if(a(t.server,t.cmd)){return e(new s(`server ${t.server.name} does not support collation`))}if(t.cursorState.cursorId!=null){return done()}if(t.logger.isDebug()){t.logger.debug(`issue initial query [${JSON.stringify(t.cmd)}] with flags [${JSON.stringify(t.query)}]`)}if(t.cmd.find!=null){n.query(t.ns,t.cmd,t.cursorState,t.options,queryCallback);return}const o=Object.assign({session:t.cursorState.session},t.options);n.command(t.ns,t.cmd,o,queryCallback)}))}}if(h.ASYNC_ITERATOR){CoreCursor.prototype[Symbol.asyncIterator]=r(1749).asyncIterator}function isConnectionDead(e,t){if(e.pool&&e.pool.isDestroyed()){e.cursorState.killed=true;const r=new i(`connection to host ${e.pool.host}:${e.pool.port} was destroyed`);_setCursorNotifiedImpl(e,(()=>t(r)));return true}return false}function isCursorDeadButNotkilled(e,t){if(e.cursorState.dead&&!e.cursorState.killed){e.cursorState.killed=true;setCursorNotified(e,t);return true}return false}function isCursorDeadAndKilled(e,t){if(e.cursorState.dead&&e.cursorState.killed){handleCallback(t,new s("cursor is dead"));return true}return false}function isCursorKilled(e,t){if(e.cursorState.killed){setCursorNotified(e,t);return true}return false}function setCursorDeadAndNotified(e,t){e.cursorState.dead=true;setCursorNotified(e,t)}function setCursorNotified(e,t){_setCursorNotifiedImpl(e,(()=>handleCallback(t,null,null)))}function _setCursorNotifiedImpl(e,t){e.cursorState.notified=true;e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.cursorState.session){e._endSession(t);return}return t()}function nextFunction(e,t){if(e.cursorState.notified){return t(new Error("cursor is exhausted"))}if(isCursorKilled(e,t))return;if(isCursorDeadButNotkilled(e,t))return;if(isCursorDeadAndKilled(e,t))return;if(!e.cursorState.init){if(!e.topology.isConnected(e.options)){if(e.topology._type==="server"&&!e.topology.s.options.reconnect){return t(new s("no connection available"))}if(e.disconnectHandler!=null){if(e.topology.isDestroyed()){return t(new s("Topology was destroyed"))}e.disconnectHandler.addObjectAndMethod("cursor",e,"next",[t],t);return}}e._initializeCursor(((r,n)=>{if(r||n===null){t(r,n);return}nextFunction(e,t)}));return}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)))}else if(e.cursorState.cursorIndex===e.cursorState.documents.length&&!m.ZERO.equals(e.cursorState.cursorId)){e.cursorState.documents=[];e.cursorState.cursorIndex=0;if(e.topology.isDestroyed())return t(new i("connection destroyed, not possible to instantiate cursor"));if(isConnectionDead(e,t))return;e._getMore((function(r,n,o){if(r){return handleCallback(t,r)}e.connection=o;if(e.cursorState.documents.length===0&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===0&&e.cmd.tailable&&!m.ZERO.equals(e.cursorState.cursorId)){return nextFunction(e,t)}if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){return setCursorDeadAndNotified(e,t)}nextFunction(e,t)}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&e.cmd.tailable&&m.ZERO.equals(e.cursorState.cursorId)){return handleCallback(t,new s({message:"No more documents in tailed cursor",tailable:e.cmd.tailable,awaitData:e.cmd.awaitData}))}else if(e.cursorState.documents.length===e.cursorState.cursorIndex&&m.ZERO.equals(e.cursorState.cursorId)){setCursorDeadAndNotified(e,t)}else{if(e.cursorState.limit>0&&e.cursorState.currentLimit>=e.cursorState.limit){e.kill((()=>setCursorDeadAndNotified(e,t)));return}e.cursorState.currentLimit+=1;let r=e.cursorState.documents[e.cursorState.cursorIndex++];if(!r||r.$err){e.kill((()=>setCursorDeadAndNotified(e,(function(){handleCallback(t,new s(r?r.$err:undefined))}))));return}if(e.cursorState.transforms&&typeof e.cursorState.transforms.doc==="function"){r=e.cursorState.transforms.doc(r)}handleCallback(t,null,r)}}e.exports={CursorState:C,CoreCursor:CoreCursor}},3111:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=Symbol("errorLabels");class MongoError extends Error{constructor(e){if(e instanceof Error){super(e.message);this.stack=e.stack}else{if(typeof e==="string"){super(e)}else{super(e.message||e.errmsg||e.$err||"n/a");if(e.errorLabels){this[o]=new Set(e.errorLabels)}for(var t in e){if(t==="errorLabels"||t==="errmsg"){continue}this[t]=e[t]}}Error.captureStackTrace(this,this.constructor)}this.name="MongoError"}get errmsg(){return this.message}static create(e){return new MongoError(e)}hasErrorLabel(e){if(this[o]==null){return false}return this[o].has(e)}addErrorLabel(e){if(this[o]==null){this[o]=new Set}this[o].add(e)}get errorLabels(){return this[o]?Array.from(this[o]):[]}}const s=Symbol("beforeHandshake");function isNetworkErrorBeforeHandshake(e){return e[s]===true}class MongoNetworkError extends MongoError{constructor(e,t){super(e);this.name="MongoNetworkError";if(t&&typeof t.beforeHandshake==="boolean"){this[s]=t.beforeHandshake}}}class MongoNetworkTimeoutError extends MongoNetworkError{constructor(e,t){super(e,t);this.name="MongoNetworkTimeoutError"}}class MongoParseError extends MongoError{constructor(e){super(e);this.name="MongoParseError"}}class MongoTimeoutError extends MongoError{constructor(e,t){if(t&&t.error){super(t.error.message||t.error)}else{super(e)}this.name="MongoTimeoutError";if(t){this.reason=t}}}class MongoServerSelectionError extends MongoTimeoutError{constructor(e,t){super(e,t);this.name="MongoServerSelectionError"}}function makeWriteConcernResultObject(e){const t=Object.assign({},e);if(t.ok===0){t.ok=1;delete t.errmsg;delete t.code;delete t.codeName}return t}class MongoWriteConcernError extends MongoError{constructor(e,t){super(e);this.name="MongoWriteConcernError";if(t&&Array.isArray(t.errorLabels)){this[o]=new Set(t.errorLabels)}if(t!=null){this.result=makeWriteConcernResultObject(t)}}}const i=new Set([n.HostUnreachable,n.HostNotFound,n.NetworkTimeout,n.ShutdownInProgress,n.PrimarySteppedDown,n.SocketException,n.NotMaster,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary]);const a=new Set([n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMaster,n.NotMasterNoSlaveOk,n.NotMasterOrSecondary,n.PrimarySteppedDown,n.ShutdownInProgress,n.HostNotFound,n.HostUnreachable,n.NetworkTimeout,n.SocketException,n.ExceededTimeLimit]);function isRetryableEndTransactionError(e){return e.hasErrorLabel("RetryableWriteError")}function isRetryableWriteError(e){if(e instanceof MongoWriteConcernError){return a.has(e.code)||a.has(e.result.code)}return a.has(e.code)}function isRetryableError(e){return i.has(e.code)||e instanceof MongoNetworkError||e.message.match(/not master/)||e.message.match(/node is recovering/)}const A=new Set([n.ShutdownInProgress,n.PrimarySteppedDown,n.InterruptedAtShutdown,n.InterruptedDueToReplStateChange,n.NotMasterOrSecondary]);const c=new Set([n.NotMaster,n.NotMasterNoSlaveOk,n.LegacyNotPrimary]);const l=new Set([n.InterruptedAtShutdown,n.ShutdownInProgress]);function isRecoveringError(e){if(typeof e.code==="number"){return A.has(e.code)}return/not master or secondary/.test(e.message)||/node is recovering/.test(e.message)}function isNotMasterError(e){if(typeof e.code==="number"){return c.has(e.code)}if(isRecoveringError(e)){return false}return/not master/.test(e.message)}function isNodeShuttingDownError(e){return e.code&&l.has(e.code)}function isSDAMUnrecoverableError(e){if(e instanceof MongoParseError||e==null){return true}return isRecoveringError(e)||isNotMasterError(e)}e.exports={MongoError:MongoError,MongoNetworkError:MongoNetworkError,MongoNetworkTimeoutError:MongoNetworkTimeoutError,MongoParseError:MongoParseError,MongoTimeoutError:MongoTimeoutError,MongoServerSelectionError:MongoServerSelectionError,MongoWriteConcernError:MongoWriteConcernError,isRetryableError:isRetryableError,isSDAMUnrecoverableError:isSDAMUnrecoverableError,isNodeShuttingDownError:isNodeShuttingDownError,isRetryableWriteError:isRetryableWriteError,isNetworkErrorBeforeHandshake:isNetworkErrorBeforeHandshake,isRetryableEndTransactionError:isRetryableEndTransactionError}},3994:(e,t,r)=>{"use strict";let n=r(4044);const o=r(3182)(require);const s=r(1178).retrieveEJSON();try{const e=o("bson-ext");if(e){n=e}}catch(e){}const i=Object.freeze({v1:"1"});const a=Object.keys(i).map((e=>i[e]));e.exports={ServerApiVersion:i,ValidServerApiVersions:a,MongoError:r(3111).MongoError,MongoNetworkError:r(3111).MongoNetworkError,MongoParseError:r(3111).MongoParseError,MongoTimeoutError:r(3111).MongoTimeoutError,MongoServerSelectionError:r(3111).MongoServerSelectionError,MongoWriteConcernError:r(3111).MongoWriteConcernError,Connection:r(6096),Server:r(6495),ReplSet:r(1134),Mongos:r(8175),Logger:r(104),Cursor:r(4847).CoreCursor,ReadPreference:r(4485),Sessions:r(5474),BSON:n,EJSON:s,Topology:r(4149).Topology,Query:r(9814).Query,MongoCredentials:r(2222).MongoCredentials,defaultAuthProviders:r(2192).defaultAuthProviders,MongoCR:r(4228),X509:r(7324),Plain:r(8728),GSSAPI:r(2640),ScramSHA1:r(864).ScramSHA1,ScramSHA256:r(864).ScramSHA256,parseConnectionString:r(8767)}},2291:e=>{"use strict";const t="closing";const r="closed";const n="connecting";const o="connected";const s={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};const i={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};function serverType(e){let t=e.s.description||e.s.serverDescription;if(t.topologyType===s.Single)return t.servers[0].type;return t.type}const a={useUnifiedTopology:true,localThresholdMS:15,serverSelectionTimeoutMS:3e4,heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:500};function drainTimerQueue(e){e.forEach(clearTimeout);e.clear()}function clearAndRemoveTimerFrom(e,t){clearTimeout(e);return t.delete(e)}e.exports={STATE_CLOSING:t,STATE_CLOSED:r,STATE_CONNECTING:n,STATE_CONNECTED:o,TOPOLOGY_DEFAULTS:a,TopologyType:s,ServerType:i,serverType:serverType,drainTimerQueue:drainTimerQueue,clearAndRemoveTimerFrom:clearAndRemoveTimerFrom}},2785:e=>{"use strict";class ServerDescriptionChangedEvent{constructor(e,t,r,n){Object.assign(this,{topologyId:e,address:t,previousDescription:r,newDescription:n})}}class ServerOpeningEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class ServerClosedEvent{constructor(e,t){Object.assign(this,{topologyId:e,address:t})}}class TopologyDescriptionChangedEvent{constructor(e,t,r){Object.assign(this,{topologyId:e,previousDescription:t,newDescription:r})}}class TopologyOpeningEvent{constructor(e){Object.assign(this,{topologyId:e})}}class TopologyClosedEvent{constructor(e){Object.assign(this,{topologyId:e})}}class ServerHeartbeatStartedEvent{constructor(e){Object.assign(this,{connectionId:e})}}class ServerHeartbeatSucceededEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,reply:t})}}class ServerHeartbeatFailedEvent{constructor(e,t,r){Object.assign(this,{connectionId:r,duration:e,failure:t})}}e.exports={ServerDescriptionChangedEvent:ServerDescriptionChangedEvent,ServerOpeningEvent:ServerOpeningEvent,ServerClosedEvent:ServerClosedEvent,TopologyDescriptionChangedEvent:TopologyDescriptionChangedEvent,TopologyOpeningEvent:TopologyOpeningEvent,TopologyClosedEvent:TopologyClosedEvent,ServerHeartbeatStartedEvent:ServerHeartbeatStartedEvent,ServerHeartbeatSucceededEvent:ServerHeartbeatSucceededEvent,ServerHeartbeatFailedEvent:ServerHeartbeatFailedEvent}},1203:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(2361);const s=r(6573);const i=r(9820).Connection;const a=r(2291);const A=r(1178).makeStateMachine;const c=r(3111).MongoNetworkError;const l=r(7746).retrieveBSON();const u=r(1371).makeInterruptableAsyncInterval;const h=r(1371).calculateDurationInMs;const d=r(1371).now;const g=r(2785);const p=g.ServerHeartbeatStartedEvent;const E=g.ServerHeartbeatSucceededEvent;const m=g.ServerHeartbeatFailedEvent;const C=Symbol("server");const I=Symbol("monitorId");const y=Symbol("connection");const B=Symbol("cancellationToken");const Q=Symbol("rttPinger");const b=Symbol("roundTripTime");const w=a.STATE_CLOSED;const S=a.STATE_CLOSING;const v="idle";const R="monitoring";const k=A({[S]:[S,v,w],[w]:[w,R],[v]:[v,R,S],[R]:[R,v,S]});const D=new Set([S,w,R]);function isInCloseState(e){return e.s.state===w||e.s.state===S}class Monitor extends o{constructor(e,t){super(t);this[C]=e;this[y]=undefined;this[B]=new o;this[B].setMaxListeners(Infinity);this[I]=null;this.s={state:w};this.address=e.description.address;this.options=Object.freeze({connectTimeoutMS:typeof t.connectionTimeout==="number"?t.connectionTimeout:typeof t.connectTimeoutMS==="number"?t.connectTimeoutMS:1e4,heartbeatFrequencyMS:typeof t.heartbeatFrequencyMS==="number"?t.heartbeatFrequencyMS:1e4,minHeartbeatFrequencyMS:typeof t.minHeartbeatFrequencyMS==="number"?t.minHeartbeatFrequencyMS:500,useUnifiedTopology:t.useUnifiedTopology});const r=Object.assign({id:"",host:e.description.host,port:e.description.port,bson:e.s.bson,connectionType:i},e.s.options,this.options,{raw:false,promoteLongs:true,promoteValues:true,promoteBuffers:true,bsonRegExp:true});delete r.credentials;delete r.autoEncrypter;this.connectOptions=Object.freeze(r)}connect(){if(this.s.state!==w){return}const e=this.options.heartbeatFrequencyMS;const t=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:e,minInterval:t,immediate:true})}requestCheck(){if(D.has(this.s.state)){return}this[I].wake()}reset(){const e=this[C].description.topologyVersion;if(isInCloseState(this)||e==null){return}k(this,S);resetMonitorState(this);k(this,v);const t=this.options.heartbeatFrequencyMS;const r=this.options.minHeartbeatFrequencyMS;this[I]=u(monitorServer(this),{interval:t,minInterval:r})}close(){if(isInCloseState(this)){return}k(this,S);resetMonitorState(this);this.emit("close");k(this,w)}}function resetMonitorState(e){if(e[I]){e[I].stop();e[I]=null}if(e[Q]){e[Q].close();e[Q]=undefined}e[B].emit("cancel");if(e[I]){clearTimeout(e[I]);e[I]=undefined}if(e[y]){e[y].destroy({force:true})}}function checkServer(e,t){let r=d();e.emit("serverHeartbeatStarted",new p(e.address));function failureHandler(n){if(e[y]){e[y].destroy({force:true});e[y]=undefined}e.emit("serverHeartbeatFailed",new m(h(r),n,e.address));e.emit("resetServer",n);e.emit("resetConnectionPool");t(n)}if(e[y]!=null&&!e[y].closed){const n=e.options.connectTimeoutMS;const o=e.options.heartbeatFrequencyMS;const s=e[C].description.topologyVersion;const i=s!=null;const a=e[y].serverApi;const A=e[y].helloOk;const c={[a||A?"hello":"ismaster"]:true};if(A)c.helloOk=A;const l={socketTimeout:n};if(i){c.maxAwaitTimeMS=o;c.topologyVersion=makeTopologyVersion(s);if(n){l.socketTimeout=n+o}l.exhaustAllowed=true;if(e[Q]==null){e[Q]=new RTTPinger(e[B],e.connectOptions)}}e[y].command("admin.$cmd",c,l,((n,o)=>{if(n){failureHandler(n);return}const s=o.result;const a=e[Q];if("isWritablePrimary"in s){s.ismaster=s.isWritablePrimary}const A=i&&a?a.roundTripTime:h(r);e.emit("serverHeartbeatSucceeded",new E(A,s,e.address));if(i&&s.topologyVersion){e.emit("serverHeartbeatStarted",new p(e.address));r=d()}else{if(e[Q]){e[Q].close();e[Q]=undefined}t(undefined,s)}}));return}s(e.connectOptions,e[B],((n,o)=>{if(o&&isInCloseState(e)){o.destroy({force:true});return}if(n){e[y]=undefined;if(!(n instanceof c)){e.emit("resetConnectionPool")}failureHandler(n);return}e[y]=o;e.emit("serverHeartbeatSucceeded",new E(h(r),o.ismaster,e.address));t(undefined,o.ismaster)}))}function monitorServer(e){return t=>{k(e,R);function done(){if(!isInCloseState(e)){k(e,v)}t()}process.nextTick((()=>e.emit("monitoring",e[C])));checkServer(e,((t,r)=>{if(t){if(e[C].description.type===n.Unknown){e.emit("resetServer",t);return done()}}if(r&&r.topologyVersion){setTimeout((()=>{if(!isInCloseState(e)){e[I].wake()}}))}done()}))}}function makeTopologyVersion(e){return{processId:e.processId,counter:l.Long.fromNumber(e.counter)}}class RTTPinger{constructor(e,t){this[y]=null;this[B]=e;this[b]=0;this.closed=false;const r=t.heartbeatFrequencyMS;this[I]=setTimeout((()=>measureRoundTripTime(this,t)),r)}get roundTripTime(){return this[b]}close(){this.closed=true;clearTimeout(this[I]);this[I]=undefined;if(this[y]){this[y].destroy({force:true})}}}function measureRoundTripTime(e,t){const r=d();const n=e[B];const o=t.heartbeatFrequencyMS;if(e.closed){return}function measureAndReschedule(n){if(e.closed){n.destroy({force:true});return}if(e[y]==null){e[y]=n}e[b]=h(r);e[I]=setTimeout((()=>measureRoundTripTime(e,t)),o)}if(e[y]==null){s(t,n,((t,r)=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule(r)}));return}e[y].command("admin.$cmd",{ismaster:1},(t=>{if(t){e[y]=undefined;e[b]=0;return}measureAndReschedule()}))}e.exports={Monitor:Monitor}},7062:(e,t,r)=>{"use strict";const n=r(2361);const o=r(2529).ConnectionPool;const s=r(897).CMAP_EVENT_NAMES;const i=r(3111).MongoError;const a=r(1178).relayEvents;const A=r(7746).retrieveBSON();const c=r(104);const l=r(750).ServerDescription;const u=r(750).compareTopologyVersion;const h=r(4485);const d=r(1203).Monitor;const g=r(3111).MongoNetworkError;const p=r(3111).MongoNetworkTimeoutError;const E=r(1178).collationNotSupported;const m=r(7746).debugOptions;const C=r(3111).isSDAMUnrecoverableError;const I=r(3111).isRetryableWriteError;const y=r(3111).isNodeShuttingDownError;const B=r(3111).isNetworkErrorBeforeHandshake;const Q=r(1178).maxWireVersion;const b=r(1178).makeStateMachine;const w=r(7703).extractCommand;const S=r(2291);const v=S.ServerType;const R=r(1707).isTransactionCommand;const k=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];const D=S.STATE_CLOSING;const N=S.STATE_CLOSED;const T=S.STATE_CONNECTING;const O=S.STATE_CONNECTED;const _=b({[N]:[N,T],[T]:[T,D,O,N],[O]:[O,D,N],[D]:[D,N]});const M=Symbol("monitor");class Server extends n{constructor(e,t,r){super();this.s={description:e,options:t,logger:c("Server",t),bson:t.bson||new A([A.Binary,A.Code,A.DBRef,A.Decimal128,A.Double,A.Int32,A.Long,A.Map,A.MaxKey,A.MinKey,A.ObjectId,A.BSONRegExp,A.Symbol,A.Timestamp]),state:N,credentials:t.credentials,topology:r};this.serverApi=t.serverApi;const n=Object.assign({host:this.description.host,port:this.description.port,bson:this.s.bson},t);this.s.pool=new o(n);a(this.s.pool,this,["commandStarted","commandSucceeded","commandFailed"].concat(s));this.s.pool.on("clusterTimeReceived",(e=>{this.clusterTime=e}));this[M]=new d(this,this.s.options);a(this[M],this,["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","monitoring"]);this[M].on("resetConnectionPool",(()=>{this.s.pool.clear()}));this[M].on("resetServer",(e=>markServerUnknown(this,e)));this[M].on("serverHeartbeatSucceeded",(e=>{this.emit("descriptionReceived",new l(this.description.address,e.reply,{roundTripTime:calculateRoundTripTime(this.description.roundTripTime,e.duration)}));if(this.s.state===T){_(this,O);this.emit("connect",this)}}))}get description(){return this.s.description}get supportsRetryableWrites(){return supportsRetryableWrites(this)}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter){return this.s.options.autoEncrypter}return null}connect(){if(this.s.state!==N){return}_(this,T);this[M].connect()}destroy(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{force:false},e);if(this.s.state===N){if(typeof t==="function"){t()}return}_(this,D);this[M].close();this.s.pool.close(e,(e=>{_(this,N);this.emit("closed");if(typeof t==="function"){t(e)}}))}requestCheck(){this[M].requestCheck()}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}r.serverApi=this.serverApi;if(this.s.state===D||this.s.state===N){n(new i("server is closed"));return}const o=basicReadValidations(this,r);if(o){return n(o)}r=Object.assign({},r,{wireProtocolCommand:false});if(this.s.logger.isDebug()){const n=w(t);this.s.logger.debug(`executing command [${JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:m(k,r)})}] against ${this.name}`)}if(E(this,t)){n(new i(`server ${this.name} does not support collation`));return}this.s.pool.withConnection(((n,o,s)=>{if(n){markServerUnknown(this,n);return s(n)}o.command(e,t,r,makeOperationHandler(this,o,t,r,s))}),n)}query(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.query(e,t,r,n,makeOperationHandler(this,s,t,n,i))}),o)}getMore(e,t,r,n,o){if(this.s.state===D||this.s.state===N){o(new i("server is closed"));return}this.s.pool.withConnection(((o,s,i)=>{if(o){markServerUnknown(this,o);return i(o)}s.getMore(e,t,r,n,makeOperationHandler(this,s,null,n,i))}),o)}killCursors(e,t,r){if(this.s.state===D||this.s.state===N){if(typeof r==="function"){r(new i("server is closed"))}return}this.s.pool.withConnection(((r,n,o)=>{if(r){markServerUnknown(this,r);return o(r)}n.killCursors(e,t,makeOperationHandler(this,n,null,undefined,o))}),r)}insert(e,t,r,n){executeWriteOperation({server:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({server:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({server:this,op:"remove",ns:e,ops:t},r,n)}}Object.defineProperty(Server.prototype,"clusterTime",{get:function(){return this.s.topology.clusterTime},set:function(e){this.s.topology.clusterTime=e}});function supportsRetryableWrites(e){return e.description.maxWireVersion>=6&&e.description.logicalSessionTimeoutMinutes&&e.description.type!==v.Standalone}function calculateRoundTripTime(e,t){if(e===-1){return t}const r=.2;return r*t+(1-r)*e}function basicReadValidations(e,t){if(t.readPreference&&!(t.readPreference instanceof h)){return new i("readPreference must be an instance of ReadPreference")}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.server;const o=e.op;const s=e.ns;const a=Array.isArray(e.ops)?e.ops:[e.ops];if(n.s.state===D||n.s.state===N){r(new i("server is closed"));return}if(E(n,t)){r(new i(`server ${n.name} does not support collation`));return}const A=t.writeConcern&&t.writeConcern.w===0;if(A||Q(n)<5){if((o==="update"||o==="remove")&&a.find((e=>e.hint))){r(new i(`servers < 3.4 do not support hint on ${o}`));return}}n.s.pool.withConnection(((e,r,i)=>{if(e){markServerUnknown(n,e);return i(e)}r[o](s,a,t,makeOperationHandler(n,r,a,t,i))}),r)}function markServerUnknown(e,t){if(t instanceof g&&!(t instanceof p)){e[M].reset()}e.emit("descriptionReceived",new l(e.description.address,null,{error:t,topologyVersion:t&&t.topologyVersion?t.topologyVersion:e.description.topologyVersion}))}function connectionIsStale(e,t){return t.generation!==e.generation}function shouldHandleStateChangeError(e,t){const r=t.topologyVersion;const n=e.description.topologyVersion;return u(n,r)<0}function inActiveTransaction(e,t){return e&&e.inTransaction()&&!R(t)}function makeOperationHandler(e,t,r,n,o){const s=n&&n.session;return function handleOperationResult(n,i){if(n&&!connectionIsStale(e.s.pool,t)){if(n instanceof g){if(s&&!s.hasEnded){s.serverSession.isDirty=true}if(supportsRetryableWrites(e)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(!(n instanceof p)||B(n)){markServerUnknown(e,n);e.s.pool.clear()}}else{if(Q(e)<9&&I(n)&&!inActiveTransaction(s,r)){n.addErrorLabel("RetryableWriteError")}if(C(n)){if(shouldHandleStateChangeError(e,n)){if(Q(e)<=7||y(n)){e.s.pool.clear()}markServerUnknown(e,n);process.nextTick((()=>e.requestCheck()))}}}}o(n,i)}}e.exports={Server:Server}},750:(e,t,r)=>{"use strict";const n=r(1178).arrayStrictEqual;const o=r(1178).tagsStrictEqual;const s=r(1178).errorStrictEqual;const i=r(2291).ServerType;const a=r(1371).now;const A=new Set([i.RSPrimary,i.Standalone,i.Mongos]);const c=new Set([i.RSPrimary,i.RSSecondary,i.Mongos,i.Standalone]);const l=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","compression","me","hosts","passives","arbiters","tags","setName","setVersion","electionId","primary","logicalSessionTimeoutMinutes","saslSupportedMechs","__nodejs_mock_server__","$clusterTime"];class ServerDescription{constructor(e,t,r){r=r||{};t=Object.assign({minWireVersion:0,maxWireVersion:0,hosts:[],passives:[],arbiters:[],tags:[]},t);if(t.isWritablePrimary!=null){t.ismaster=t.isWritablePrimary}this.address=e;this.error=r.error;this.roundTripTime=r.roundTripTime||-1;this.lastUpdateTime=a();this.lastWriteDate=t.lastWrite?t.lastWrite.lastWriteDate:null;this.opTime=t.lastWrite?t.lastWrite.opTime:null;this.type=parseServerType(t);this.topologyVersion=r.topologyVersion||t.topologyVersion;l.forEach((e=>{if(typeof t[e]!=="undefined")this[e]=t[e]}));if(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 c.has(this.type)}get isWritable(){return A.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||compareTopologyVersion(this.topologyVersion,e.topologyVersion)===0;return e!=null&&s(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&this.me===e.me&&n(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}}function parseServerType(e){if(!e||!e.ok){return i.Unknown}if(e.isreplicaset){return i.RSGhost}if(e.msg&&e.msg==="isdbgrid"){return i.Mongos}if(e.setName){if(e.hidden){return i.RSOther}else if(e.ismaster){return i.RSPrimary}else if(e.secondary){return i.RSSecondary}else if(e.arbiterOnly){return i.RSArbiter}else{return i.RSOther}}return i.Standalone}function compareTopologyVersion(e,t){if(e==null||t==null){return-1}if(e.processId.equals(t.processId)){if(e.counter===t.counter){return 0}else if(e.counter{"use strict";const n=r(2291).ServerType;const o=r(2291).TopologyType;const s=r(4485);const i=r(3111).MongoError;const a=1e4;const A=90;function writableServerSelector(){return function(e,t){return latencyWindowReducer(e,t.filter((e=>e.isWritable)))}}function maxStalenessReducer(e,t,r){if(e.maxStalenessSeconds==null||e.maxStalenessSeconds<0){return r}const n=e.maxStalenessSeconds;const s=(t.heartbeatFrequencyMS+a)/1e3;if(n{const s=o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}if(t.type===o.ReplicaSetNoPrimary){if(r.length===0){return r}const n=r.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return r.reduce(((r,o)=>{const s=n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS;const i=s/1e3;if(i<=e.maxStalenessSeconds)r.push(o);return r}),[])}return r}function tagSetMatch(e,t){const r=Object.keys(e);const n=Object.keys(t);for(let o=0;o{if(tagSetMatch(n,t.tags))e.push(t);return e}),[]);if(o.length){return o}}return[]}function latencyWindowReducer(e,t){const r=t.reduce(((e,t)=>e===-1?t.roundTripTime:Math.min(t.roundTripTime,e)),-1);const n=r+e.localThresholdMS;return t.reduce(((e,t)=>{if(t.roundTripTime<=n&&t.roundTripTime>=r)e.push(t);return e}),[])}function primaryFilter(e){return e.type===n.RSPrimary}function secondaryFilter(e){return e.type===n.RSSecondary}function nearestFilter(e){return e.type===n.RSSecondary||e.type===n.RSPrimary}function knownFilter(e){return e.type!==n.Unknown}function readPreferenceServerSelector(e){if(!e.isValid()){throw new TypeError("Invalid read preference specified")}return function(t,r){const n=t.commonWireVersion;if(n&&e.minWireVersion&&e.minWireVersion>n){throw new i(`Minimum wire version '${e.minWireVersion}' required, but found '${n}'`)}if(t.type===o.Unknown){return[]}if(t.type===o.Single||t.type===o.Sharded){return latencyWindowReducer(t,r.filter(knownFilter))}const a=e.mode;if(a===s.PRIMARY){return r.filter(primaryFilter)}if(a===s.PRIMARY_PREFERRED){const e=r.filter(primaryFilter);if(e.length){return e}}const A=a===s.NEAREST?nearestFilter:secondaryFilter;const c=latencyWindowReducer(t,tagSetReducer(e,maxStalenessReducer(e,t,r.filter(A))));if(a===s.SECONDARY_PREFERRED&&c.length===0){return r.filter(primaryFilter)}return c}}e.exports={writableServerSelector:writableServerSelector,readPreferenceServerSelector:readPreferenceServerSelector}},9663:(e,t,r)=>{"use strict";var n;const o=r(104);const s=r(2361).EventEmitter;const i=r(7578);function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}class SrvPollingEvent{constructor(e){this.srvRecords=e}addresses(){return new Set(this.srvRecords.map((e=>`${e.name}:${e.port}`)))}}class SrvPoller extends s{constructor(e){super();if(!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=o("srvPoller",e);this.haMode=false;this.generation=0;this._timeout=null}get srvAddress(){return`_mongodb._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){if(!this._timeout){this.schedule()}}stop(){if(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=false;this.schedule();this.emit("srvRecordDiscovery",new SrvPollingEvent(e))}failure(e,t){this.logger.warn(e,t);this.haMode=true;this.schedule()}parentDomainMismatch(e){this.logger.warn(`parent domain mismatch on SRV record (${e.name}:${e.port})`,e)}_poll(){const e=this.generation;i.resolveSrv(this.srvAddress,((t,r)=>{if(e!==this.generation){return}if(t){this.failure("DNS error",t);return}const n=[];r.forEach((e=>{if(matchesParentDomain(e.name,this.srvHost)){n.push(e)}else{this.parentDomainMismatch(e)}}));if(!n.length){this.failure("No valid addresses found at host");return}this.success(n)}))}}n=SrvPollingEvent;e.exports.D=SrvPoller},4149:(e,t,r)=>{"use strict";const n=r(2342);const o=r(2361);const s=r(750).ServerDescription;const i=r(2291).ServerType;const a=r(7962).TopologyDescription;const A=r(2291).TopologyType;const c=r(2785);const l=r(7062).Server;const u=r(1178).relayEvents;const h=r(4485);const d=r(4847).CoreCursor;const g=r(3837).deprecate;const p=r(7746).retrieveBSON();const E=r(2306).createCompressionInfo;const m=r(5474).ClientSession;const C=r(3111).MongoError;const I=r(3111).MongoServerSelectionError;const y=r(2306).resolveClusterTime;const B=r(9663).D;const Q=r(2306).getMMAPError;const b=r(1178).makeStateMachine;const w=r(1178).eachAsync;const S=r(1371).emitDeprecationWarning;const v=r(5474).ServerSessionPool;const R=r(1178).makeClientMetadata;const k=r(897).CMAP_EVENT_NAMES;const D=r(750).compareTopologyVersion;const N=r(1371).emitWarning;const T=r(2291);const O=T.drainTimerQueue;const _=T.clearAndRemoveTimerFrom;const M=r(4547);const L=M.readPreferenceServerSelector;const F=M.writableServerSelector;let U=0;const P=["serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","commandStarted","commandSucceeded","commandFailed","monitoring"].concat(k);const G=["connect","descriptionReceived","close","ended"];const Y=T.STATE_CLOSING;const V=T.STATE_CLOSED;const W=T.STATE_CONNECTING;const J=T.STATE_CONNECTED;const q=b({[V]:[V,W],[W]:[W,Y,J,V],[J]:[J,Y,V],[Y]:[Y,V]});const j=new Set(["autoReconnect","reconnectTries","reconnectInterval","bufferMaxEntries"]);const z=Symbol("cancelled");const $=Symbol("waitQueue");class Topology extends o{constructor(e,t){super();if(typeof t==="undefined"&&typeof e!=="string"){t=e;e=[];if(t.host){e.push({host:t.host,port:t.port})}}e=e||[];if(typeof e==="string"){e=parseStringSeedlist(e)}t=Object.assign({},T.TOPOLOGY_DEFAULTS,t);t=Object.freeze(Object.assign(t,{metadata:R(t),compression:{compressors:E(t)}}));j.forEach((e=>{if(t[e]){S(`The option \`${e}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}));const r=topologyTypeFromSeedlist(e,t);const o=U++;const i=e.reduce(((e,t)=>{if(t.domain_socket)t.host=t.domain_socket;const r=t.port?`${t.host}:${t.port}`:`${t.host}:27017`;e.set(r,new s(r));return e}),new Map);this[$]=new n;this.s={id:o,options:t,seedlist:e,state:V,description:new a(r,i,t.replicaSet,null,null,null,t),serverSelectionTimeoutMS:t.serverSelectionTimeoutMS,heartbeatFrequencyMS:t.heartbeatFrequencyMS,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS,Cursor:t.cursorFactory||d,bson:t.bson||new p([p.Binary,p.Code,p.DBRef,p.Decimal128,p.Double,p.Int32,p.Long,p.Map,p.MaxKey,p.MinKey,p.ObjectId,p.BSONRegExp,p.Symbol,p.Timestamp]),servers:new Map,sessionPool:new v(this),sessions:new Set,promiseLibrary:t.promiseLibrary||Promise,credentials:t.credentials,clusterTime:null,connectionTimers:new Set};this.serverApi=t.serverApi;if(t.srvHost){this.s.srvPoller=t.srvPoller||new B({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:t.srvHost,logger:t.logger,loggerLevel:t.loggerLevel});this.s.detectTopologyDescriptionChange=e=>{const t=e.previousDescription.type;const r=e.newDescription.type;if(t!==A.Sharded&&r===A.Sharded){this.s.handleSrvPolling=srvPollingHandler(this);this.s.srvPoller.on("srvRecordDiscovery",this.s.handleSrvPolling);this.s.srvPoller.start()}};this.on("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange)}this.setMaxListeners(Infinity)}get description(){return this.s.description}get parserType(){return p.native?"c++":"js"}connect(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.s.state===J){if(typeof t==="function"){t()}return}q(this,W);this.emit("topologyOpening",new c.TopologyOpeningEvent(this.s.id));this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,new a(A.Unknown),this.s.description));connectServers(this,Array.from(this.s.description.servers.values()));h.translate(e);const r=e.readPreference||h.primary;const connectHandler=e=>{if(e){this.close();if(typeof t==="function"){t(e)}else{this.emit("error",e)}return}q(this,J);this.emit("open",e,this);this.emit("connect",this);if(typeof t==="function")t(e,this)};if(this.s.credentials){this.command("admin.$cmd",{ping:1},{readPreference:r},connectHandler);return}this.selectServer(L(r),e,connectHandler)}close(e,t){if(typeof e==="function"){t=e;e={}}if(typeof e==="boolean"){e={force:e}}e=e||{};if(this.s.state===V||this.s.state===Y){if(typeof t==="function"){t()}return}q(this,Y);drainWaitQueue(this[$],new C("Topology closed"));O(this.s.connectionTimers);if(this.s.srvPoller){this.s.srvPoller.stop();if(this.s.handleSrvPolling){this.s.srvPoller.removeListener("srvRecordDiscovery",this.s.handleSrvPolling);delete this.s.handleSrvPolling}}if(this.s.detectTopologyDescriptionChange){this.removeListener("topologyDescriptionChanged",this.s.detectTopologyDescriptionChange);delete this.s.detectTopologyDescriptionChange}this.s.sessions.forEach((e=>e.endSession()));this.s.sessionPool.endAllPooledSessions((()=>{w(Array.from(this.s.servers.values()),((t,r)=>destroyServer(t,this,e,r)),(e=>{this.s.servers.clear();this.emit("topologyClosed",new c.TopologyClosedEvent(this.s.id));q(this,V);if(typeof t==="function"){t(e)}}))}))}selectServer(e,t,r){if(typeof t==="function"){r=t;if(typeof e!=="function"){t=e;let r;if(e instanceof h){r=e}else if(typeof e==="string"){r=new h(e)}else{h.translate(t);r=t.readPreference||h.primary}e=L(r)}else{t={}}}t=Object.assign({},{serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS},t);const n=this.description.type===A.Sharded;const o=t.session;const s=o&&o.transaction;if(n&&s&&s.server){r(undefined,s.server);return}let i=e;if(typeof e==="object"){const t=e.readPreference?e.readPreference:h.primary;i=L(t)}const a={serverSelector:i,transaction:s,callback:r};const c=t.serverSelectionTimeoutMS;if(c){a.timer=setTimeout((()=>{a[z]=true;a.timer=undefined;const e=new I(`Server selection timed out after ${c} ms`,this.description);a.callback(e)}),c)}this[$].push(a);processWaitQueue(this)}shouldCheckForSessionSupport(){if(this.description.type===A.Single){return!this.description.hasKnownServers}return!this.description.hasDataBearingServers}hasSessionSupport(){return this.description.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new m(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){if(!Array.isArray(e)){e=[e]}this.command("admin.$cmd",{endSessions:e},{readPreference:h.primaryPreferred,noResponse:true,serverApi:this.serverApi},(()=>{if(typeof t==="function")t()}))}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address)){return}if(isStaleServerDescription(this.s.description,e)){return}const t=this.s.description;const r=this.s.description.servers.get(e.address);const n=e.$clusterTime;if(n){y(this,n)}const o=r&&r.equals(e);this.s.description=this.s.description.update(e);if(this.s.description.compatibilityError){this.emit("error",new C(this.s.description.compatibilityError));return}if(!o){this.emit("serverDescriptionChanged",new c.ServerDescriptionChangedEvent(this.s.id,e.address,r,this.s.description.servers.get(e.address)))}updateServers(this,e);if(this[$].length>0){processWaitQueue(this)}if(!o){this.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){if(typeof e==="function")t=e,e=null;if(typeof t==="function")t(null,true)}logout(e){if(typeof e==="function")e(null,true)}insert(e,t,r,n){executeWriteOperation({topology:this,op:"insert",ns:e,ops:t},r,n)}update(e,t,r,n){executeWriteOperation({topology:this,op:"update",ns:e,ops:t},r,n)}remove(e,t,r,n){executeWriteOperation({topology:this,op:"remove",ns:e,ops:t},r,n)}command(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}h.translate(r);const o=r.readPreference||h.primary;this.selectServer(L(o),r,((o,s)=>{if(o){n(o);return}const i=!r.retrying;const a=!!r.retryWrites;const A=!!r.session;const c=s.supportsRetryableWrites;const l=!A||!r.session.inTransaction();const u=i&&a&&A&&c&&l&&isWriteCommand(t);const cb=(o,s)=>{if(!o)return n(null,s);if(!shouldRetryOperation(o)){return n(o)}if(u){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}return n(o)};if(u){r.session.incrementTransactionNumber();r.willRetryWrite=u}s.command(e,t,r,cb)}))}cursor(e,t,r){r=r||{};const n=r.topology||this;const o=r.cursorFactory||this.s.Cursor;h.translate(r);return new o(n,e,t,r)}get clientMetadata(){return this.s.options.metadata}isConnected(){return this.s.state===J}isDestroyed(){return this.s.state===V}unref(){N("`unref` is a noop and will be removed in the next major version")}lastIsMaster(){const e=Array.from(this.description.servers.values());if(e.length===0)return{};const t=e.filter((e=>e.type!==i.Unknown))[0];const r=t||{maxWireVersion:this.description.commonWireVersion};return r}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get bson(){return this.s.bson}}Object.defineProperty(Topology.prototype,"clusterTime",{enumerable:true,get:function(){return this.s.clusterTime},set:function(e){this.s.clusterTime=e}});Topology.prototype.destroy=g(Topology.prototype.close,"destroy() is deprecated, please use close() instead");const K=["findAndModify","insert","update","delete"];function isWriteCommand(e){return K.some((t=>e[t]))}function isStaleServerDescription(e,t){const r=e.servers.get(t.address);const n=r.topologyVersion;return D(n,t.topologyVersion)>0}function destroyServer(e,t,r,n){r=r||{};G.forEach((t=>e.removeAllListeners(t)));e.destroy(r,(()=>{t.emit("serverClosed",new c.ServerClosedEvent(t.s.id,e.description.address));P.forEach((t=>e.removeAllListeners(t)));if(typeof n==="function"){n()}}))}function parseStringSeedlist(e){return e.split(",").map((e=>({host:e.split(":")[0],port:e.split(":")[1]||27017})))}function topologyTypeFromSeedlist(e,t){if(t.directConnection){return A.Single}const r=t.replicaSet||t.setName||t.rs_name;if(r==null){return A.Unknown}return A.ReplicaSetNoPrimary}function randomSelection(e){return e[Math.floor(Math.random()*e.length)]}function createAndConnectServer(e,t,r){e.emit("serverOpening",new c.ServerOpeningEvent(e.s.id,t.address));const n=new l(t,e.s.options,e);u(n,e,P);n.on("descriptionReceived",e.serverUpdateHandler.bind(e));if(r){const t=setTimeout((()=>{_(t,e.s.connectionTimers);n.connect()}),r);e.s.connectionTimers.add(t);return n}n.connect();return n}function connectServers(e,t){e.s.servers=t.reduce(((t,r)=>{const n=createAndConnectServer(e,r);t.set(r.address,n);return t}),new Map)}function updateServers(e,t){if(t&&e.s.servers.has(t.address)){const r=e.s.servers.get(t.address);r.s.description=t}for(const t of e.description.servers.values()){if(!e.s.servers.has(t.address)){const r=createAndConnectServer(e,t);e.s.servers.set(t.address,r)}}for(const t of e.s.servers){const r=t[0];if(e.description.hasServer(r)){continue}const n=e.s.servers.get(r);e.s.servers.delete(r);destroyServer(n,e)}}function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.topology;const o=e.op;const s=e.ns;const i=e.ops;n.selectServer(F(),t,((n,a)=>{if(n){r(n,null);return}const A=!e.retrying;const c=!!t.retryWrites;const l=!!t.session;const u=a.supportsRetryableWrites;const h=!l||!t.session.inTransaction();const d=t.explain===undefined;const g=A&&c&&l&&u&&h&&d;const handler=(n,o)=>{if(!n)return r(null,o);if(!shouldRetryOperation(n)){n=Q(n);return r(n)}if(g){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}return r(n)};if(r.operationId){handler.operationId=r.operationId}if(g){t.session.incrementTransactionNumber();t.willRetryWrite=g}a[o](s,i,t,handler)}))}function shouldRetryOperation(e){return e instanceof C&&e.hasErrorLabel("RetryableWriteError")}function srvPollingHandler(e){return function handleSrvPolling(t){const r=e.s.description;e.s.description=e.s.description.updateFromSrvPollingEvent(t);if(e.s.description===r){return}updateServers(e);e.emit("topologyDescriptionChanged",new c.TopologyDescriptionChangedEvent(e.s.id,r,e.s.description))}}function drainWaitQueue(e,t){while(e.length){const r=e.shift();clearTimeout(r.timer);if(!r[z]){r.callback(t)}}}function processWaitQueue(e){if(e.s.state===V){drainWaitQueue(e[$],new C("Topology is closed, please connect"));return}const t=Array.from(e.description.servers.values());const r=e[$].length;for(let n=0;n0){e.s.servers.forEach((e=>process.nextTick((()=>e.requestCheck()))))}}e.exports={Topology:Topology}},7962:(e,t,r)=>{"use strict";const n=r(2291).ServerType;const o=r(750).ServerDescription;const s=r(7161);const i=r(2291).TopologyType;const a=s.MIN_SUPPORTED_SERVER_VERSION;const A=s.MAX_SUPPORTED_SERVER_VERSION;const c=s.MIN_SUPPORTED_WIRE_VERSION;const l=s.MAX_SUPPORTED_WIRE_VERSION;class TopologyDescription{constructor(e,t,r,o,s,u,h){h=h||{};this.type=e||i.Unknown;this.setName=r||null;this.maxSetVersion=o||null;this.maxElectionId=s||null;this.servers=t||new Map;this.stale=false;this.compatible=true;this.compatibilityError=null;this.logicalSessionTimeoutMinutes=null;this.heartbeatFrequencyMS=h.heartbeatFrequencyMS||0;this.localThresholdMS=h.localThresholdMS||0;this.commonWireVersion=u||null;Object.defineProperty(this,"options",{value:h,enumberable:false});for(const e of this.servers.values()){if(e.type===n.Unknown)continue;if(e.minWireVersion>l){this.compatible=false;this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${l} (MongoDB ${A})`}if(e.maxWireVersion=0){u.delete(t)}if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){const t=updateRsNoPrimaryFromMember(u,s,e);r=t[0],s=t[1]}}if(r===i.ReplicaSetWithPrimary){if([n.Standalone,n.Mongos].indexOf(l)>=0){u.delete(t);r=checkHasPrimary(u)}else if(l===n.RSPrimary){const t=updateRsFromPrimary(u,s,e,a,A);r=t[0],s=t[1],a=t[2],A=t[3]}else if([n.RSSecondary,n.RSArbiter,n.RSOther].indexOf(l)>=0){r=updateRsWithPrimaryFromMember(u,s,e)}else{r=checkHasPrimary(u)}}return new TopologyDescription(r,u,s,a,A,c,this.options)}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));if(e.length>0){return e[0].error}return undefined}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==n.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}}function topologyTypeForServerType(e){if(e===n.Standalone){return i.Single}if(e===n.Mongos){return i.Sharded}if(e===n.RSPrimary){return i.ReplicaSetWithPrimary}if(e===n.RSGhost||e===n.Unknown){return i.Unknown}return i.ReplicaSetNoPrimary}function compareObjectId(e,t){if(e==null){return-1}if(t==null){return 1}if(e.id instanceof Buffer&&t.id instanceof Buffer){const r=e.id;const n=t.id;return r.compare(n)}const r=e.toString();const n=t.toString();return r.localeCompare(n)}function updateRsFromPrimary(e,t,r,s,i){t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[checkHasPrimary(e),t,s,i]}const a=r.electionId?r.electionId:null;if(r.setVersion&&a){if(s&&i){if(s>r.setVersion||compareObjectId(i,a)>0){e.set(r.address,new o(r.address));return[checkHasPrimary(e),t,s,i]}}i=r.electionId}if(r.setVersion!=null&&(s==null||r.setVersion>s)){s=r.setVersion}for(const t of e.keys()){const s=e.get(t);if(s.type===n.RSPrimary&&s.address!==r.address){e.set(t,new o(s.address));break}}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));const A=Array.from(e.keys());const c=r.allHosts;A.filter((e=>c.indexOf(e)===-1)).forEach((t=>{e.delete(t)}));return[checkHasPrimary(e),t,s,i]}function updateRsWithPrimaryFromMember(e,t,r){if(t==null){throw new TypeError("setName is required")}if(t!==r.setName||r.me&&r.address!==r.me){e.delete(r.address)}return checkHasPrimary(e)}function updateRsNoPrimaryFromMember(e,t,r){let n=i.ReplicaSetNoPrimary;t=t||r.setName;if(t!==r.setName){e.delete(r.address);return[n,t]}r.allHosts.forEach((t=>{if(!e.has(t)){e.set(t,new o(t))}}));if(r.me&&r.address!==r.me){e.delete(r.address)}return[n,t]}function checkHasPrimary(e){for(const t of e.keys()){if(e.get(t).type===n.RSPrimary){return i.ReplicaSetWithPrimary}}return i.ReplicaSetNoPrimary}e.exports={TopologyDescription:TopologyDescription}},5474:(e,t,r)=>{"use strict";const n=r(7746).retrieveBSON;const o=r(2361);const s=n();const i=s.Binary;const a=r(1178).uuidV4;const A=r(3111).MongoError;const c=r(3111).isRetryableError;const l=r(3111).isRetryableEndTransactionError;const u=r(3111).MongoNetworkError;const h=r(3111).MongoWriteConcernError;const d=r(1707).Transaction;const g=r(1707).TxnState;const p=r(1178).isPromiseLike;const E=r(4485);const m=r(1371).maybePromise;const C=r(1707).isTransactionCommand;const I=r(2306).resolveClusterTime;const y=r(7272).isSharded;const B=r(1178).maxWireVersion;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;const w=8;function assertAlive(e,t){if(e.serverSession==null){const e=new A("Cannot use a session that has ended");if(typeof t==="function"){t(e,null);return false}throw e}return true}const S=Symbol("serverSession");class ClientSession extends o{constructor(e,t,r,n){super();if(e==null){throw new Error("ClientSession requires a topology")}if(t==null||!(t instanceof ServerSessionPool)){throw new Error("ClientSession requires a ServerSessionPool")}r=r||{};n=n||{};this.topology=e;this.sessionPool=t;this.hasEnded=false;this.clientOptions=n;this[S]=undefined;this.supports={causalConsistency:typeof r.causalConsistency!=="undefined"?r.causalConsistency:true};this.clusterTime=r.initialClusterTime;this.operationTime=null;this.explicit=!!r.explicit;this.owner=r.owner;this.defaultTransactionOptions=Object.assign({},r.defaultTransactionOptions);this.transaction=new d}get id(){return this.serverSession.id}get serverSession(){if(this[S]==null){this[S]=this.sessionPool.acquire()}return this[S]}endSession(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=this;return m(this,t,(e=>{if(r.hasEnded){return e()}function completeEndSession(){r.sessionPool.release(r.serverSession);r[S]=undefined;r.hasEnded=true;r.emit("ended",r);e()}if(r.serverSession&&r.inTransaction()){r.abortTransaction((t=>{if(t)return e(t);completeEndSession()}));return}completeEndSession()}))}advanceOperationTime(e){if(this.operationTime==null){this.operationTime=e;return}if(e.greaterThan(this.operationTime)){this.operationTime=e}}equals(e){if(!(e instanceof ClientSession)){return false}return this.id.id.buffer.equals(e.id.id.buffer)}incrementTransactionNumber(){this.serverSession.txnNumber++}inTransaction(){return this.transaction.isActive}startTransaction(e){assertAlive(this);if(this.inTransaction()){throw new A("Transaction already in progress")}const t=B(this.topology);if(y(this.topology)&&t!=null&&tendTransaction(this,"commitTransaction",e)))}abortTransaction(e){return m(this,e,(e=>endTransaction(this,"abortTransaction",e)))}toBSON(){throw new Error("ClientSession cannot be serialized to BSON.")}withTransaction(e,t){const r=Q();return attemptTransaction(this,r,e,t)}}const v=12e4;const R=100;const k=79;const D=50;const N=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function hasNotTimedOut(e,t){return b(e){if(o instanceof A&&hasNotTimedOut(t,v)&&!isMaxTimeMSExpiredError(o)){if(o.hasErrorLabel("UnknownTransactionCommitResult")){return attemptTransactionCommit(e,t,r,n)}if(o.hasErrorLabel("TransientTransactionError")){return attemptTransaction(e,t,r,n)}}throw o}))}const T=new Set([g.NO_TRANSACTION,g.TRANSACTION_COMMITTED,g.TRANSACTION_ABORTED]);function userExplicitlyEndedTransaction(e){return T.has(e.transaction.state)}function attemptTransaction(e,t,r,n){e.startTransaction(n);let o;try{o=r(e)}catch(e){o=Promise.reject(e)}if(!p(o)){e.abortTransaction();throw new TypeError("Function provided to `withTransaction` must return a Promise")}return o.then((()=>{if(userExplicitlyEndedTransaction(e)){return}return attemptTransactionCommit(e,t,r,n)})).catch((o=>{function maybeRetryOrThrow(o){if(o instanceof A&&o.hasErrorLabel("TransientTransactionError")&&hasNotTimedOut(t,v)){return attemptTransaction(e,t,r,n)}if(isMaxTimeMSExpiredError(o)){o.addErrorLabel("UnknownTransactionCommitResult")}throw o}if(e.transaction.isActive){return e.abortTransaction().then((()=>maybeRetryOrThrow(o)))}return maybeRetryOrThrow(o)}))}function endTransaction(e,t,r){if(!assertAlive(e,r)){return}let n=e.transaction.state;if(n===g.NO_TRANSACTION){r(new A("No transaction started"));return}if(t==="commitTransaction"){if(n===g.STARTING_TRANSACTION||n===g.TRANSACTION_COMMITTED_EMPTY){e.transaction.transition(g.TRANSACTION_COMMITTED_EMPTY);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call commitTransaction after calling abortTransaction"));return}}else{if(n===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_ABORTED);r(null,null);return}if(n===g.TRANSACTION_ABORTED){r(new A("Cannot call abortTransaction twice"));return}if(n===g.TRANSACTION_COMMITTED||n===g.TRANSACTION_COMMITTED_EMPTY){r(new A("Cannot call abortTransaction after calling commitTransaction"));return}}const o={[t]:1};let s;if(e.transaction.options.writeConcern){s=Object.assign({},e.transaction.options.writeConcern)}else if(e.clientOptions&&e.clientOptions.w){s={w:e.clientOptions.w}}if(n===g.TRANSACTION_COMMITTED){s=Object.assign({wtimeout:1e4},s,{w:"majority"})}if(s){Object.assign(o,{writeConcern:s})}if(t==="commitTransaction"&&e.transaction.options.maxTimeMS){Object.assign(o,{maxTimeMS:e.transaction.options.maxTimeMS})}function commandHandler(n,o){if(t==="commitTransaction"){e.transaction.transition(g.TRANSACTION_COMMITTED);if(n){if(n instanceof u||n instanceof h||c(n)||isMaxTimeMSExpiredError(n)){if(isUnknownTransactionCommitResult(n)){n.addErrorLabel("UnknownTransactionCommitResult");e.transaction.unpinServer()}}else if(n.hasErrorLabel("TransientTransactionError")){e.transaction.unpinServer()}}}else{e.transaction.transition(g.TRANSACTION_ABORTED)}r(n,o)}function transactionError(e){return t==="commitTransaction"?e:null}if(e.transaction.recoveryToken&&supportsRecoveryToken(e)){o.recoveryToken=e.transaction.recoveryToken}e.topology.command("admin.$cmd",o,{session:e},((t,r)=>{if(t&&l(t)){if(o.commitTransaction){e.transaction.unpinServer();o.writeConcern=Object.assign({wtimeout:1e4},o.writeConcern,{w:"majority"})}return e.topology.command("admin.$cmd",o,{session:e},((e,t)=>commandHandler(transactionError(e),t)))}commandHandler(transactionError(t),r)}))}function supportsRecoveryToken(e){const t=e.topology;return!!t.s.options.useRecoveryToken}class ServerSession{constructor(){this.id={id:new i(a(),i.SUBTYPE_UUID)};this.lastUse=Q();this.txnNumber=0;this.isDirty=false}hasTimedOut(e){const t=Math.round(b(this.lastUse)%864e5%36e5/6e4);return t>e-1}}class ServerSessionPool{constructor(e){if(e==null){throw new Error("ServerSessionPool requires a topology")}this.topology=e;this.sessions=[]}endAllPooledSessions(e){if(this.sessions.length){this.topology.endSessions(this.sessions.map((e=>e.id)),(()=>{this.sessions=[];if(typeof e==="function"){e()}}));return}if(typeof e==="function"){e()}}acquire(){const e=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const t=this.sessions.shift();if(!t.hasTimedOut(e)){return t}}return new ServerSession}release(e){const t=this.topology.logicalSessionTimeoutMinutes;while(this.sessions.length){const e=this.sessions[this.sessions.length-1];if(e.hasTimedOut(t)){this.sessions.pop()}else{break}}if(!e.hasTimedOut(t)){if(e.isDirty){return}this.sessions.unshift(e)}}}function commandSupportsReadConcern(e,t){if(e.aggregate||e.count||e.distinct||e.find||e.parallelCollectionScan||e.geoNear||e.geoSearch){return true}if(e.mapReduce&&t&&t.out&&(t.out.inline===1||t.out==="inline")){return true}return false}function applySession(e,t,r){if(e.hasEnded){return new A("Cannot use a session that has ended")}if(r&&r.writeConcern&&r.writeConcern.w===0){return}const n=e.serverSession;n.lastUse=Q();t.lsid=n.id;const o=e.inTransaction()||C(t);const i=r.willRetryWrite;const a=commandSupportsReadConcern(t,r);if(n.txnNumber&&(i||o)){t.txnNumber=s.Long.fromNumber(n.txnNumber)}if(!o){if(e.transaction.state!==g.NO_TRANSACTION){e.transaction.transition(g.NO_TRANSACTION)}if(e.supports.causalConsistency&&e.operationTime&&a){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}return}if(r.readPreference&&!r.readPreference.equals(E.primary)){return new A(`Read preference in a transaction must be primary, not: ${r.readPreference.mode}`)}t.autocommit=false;if(e.transaction.state===g.STARTING_TRANSACTION){e.transaction.transition(g.TRANSACTION_IN_PROGRESS);t.startTransaction=true;const r=e.transaction.options.readConcern||e.clientOptions.readConcern;if(r){t.readConcern=r}if(e.supports.causalConsistency&&e.operationTime){t.readConcern=t.readConcern||{};Object.assign(t.readConcern,{afterClusterTime:e.operationTime})}}}function updateSessionFromResponse(e,t){if(t.$clusterTime){I(e,t.$clusterTime)}if(t.operationTime&&e&&e.supports.causalConsistency){e.advanceOperationTime(t.operationTime)}if(t.recoveryToken&&e&&e.inTransaction()){e.transaction._recoveryToken=t.recoveryToken}}e.exports={ClientSession:ClientSession,ServerSession:ServerSession,ServerSessionPool:ServerSessionPool,TxnState:g,applySession:applySession,updateSessionFromResponse:updateSessionFromResponse,commandSupportsReadConcern:commandSupportsReadConcern}},8175:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4847).CoreCursor;const a=r(104);const A=r(7746).retrieveBSON;const c=r(3111).MongoError;const l=r(6495);const u=r(2306).diff;const h=r(2306).cloneOptions;const d=r(2306).SessionMixins;const g=r(2306).isRetryableWritesSupported;const p=r(1178).relayEvents;const E=A();const m=r(2306).getMMAPError;const C=r(1178).makeClientMetadata;const I=r(2306).legacyIsRetryableWriteError;var y="disconnected";var B="connecting";var Q="connected";var b="unreferenced";var w="destroying";var S="destroyed";function stateTransition(e,t){var r={disconnected:[B,w,S,y],connecting:[B,w,S,Q,y],connected:[Q,y,w,S,b],unreferenced:[b,w,S],destroyed:[S]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{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 v=1;var R=["connect","close","error","timeout","parseError"];var Mongos=function(e,t){t=t||{};this.id=v++;if(Array.isArray(e)){e=e.reduce(((e,t)=>{if(e.find((e=>e.host===t.host&&e.port===t.port))){return e}e.push(t);return e}),[])}this.s={options:Object.assign({metadata:C(t)},t),bson:t.bson||new E([E.Binary,E.Code,E.DBRef,E.Decimal128,E.Double,E.Int32,E.Long,E.Map,E.MaxKey,E.MinKey,E.ObjectId,E.BSONRegExp,E.Symbol,E.Timestamp]),Cursor:t.cursorFactory||i,logger:a("Mongos",t),seedlist:e,haInterval:t.haInterval?t.haInterval:1e4,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false,localThresholdMS:t.localThresholdMS||15};if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeout0){e.emit(t,r)}}const k=["serverDescriptionChanged","error","close","timeout","parseError"];function destroyServer(e,t,r){t=t||{};k.forEach((t=>e.removeAllListeners(t)));e.destroy(t,r)}Mongos.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,B);var r=this.s.seedlist.map((function(r){const n=new l(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,parent:t}));p(n,t,["serverDescriptionChanged"]);return n}));emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectProxies(t,r)};Mongos.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};function handleEvent(e){return function(){if(e.state===S||e.state===w){return}moveServerFrom(e.connectedProxies,e.disconnectedProxies,this);emitTopologyDescriptionChanged(e);e.emit("left","mongos",this);e.emit("serverClosed",{topologyId:e.id,address:this.name})}}function handleInitialConnectEvent(e,t){return function(){var r=this;if(e.state===S){emitTopologyDescriptionChanged(e);moveServerFrom(e.connectingProxies,e.disconnectedProxies,this);return this.destroy()}if(t==="connect"){e.ismaster=r.lastIsMaster();if(e.ismaster.msg==="isdbgrid"){for(let t=0;t0&&e.state===B){stateTransition(e,Q);e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.disconnectedProxies.length===0){if(e.s.logger.isWarn()){e.s.logger.warn(o("no mongos proxies found in seed list, did you mean to connect to a replicaset"))}return e.emit("error",new c("no mongos proxies found in seed list"))}topologyMonitor(e,{firstConnect:true})}}}function connectProxies(e,t){e.connectingProxies=e.connectingProxies.concat(t);var r=0;function connect(t,r){setTimeout((function(){e.emit("serverOpening",{topologyId:e.id,address:t.name});emitTopologyDescriptionChanged(e);t.once("close",handleInitialConnectEvent(e,"close"));t.once("timeout",handleInitialConnectEvent(e,"timeout"));t.once("parseError",handleInitialConnectEvent(e,"parseError"));t.once("error",handleInitialConnectEvent(e,"error"));t.once("connect",handleInitialConnectEvent(e,"connect"));p(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}t.forEach((e=>connect(e,r++)))}function pickProxy(e,t){const r=t&&t.transaction;if(r&&r.server){if(r.server.isConnected()){return r.server}else{r.unpinServer()}}var n=e.connectedProxies.slice(0);var o=Number.MAX_VALUE;for(var s=0;s0&&e.state===B){e.emit("error",new c("no mongos proxy available"))}else{e.emit("close",e)}return reconnectProxies(e,e.disconnectedProxies,(function(){if(e.state===S||e.state===w||e.state===b){return}if(e.state===B&&t.firstConnect){e.emit("connect",e);e.emit("fullsetup",e);e.emit("all",e)}else if(e.isConnected()){e.emit("reconnect",e)}else if(!e.isConnected()&&e.listeners("close").length>0){e.emit("close",e)}topologyMonitor(e)}))}for(var o=0;o{n--;if(n>0){return}emitTopologyDescriptionChanged(this);emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});stateTransition(this,S);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>{this.emit("serverClosed",{topologyId:this.id,address:t.name});destroyServer(t,e,serverDestroyed);moveServerFrom(this.connectedProxies,this.disconnectedProxies,t)}))};Mongos.prototype.isConnected=function(){return this.connectedProxies.length>0};Mongos.prototype.isDestroyed=function(){return this.state===S};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const o=e.op;const s=e.ns;const i=e.ops;let a=pickProxy(n,t.session);if(!a)return r(new c("no mongos proxy available"));const A=!e.retrying&&!!t.retryWrites&&t.session&&g(n)&&!t.session.inTransaction()&&t.explain===undefined;const handler=(o,s)=>{if(!o)return r(null,s);if(!I(o,n)||!A){o=m(o);return r(o)}a=pickProxy(n,t.session);if(!a){return r(o)}const i=Object.assign({},e,{retrying:true});return executeWriteOperation(i,t,r)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}a[o](s,i,t,handler)}Mongos.prototype.insert=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("insert",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};Mongos.prototype.update=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("update",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};Mongos.prototype.remove=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}if(!this.isConnected()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("remove",e,t,r,n)}if(!this.isConnected()){return n(new c("no mongos proxy available"))}executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const D=["findAndModify","insert","update","delete"];function isWriteCommand(e){return D.some((t=>e[t]))}Mongos.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===S){return n(new c(o("topology was destroyed")))}var s=this;var i=pickProxy(s,r.session);if((i==null||!i.isConnected())&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}if(i==null){return n(new c("no mongos proxy available"))}var a=h(r);a.topology=s;const A=!r.retrying&&r.retryWrites&&r.session&&g(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(r,o)=>{if(!r)return n(null,o);if(!I(r,s)){return n(r)}if(A){const r=Object.assign({},a,{retrying:true});return this.command(e,t,r,n)}return n(r)};if(A){a.session.incrementTransactionNumber();a.willRetryWrite=A}i.command(e,t,a,cb)};Mongos.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Mongos.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;t=t||{};const n=pickProxy(this,t.session);if(n==null){r(new c("server selection failed"));return}if(this.s.debug)this.emit("pickedServer",null,n);r(null,n)};Mongos.prototype.connections=function(){var e=[];for(var t=0;t0){var t="Unknown";if(e.connectedProxies.length>0){t="Sharded"}var r={topologyType:t,servers:[]};var n=e.disconnectedProxies.concat(e.connectingProxies);r.servers=r.servers.concat(n.map((function(e){var t=e.getDescription();t.type="Unknown";return t})));r.servers=r.servers.concat(e.connectedProxies.map((function(e){var t=e.getDescription();t.type="Mongos";return t})));var o=u(e.topologyDescription,r);var s={topologyId:e.id,previousDescription:e.topologyDescription,newDescription:r,diff:o};if(o.servers.length>0){e.emit("topologyDescriptionChanged",s)}e.topologyDescription=r}}e.exports=Mongos},4485:(e,t,r)=>{"use strict";const n=r(1371).emitWarningOnce;const ReadPreference=function(e,t,r){if(!ReadPreference.isValid(e)){throw new TypeError(`Invalid read preference mode ${e}`)}if(t&&!Array.isArray(t)){n("ReadPreference tags must be an array, this will change in the next major version");const e=typeof t.maxStalenessSeconds!=="undefined";const o=typeof t.hedge!=="undefined";const s=e||o;if(s){r=t;t=undefined}else{t=[t]}}this.mode=e;this.tags=t;this.hedge=r&&r.hedge;r=r||{};if(r.maxStalenessSeconds!=null){if(r.maxStalenessSeconds<=0){throw new TypeError("maxStalenessSeconds must be a positive integer")}this.maxStalenessSeconds=r.maxStalenessSeconds;this.minWireVersion=5}if(this.mode===ReadPreference.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(ReadPreference.prototype,"preference",{enumerable:true,get:function(){return this.mode}});ReadPreference.PRIMARY="primary";ReadPreference.PRIMARY_PREFERRED="primaryPreferred";ReadPreference.SECONDARY="secondary";ReadPreference.SECONDARY_PREFERRED="secondaryPreferred";ReadPreference.NEAREST="nearest";const o=[ReadPreference.PRIMARY,ReadPreference.PRIMARY_PREFERRED,ReadPreference.SECONDARY,ReadPreference.SECONDARY_PREFERRED,ReadPreference.NEAREST,null];ReadPreference.fromOptions=function(e){if(!e)return null;const t=e.readPreference;if(!t)return null;const r=e.readPreferenceTags;const n=e.maxStalenessSeconds;if(typeof t==="string"){return new ReadPreference(t,r)}else if(!(t instanceof ReadPreference)&&typeof t==="object"){const e=t.mode||t.preference;if(e&&typeof e==="string"){return new ReadPreference(e,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds||n,hedge:t.hedge})}}return t};ReadPreference.resolve=function(e,t){t=t||{};const r=t.session;const n=e&&e.readPreference;let o;if(t.readPreference){o=ReadPreference.fromOptions(t)}else if(r&&r.inTransaction()&&r.transaction.options.readPreference){o=r.transaction.options.readPreference}else if(n!=null){o=n}else{o=ReadPreference.primary}return typeof o==="string"?new ReadPreference(o):o};ReadPreference.translate=function(e){if(e.readPreference==null)return e;const t=e.readPreference;if(typeof t==="string"){e.readPreference=new ReadPreference(t)}else if(t&&!(t instanceof ReadPreference)&&typeof t==="object"){const r=t.mode||t.preference;if(r&&typeof r==="string"){e.readPreference=new ReadPreference(r,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds})}}else if(!(t instanceof ReadPreference)){throw new TypeError("Invalid read preference: "+t)}return e};ReadPreference.isValid=function(e){return o.indexOf(e)!==-1};ReadPreference.prototype.isValid=function(e){return ReadPreference.isValid(typeof e==="string"?e:this.mode)};const s=["primaryPreferred","secondary","secondaryPreferred","nearest"];ReadPreference.prototype.slaveOk=function(){return s.indexOf(this.mode)!==-1};ReadPreference.prototype.equals=function(e){return e.mode===this.mode};ReadPreference.prototype.toJSON=function(){const e={mode:this.mode};if(Array.isArray(this.tags))e.tags=this.tags;if(this.maxStalenessSeconds)e.maxStalenessSeconds=this.maxStalenessSeconds;if(this.hedge)e.hedge=this.hedge;return e};ReadPreference.primary=new ReadPreference("primary");ReadPreference.primaryPreferred=new ReadPreference("primaryPreferred");ReadPreference.secondary=new ReadPreference("secondary");ReadPreference.secondaryPreferred=new ReadPreference("secondaryPreferred");ReadPreference.nearest=new ReadPreference("nearest");e.exports=ReadPreference},1134:(e,t,r)=>{"use strict";const n=r(3837).inherits;const o=r(3837).format;const s=r(2361).EventEmitter;const i=r(4485);const a=r(4847).CoreCursor;const A=r(7746).retrieveBSON;const c=r(104);const l=r(3111).MongoError;const u=r(6495);const h=r(8742);const d=r(2306).Timeout;const g=r(2306).Interval;const p=r(2306).SessionMixins;const E=r(2306).isRetryableWritesSupported;const m=r(1178).relayEvents;const C=A();const I=r(2306).getMMAPError;const y=r(1178).makeClientMetadata;const B=r(2306).legacyIsRetryableWriteError;const Q=r(1371).now;const b=r(1371).calculateDurationInMs;var w="disconnected";var S="connecting";var v="connected";var R="unreferenced";var k="destroyed";function stateTransition(e,t){var r={disconnected:[S,k,w],connecting:[S,k,v,w],connected:[v,w,k,R],unreferenced:[R,k],destroyed:[k]};var n=r[e.state];if(n&&n.indexOf(t)!==-1){e.state=t}else{e.s.logger.error(o("Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]",e.id,e.state,t,n))}}var D=1;var N=["connect","close","error","timeout","parseError"];var ReplSet=function(e,t){var r=this;t=t||{};if(!Array.isArray(e))throw new l("seedlist must be an array");if(e.length===0)throw new l("seedlist must contain at least one entry");e.forEach((function(e){if(typeof e.host!=="string"||typeof e.port!=="number")throw new l("seedlist entry must contain a host and port")}));s.call(this);this.id=D++;var n=t.localThresholdMS||15;if(t.acceptableLatency)n=t.acceptableLatency;var i=c("ReplSet",t);this.s={options:Object.assign({metadata:y(t)},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]),Cursor:t.cursorFactory||a,logger:i,seedlist:e,replicaSetState:new h({id:this.id,setName:t.setName,acceptableLatency:n,heartbeatFrequencyMS:t.haInterval?t.haInterval:1e4,logger:i}),connectingServers:[],haInterval:t.haInterval?t.haInterval:1e4,minHeartbeatFrequencyMS:500,disconnectHandler:t.disconnectHandler,index:0,connectOptions:{},debug:typeof t.debug==="boolean"?t.debug:false};this.s.replicaSetState.on("topologyDescriptionChanged",(function(e){r.emit("topologyDescriptionChanged",e)}));if(this.s.logger.isWarn()&&this.s.options.socketTimeout!==0&&this.s.options.socketTimeoute.name===t));if(r>=0){const t=e.s.connectingServers[r];t.destroy({force:true});e.s.connectingServers.splice(r,1);return done()}var n=new u(Object.assign({},e.s.options,{host:t.split(":")[0],port:parseInt(t.split(":")[1],10),reconnect:false,monitoring:false,parent:e}));n.once("connect",_handleEvent(e,"connect"));n.once("close",_handleEvent(e,"close"));n.once("timeout",_handleEvent(e,"timeout"));n.once("error",_handleEvent(e,"error"));n.once("parseError",_handleEvent(e,"parseError"));n.on("serverOpening",(t=>e.emit("serverOpening",t)));n.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));n.on("serverClosed",(t=>e.emit("serverClosed",t)));m(n,e,["commandStarted","commandSucceeded","commandFailed"]);e.s.connectingServers.push(n);n.connect(e.s.connectOptions)}),r)}for(var s=0;se.emit("serverOpening",t)));t.on("serverDescriptionChanged",(t=>e.emit("serverDescriptionChanged",t)));t.on("serverClosed",(t=>e.emit("serverClosed",t)));m(t,e,["commandStarted","commandSucceeded","commandFailed"]);t.connect(e.s.connectOptions)}),r)}while(t.length>0){connect(t.shift(),r++)}}function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}ReplSet.prototype.connect=function(e){var t=this;this.s.connectOptions=e||{};stateTransition(this,S);var r=this.s.seedlist.map((function(r){return new u(Object.assign({},t.s.options,r,e,{reconnect:false,monitoring:false,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)))}emitSDAMEvent(this,"topologyOpening",{topologyId:this.id});connectServers(t,r)};ReplSet.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};ReplSet.prototype.destroy=function(e,t){if(typeof e==="function"){t=e;e={}}e=e||{};let r=this.s.connectingServers.length+1;const serverDestroyed=()=>{r--;if(r>0){return}emitSDAMEvent(this,"topologyClosed",{topologyId:this.id});if(typeof t==="function"){t(null,null)}};if(this.state===k){if(typeof t==="function")t(null,null);return}stateTransition(this,k);if(this.haTimeoutId)clearTimeout(this.haTimeoutId);for(var n=0;n{if(b(s)>=T){if(o!=null){r(o,null)}else{r(new l("Server selection timed out"))}return}const e=this.s.replicaSetState.pickServer(n);if(e==null){setTimeout(_selectServer,O);return}if(!(e instanceof u)){o=e;setTimeout(_selectServer,O);return}if(this.s.debug)this.emit("pickedServer",t.readPreference,e);r(null,e)};_selectServer()};ReplSet.prototype.getServers=function(){return this.s.replicaSetState.allServers()};function executeWriteOperation(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=e.self;const s=e.op;const i=e.ns;const a=e.ops;if(n.state===k){return r(new l(o("topology was destroyed")))}const A=!e.retrying&&!!t.retryWrites&&t.session&&E(n)&&!t.session.inTransaction()&&t.explain===undefined;if(!n.s.replicaSetState.hasPrimary()){if(n.s.disconnectHandler){return n.s.disconnectHandler.add(s,i,a,t,r)}else if(!A){return r(new l("no primary server found"))}}const handler=(o,s)=>{if(!o)return r(null,s);if(!B(o,n)){o=I(o);return r(o)}if(A){const n=Object.assign({},e,{retrying:true});return executeWriteOperation(n,t,r)}if(n.s.replicaSetState.primary){n.s.replicaSetState.primary.destroy();n.s.replicaSetState.remove(n.s.replicaSetState.primary,{force:true})}return r(o)};if(r.operationId){handler.operationId=r.operationId}if(A){t.session.incrementTransactionNumber();t.willRetryWrite=A}n.s.replicaSetState.primary[s](i,a,t,handler)}ReplSet.prototype.insert=function(e,t,r,n){executeWriteOperation({self:this,op:"insert",ns:e,ops:t},r,n)};ReplSet.prototype.update=function(e,t,r,n){executeWriteOperation({self:this,op:"update",ns:e,ops:t},r,n)};ReplSet.prototype.remove=function(e,t,r,n){executeWriteOperation({self:this,op:"remove",ns:e,ops:t},r,n)};const _=["findAndModify","insert","update","delete"];function isWriteCommand(e){return _.some((t=>e[t]))}ReplSet.prototype.command=function(e,t,r,n){if(typeof r==="function"){n=r,r={},r=r||{}}if(this.state===k)return n(new l(o("topology was destroyed")));var s=this;var a=r.readPreference?r.readPreference:i.primary;if(a.preference==="primary"&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference==="secondary"&&!this.s.replicaSetState.hasSecondary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}else if(a.preference!=="primary"&&!this.s.replicaSetState.hasSecondary()&&!this.s.replicaSetState.hasPrimary()&&this.s.disconnectHandler!=null){return this.s.disconnectHandler.add("command",e,t,r,n)}var A=this.s.replicaSetState.pickServer(a);if(!(A instanceof u))return n(A);if(s.s.debug)s.emit("pickedServer",i.primary,A);if(A==null){return n(new l(o("no server found that matches the provided readPreference %s",a)))}const c=!r.retrying&&!!r.retryWrites&&r.session&&E(s)&&!r.session.inTransaction()&&isWriteCommand(t);const cb=(o,i)=>{if(!o)return n(null,i);if(!B(o,s)){return n(o)}if(c){const o=Object.assign({},r,{retrying:true});return this.command(e,t,o,n)}if(this.s.replicaSetState.primary){this.s.replicaSetState.primary.destroy();this.s.replicaSetState.remove(this.s.replicaSetState.primary,{force:true})}return n(o)};if(c){r.session.incrementTransactionNumber();r.willRetryWrite=c}A.command(e,t,r,cb)};ReplSet.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};e.exports=ReplSet},8742:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2306).diff,i=r(2361).EventEmitter,a=r(104),A=r(4485),c=r(3111).MongoError,l=r(1867).Buffer;var u={Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown"};var h={Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown"};var ReplSetState=function(e){e=e||{};i.call(this);this.topologyType=e.setName?u.ReplicaSetNoPrimary:u.Unknown;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=undefined};n(ReplSetState,i);ReplSetState.prototype.hasPrimaryAndSecondary=function(){return this.primary!=null&&this.secondaries.length>0};ReplSetState.prototype.hasPrimaryOrSecondary=function(){return this.hasPrimary()||this.hasSecondary()};ReplSetState.prototype.hasPrimary=function(){return this.primary!=null};ReplSetState.prototype.hasSecondary=function(){return this.secondaries.length>0};ReplSetState.prototype.get=function(e){var t=this.allServers();for(var r=0;r{n--;if(n>0){return}this.secondaries=[];this.arbiters=[];this.passives=[];this.ghosts=[];this.unknownServers=[];this.set={};this.primary=null;emitTopologyDescriptionChanged(this);if(typeof t==="function"){t(null,null)}};if(n===0){serverDestroyed();return}r.forEach((t=>t.destroy(e,serverDestroyed)))};ReplSetState.prototype.remove=function(e,t){t=t||{};var r=e.name.toLowerCase();var n=this.primary?[this.primary]:[];n=n.concat(this.secondaries);n=n.concat(this.arbiters);n=n.concat(this.passives);for(var o=0;oe.arbiterOnly&&e.setName;ReplSetState.prototype.update=function(e){var t=this;const r=e.lastIsMaster();if(r&&r.isWritablePrimary)r.ismaster=r.isWritablePrimary;var n=e.name.toLowerCase();if(r){var s=Array.isArray(r.hosts)?r.hosts:[];s=s.concat(Array.isArray(r.arbiters)?r.arbiters:[]);s=s.concat(Array.isArray(r.passives)?r.passives:[]);s=s.map((function(e){return e.toLowerCase()}));for(var i=0;il){return false}}else if(!p&&a&&l){if(l=5&&e.ismaster.secondary&&this.hasPrimary()){e.staleness=e.lastUpdateTime-e.lastWriteDate-(this.primary.lastUpdateTime-this.primary.lastWriteDate)+t}else if(e.ismaster.maxWireVersion>=5&&e.ismaster.secondary){e.staleness=r-e.lastWriteDate+t}};ReplSetState.prototype.updateSecondariesMaxStaleness=function(e){for(var t=0;t0&&e.maxStalenessSeconds==null){var o=pickNearest(this,e);if(o){return o}}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e);if(o){return o}}if(e.equals(A.secondaryPreferred)){return this.primary}return null}if(e.equals(A.primaryPreferred)){o=null;if(this.primary){return this.primary}if(n.length>0&&e.maxStalenessSeconds==null){o=pickNearest(this,e)}else if(n.length>0&&e.maxStalenessSeconds!=null){o=pickNearestMaxStalenessSeconds(this,e)}if(o)return o}return this.primary};var filterByTags=function(e,t){if(e.tags==null)return t;var r=[];var n=Array.isArray(e.tags)?e.tags:[e.tags];for(var o=0;o0?r[0].lastIsMasterMS:0;r=r.filter((function(t){return t.lastIsMasterMS<=o+e.acceptableLatency}));if(r.length===0){return null}e.index=e.index%r.length;var s=r[e.index];e.index=e.index+1;return s}function inList(e,t,r){for(var n=0;n0){var t="Unknown";var r=e.setName;if(e.hasPrimaryAndSecondary()){t="ReplicaSetWithPrimary"}else if(!e.hasPrimary()&&e.hasSecondary()){t="ReplicaSetNoPrimary"}var n={topologyType:t,setName:r,servers:[]};if(e.hasPrimary()){var o=e.primary.getDescription();o.type="RSPrimary";n.servers.push(o)}n.servers=n.servers.concat(e.secondaries.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));n.servers=n.servers.concat(e.arbiters.map((function(e){var t=e.getDescription();t.type="RSArbiter";return t})));n.servers=n.servers.concat(e.passives.map((function(e){var t=e.getDescription();t.type="RSSecondary";return t})));var i=s(e.replicasetDescription,n);var a={topologyId:e.id,previousDescription:e.replicasetDescription,newDescription:n,diff:i};e.emit("topologyDescriptionChanged",a);e.replicasetDescription=n}}e.exports=ReplSetState},6495:(e,t,r)=>{"use strict";var n=r(3837).inherits,o=r(3837).format,s=r(2361).EventEmitter,i=r(4485),a=r(104),A=r(7746).debugOptions,c=r(7746).retrieveBSON,l=r(5500),u=r(3111).MongoError,h=r(3111).MongoNetworkError,d=r(9206),g=r(4847).CoreCursor,p=r(2306),E=r(2306).createCompressionInfo,m=r(2306).resolveClusterTime,C=r(2306).SessionMixins,I=r(7703).extractCommand,y=r(1178).relayEvents;const B=r(1178).collationNotSupported;const Q=r(1178).makeClientMetadata;var b=["reconnect","reconnectTries","reconnectInterval","emitError","cursorFactory","host","port","size","keepAlive","keepAliveInitialDelay","noDelay","connectionTimeout","checkServerIdentity","socketTimeout","ssl","ca","crl","cert","key","rejectUnauthorized","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","servername"];var w=0;var S=false;var v={};var R=c();function topologyId(e){return e.s.parent==null?e.id:e.s.parent.id}var Server=function(e){e=e||{};s.call(this);this.id=w++;this.s={options:Object.assign({metadata:Q(e)},e),logger:a("Server",e),Cursor:e.cursorFactory||g,bson:e.bson||new R([R.Binary,R.Code,R.DBRef,R.Decimal128,R.Double,R.Int32,R.Long,R.Map,R.MaxKey,R.MinKey,R.ObjectId,R.BSONRegExp,R.Symbol,R.Timestamp]),pool:null,disconnectHandler:e.disconnectHandler,monitoring:typeof e.monitoring==="boolean"?e.monitoring:true,inTopology:!!e.parent,monitoringInterval:typeof e.monitoringInterval==="number"?e.monitoringInterval:5e3,compression:{compressors:E(e)},parent:e.parent};if(!this.s.parent){this.s.clusterTime=null}this.ismaster=null;this.lastIsMasterMS=-1;this.monitoringProcessId=null;this.initialConnect=true;this._type="server";this.lastUpdateTime=0;this.lastWriteDate=0;this.staleness=0};n(Server,s);Object.assign(Server.prototype,C);Object.defineProperty(Server.prototype,"type",{enumerable:true,get:function(){return this._type}});Object.defineProperty(Server.prototype,"parserType",{enumerable:true,get:function(){return R.native?"c++":"js"}});Object.defineProperty(Server.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){if(!this.ismaster)return null;return this.ismaster.logicalSessionTimeoutMinutes||null}});Object.defineProperty(Server.prototype,"clientMetadata",{enumerable:true,get:function(){return this.s.options.metadata}});Object.defineProperty(Server.prototype,"clusterTime",{enumerable:true,set:function(e){const t=this.s.parent?this.s.parent:this.s;m(t,e)},get:function(){const e=this.s.parent?this.s.parent:this.s;return e.clusterTime||null}});Server.enableServerAccounting=function(){S=true;v={}};Server.disableServerAccounting=function(){S=false};Server.servers=function(){return v};Object.defineProperty(Server.prototype,"name",{enumerable:true,get:function(){return this.s.options.host+":"+this.s.options.port}});function disconnectHandler(e,t,r,n,s,i){if(!e.s.pool.isConnected()&&e.s.options.reconnect&&e.s.disconnectHandler!=null&&!s.monitoring){e.s.disconnectHandler.add(t,r,n,s,i);return true}if(!e.s.pool.isConnected()){i(new u(o("no connection available to server %s",e.name)));return true}}function monitoringProcess(e){return function(){if(e.s.pool.isDestroyed())return;e.emit("monitoring",e);var t=(new Date).getTime();e.command("admin.$cmd",{ismaster:true},{socketTimeout:typeof e.s.options.connectionTimeout!=="number"?2e3:e.s.options.connectionTimeout,monitoring:true},((r,n)=>{e.lastIsMasterMS=(new Date).getTime()-t;if(e.s.pool.isDestroyed())return;if(n){e.ismaster=n.result}e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}))}}var eventHandler=function(e,t){return function(r,n){if(e.s.logger.isInfo()){var s=r instanceof u?JSON.stringify(r):{};e.s.logger.info(o("server %s fired event %s out with message %s",e.name,t,s))}if(t==="connect"){e.initialConnect=false;e.ismaster=n.ismaster;e.lastIsMasterMS=n.lastIsMasterMS;if(n.agreedCompressor){e.s.pool.options.agreedCompressor=n.agreedCompressor}if(n.zlibCompressionLevel){e.s.pool.options.zlibCompressionLevel=n.zlibCompressionLevel}if(n.ismaster.$clusterTime){const t=n.ismaster.$clusterTime;e.clusterTime=t}if(e.ismaster.msg==="isdbgrid"){e._type="mongos"}if(e.s.monitoring){e.monitoringProcessId=setTimeout(monitoringProcess(e),e.s.monitoringInterval)}p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});if(!e.s.inTopology){p.emitTopologyDescriptionChanged(e,{topologyType:"Single",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)}]})}if(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==="error"||t==="parseError"||t==="close"||t==="timeout"||t==="reconnect"||t==="attemptReconnect"||t==="reconnectFailed"){if(S&&["close","timeout","error","parseError","reconnectFailed"].indexOf(t)!==-1){if(!e.s.inTopology){e.emit("topologyOpening",{topologyId:e.id})}delete v[e.id]}if(t==="close"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"})}if(t==="reconnectFailed"){e.emit("reconnectFailed",r);if(e.listeners("error").length>0){e.emit("error",r)}return}if(["disconnected","connecting"].indexOf(e.s.pool.state)!==-1&&e.initialConnect&&["close","timeout","error","parseError"].indexOf(t)!==-1){e.initialConnect=false;return e.emit("error",new h(o("failed to connect to server [%s] on first connect [%s]",e.name,r)))}if(t==="reconnect"){p.emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:p.getTopologyType(e)});return e.emit(t,e)}e.emit(t,r)}}};Server.prototype.connect=function(e){var t=this;e=e||{};if(S)v[this.id]=this;if(t.s.pool&&!t.s.pool.isDisconnected()&&!t.s.pool.isDestroyed()){throw new u(o("server instance in invalid state %s",t.s.pool.state))}t.s.pool=new l(this,Object.assign(t.s.options,e,{bson:this.s.bson}));t.s.pool.on("close",eventHandler(t,"close"));t.s.pool.on("error",eventHandler(t,"error"));t.s.pool.on("timeout",eventHandler(t,"timeout"));t.s.pool.on("parseError",eventHandler(t,"parseError"));t.s.pool.on("connect",eventHandler(t,"connect"));t.s.pool.on("reconnect",eventHandler(t,"reconnect"));t.s.pool.on("reconnectFailed",eventHandler(t,"reconnectFailed"));y(t.s.pool,t,["commandStarted","commandSucceeded","commandFailed"]);if(!t.s.inTopology){this.emit("topologyOpening",{topologyId:topologyId(t)})}t.emit("serverOpening",{topologyId:topologyId(t),address:t.name});t.s.pool.connect()};Server.prototype.auth=function(e,t){if(typeof t==="function")t(null,null)};Server.prototype.getDescription=function(){var e=this.ismaster||{};var t={type:p.getTopologyType(this),address:this.name};if(e.hosts)t.hosts=e.hosts;if(e.arbiters)t.arbiters=e.arbiters;if(e.passives)t.passives=e.passives;if(e.setName)t.setName=e.setName;return t};Server.prototype.lastIsMaster=function(){return this.ismaster};Server.prototype.unref=function(){this.s.pool.unref()};Server.prototype.isConnected=function(){if(!this.s.pool)return false;return this.s.pool.isConnected()};Server.prototype.isDestroyed=function(){if(!this.s.pool)return false;return this.s.pool.isDestroyed()};function basicWriteValidations(e){if(!e.s.pool)return new u("server instance is not connected");if(e.s.pool.isDestroyed())return new u("server instance pool was destroyed")}function basicReadValidations(e,t){basicWriteValidations(e,t);if(t.readPreference&&!(t.readPreference instanceof i)){throw new Error("readPreference must be an instance of ReadPreference")}}Server.prototype.command=function(e,t,r,n){var s=this;if(typeof r==="function"){n=r,r={},r=r||{}}var i=basicReadValidations(s,r);if(i)return n(i);r=Object.assign({},r,{wireProtocolCommand:false});if(s.s.logger.isDebug()){const n=I(t);s.s.logger.debug(o("executing command [%s] against %s",JSON.stringify({ns:e,cmd:n.shouldRedact?`${n.name} details REDACTED`:t,options:A(b,r)}),s.name))}if(disconnectHandler(s,"command",e,t,r,n))return;if(B(this,t)){return n(new u(`server ${this.name} does not support collation`))}d.command(s,e,t,r,n)};Server.prototype.query=function(e,t,r,n,o){d.query(this,e,t,r,n,o)};Server.prototype.getMore=function(e,t,r,n,o){d.getMore(this,e,t,r,n,o)};Server.prototype.killCursors=function(e,t,r){d.killCursors(this,e,t,r)};Server.prototype.insert=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"insert",e,t,r,n))return;t=Array.isArray(t)?t:[t];return d.insert(o,e,t,r,n)};Server.prototype.update=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"update",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.update(o,e,t,r,n)};Server.prototype.remove=function(e,t,r,n){var o=this;if(typeof r==="function"){n=r,r={},r=r||{}}var s=basicWriteValidations(o,r);if(s)return n(s);if(disconnectHandler(o,"remove",e,t,r,n))return;if(B(this,r)){return n(new u(`server ${this.name} does not support collation`))}t=Array.isArray(t)?t:[t];return d.remove(o,e,t,r,n)};Server.prototype.cursor=function(e,t,r){r=r||{};const n=r.topology||this;var o=r.cursorFactory||this.s.Cursor;return new o(n,e,t,r)};Server.prototype.equals=function(e){if(typeof e==="string")return this.name.toLowerCase()===e.toLowerCase();if(e.name)return this.name.toLowerCase()===e.name.toLowerCase();return false};Server.prototype.connections=function(){return this.s.pool.allConnections()};Server.prototype.selectServer=function(e,t,r){if(typeof e==="function"&&typeof r==="undefined")r=e,e=undefined,t={};if(typeof t==="function")r=t,t=e,e=undefined;r(null,this)};var k=["close","error","timeout","parseError","connect"];Server.prototype.destroy=function(e,t){if(this._destroyed){if(typeof t==="function")t(null,null);return}if(typeof e==="function"){t=e;e={}}e=e||{};var r=this;if(S)delete v[this.id];if(this.monitoringProcessId){clearTimeout(this.monitoringProcessId)}if(!r.s.pool||this._destroyed){this._destroyed=true;if(typeof t==="function")t(null,null);return}this._destroyed=true;if(e.emitClose){r.emit("close",r)}if(e.emitDestroy){r.emit("destroy",r)}k.forEach((function(e){r.s.pool.removeAllListeners(e)}));if(r.listeners("serverClosed").length>0)r.emit("serverClosed",{topologyId:topologyId(r),address:r.name});if(r.listeners("topologyClosed").length>0&&!r.s.inTopology){r.emit("topologyClosed",{topologyId:topologyId(r)})}if(r.s.logger.isDebug()){r.s.logger.debug(o("destroy called on server %s",r.name))}this.s.pool.destroy(e.force,t)};e.exports=Server},2306:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(4485);const s=r(2291).TopologyType;const i=r(3111).MongoError;const a=r(3111).isRetryableWriteError;const A=r(1178).maxWireVersion;const c=r(3111).MongoNetworkError;const l=n.IllegalOperation;function emitSDAMEvent(e,t,r){if(e.listeners(t).length>0){e.emit(t,r)}}function createCompressionInfo(e){if(!e.compression||!e.compression.compressors){return[]}e.compression.compressors.forEach((function(e){if(e!=="snappy"&&e!=="zlib"){throw new Error("compressors must be at least one of snappy or zlib")}}));return e.compression.compressors}function clone(e){return JSON.parse(JSON.stringify(e))}var getPreviousDescription=function(e){if(!e.s.serverDescription){e.s.serverDescription={address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}}return e.s.serverDescription};var emitServerDescriptionChanged=function(e,t){if(e.listeners("serverDescriptionChanged").length>0){e.emit("serverDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousDescription(e),newDescription:t});e.s.serverDescription=t}};var getPreviousTopologyDescription=function(e){if(!e.s.topologyDescription){e.s.topologyDescription={topologyType:"Unknown",servers:[{address:e.name,arbiters:[],hosts:[],passives:[],type:"Unknown"}]}}return e.s.topologyDescription};var emitTopologyDescriptionChanged=function(e,t){if(e.listeners("topologyDescriptionChanged").length>0){e.emit("topologyDescriptionChanged",{topologyId:e.s.topologyId!==-1?e.s.topologyId:e.id,address:e.name,previousDescription:getPreviousTopologyDescription(e),newDescription:t});e.s.serverDescription=t}};var changedIsMaster=function(e,t,r){var n=getTopologyType(e,t);var o=getTopologyType(e,r);if(o!==n)return true;return false};var getTopologyType=function(e,t){if(!t){t=e.ismaster}if(!t)return"Unknown";if(t.ismaster&&t.msg==="isdbgrid")return"Mongos";if(t.ismaster&&!t.hosts)return"Standalone";if(t.ismaster)return"RSPrimary";if(t.secondary)return"RSSecondary";if(t.arbiterOnly)return"RSArbiter";return"Unknown"};var inquireServerState=function(e){return function(t){if(e.s.state==="destroyed")return;var r=(new Date).getTime();emitSDAMEvent(e,"serverHeartbeatStarted",{connectionId:e.name});e.command("admin.$cmd",{ismaster:true},{monitoring:true},(function(n,o){if(!n){e.emit("ismaster",o,e);var s=(new Date).getTime()-r;emitSDAMEvent(e,"serverHeartbeatSucceeded",{durationMS:s,reply:o.result,connectionId:e.name});if(changedIsMaster(e,e.s.ismaster,o.result)){emitServerDescriptionChanged(e,{address:e.name,arbiters:[],hosts:[],passives:[],type:!e.s.inTopology?"Standalone":getTopologyType(e)})}e.s.ismaster=o.result;e.s.isMasterLatencyMS=s}else{emitSDAMEvent(e,"serverHeartbeatFailed",{durationMS:s,failure:n,connectionId:e.name})}if(typeof t==="function"){return t(n,o)}e.s.inquireServerStateTimeout=setTimeout(inquireServerState(e),e.s.haInterval)}))}};var cloneOptions=function(e){var t={};for(var r in e){t[r]=e[r]}return t};function Interval(e,t){var r=false;this.start=function(){if(!this.isRunning()){r=setInterval(e,t)}return this};this.stop=function(){clearInterval(r);r=false;return this};this.isRunning=function(){return r!==false}}function Timeout(e,t){var r=false;var func=()=>{if(r){clearTimeout(r);r=false;e()}};this.start=function(){if(!this.isRunning()){r=setTimeout(func,t)}return this};this.stop=function(){clearTimeout(r);r=false;return this};this.isRunning=function(){return r!==false}}function diff(e,t){var r={servers:[]};if(!e){e={servers:[]}}for(var n=0;n{if(typeof t==="function")t()}))}};function topologyType(e){if(e.description){return e.description.type}if(e.type==="mongos"){return s.Sharded}else if(e.type==="replset"){return s.ReplicaSetWithPrimary}return s.Single}const h=6;const isRetryableWritesSupported=function(e){const t=e.lastIsMaster().maxWireVersion;if(t{"use strict";const n=r(3111).MongoError;const o=r(4485);const s=r(7289);const i=r(2481);let a;let A;(()=>{const e="NO_TRANSACTION";const t="STARTING_TRANSACTION";const r="TRANSACTION_IN_PROGRESS";const n="TRANSACTION_COMMITTED";const o="TRANSACTION_COMMITTED_EMPTY";const s="TRANSACTION_ABORTED";a={NO_TRANSACTION:e,STARTING_TRANSACTION:t,TRANSACTION_IN_PROGRESS:r,TRANSACTION_COMMITTED:n,TRANSACTION_COMMITTED_EMPTY:o,TRANSACTION_ABORTED:s};A={[e]:[e,t],[t]:[r,n,o,s],[r]:[r,n,s],[n]:[n,o,t,e],[s]:[t,e],[o]:[o,e]}})();class Transaction{constructor(e){e=e||{};this.state=a.NO_TRANSACTION;this.options={};const t=i.fromOptions(e);if(t){if(t.w<=0){throw new n("Transactions do not support unacknowledged write concern")}this.options.writeConcern=t}if(e.readConcern){this.options.readConcern=s.fromOptions(e)}if(e.readPreference){this.options.readPreference=o.fromOptions(e)}if(e.maxCommitTimeMS){this.options.maxTimeMS=e.maxCommitTimeMS}this._pinnedServer=undefined;this._recoveryToken=undefined}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isActive(){return[a.STARTING_TRANSACTION,a.TRANSACTION_IN_PROGRESS].indexOf(this.state)!==-1}transition(e){const t=A[this.state];if(t&&t.indexOf(e)!==-1){this.state=e;if(this.state===a.NO_TRANSACTION||this.state===a.STARTING_TRANSACTION||this.state===a.TRANSACTION_ABORTED){this.unpinServer()}return}throw new n(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){if(this.isActive){this._pinnedServer=e}}unpinServer(){this._pinnedServer=undefined}}function isTransactionCommand(e){return!!(e.commitTransaction||e.abortTransaction)}e.exports={TxnState:a,Transaction:Transaction,isTransactionCommand:isTransactionCommand}},8767:(e,t,r)=>{"use strict";const n=r(7310);const o=r(3477);const s=r(7578);const i=r(3111).MongoParseError;const a=r(4485);const A=r(1371).emitWarningOnce;const c=/(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/;const l=new Set(["sslCA","sslCert","sslKey","tlsCAFile","tlsCertificateKeyFile"].map((e=>e.toLowerCase())));function matchesParentDomain(e,t){const r=/^.*?\./;const n=`.${e.replace(r,"")}`;const o=`.${t.replace(r,"")}`;return n.endsWith(o)}function parseSrvConnectionString(e,t,r){const a=n.parse(e,true);if(t.directConnection||t.directconnection){return r(new i("directConnection not supported with SRV URI"))}if(a.hostname.split(".").length<3){return r(new i("URI does not have hostname, domain name and tld"))}a.domainLength=a.hostname.split(".").length;const A=e.substring("mongodb+srv://".length).split("/")[0];if(A.match(",")){return r(new i("Invalid URI, cannot contain multiple hostnames"))}if(a.port){return r(new i(`Ports not accepted with '${m}' URIs`))}const c=a.host;s.resolveSrv(`_mongodb._tcp.${c}`,((e,A)=>{if(e)return r(e);if(A.length===0){return r(new i("No addresses found at host"))}for(let e=0;e`${e.name}:${e.port}`)).join(",");if(!("ssl"in t)&&(!a.search||!("ssl"in a.query)||a.query.ssl===null)){a.query.ssl=true}s.resolveTxt(c,((e,s)=>{if(e){if(e.code!=="ENODATA"&&e.code!=="ENOTFOUND"){return r(e)}s=null}if(s){if(s.length>1){return r(new i("Multiple text records not allowed"))}s=o.parse(s[0].join(""));if(Object.keys(s).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(Object.keys(s).some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new i("Text record must only set `authSource` or `replicaSet`"))}a.query=Object.assign({},s,a.query)}a.search=o.stringify(a.query);const A=n.format(a);parseConnectionString(A,t,((e,t)=>{if(e){r(e);return}r(null,Object.assign({},t,{srvHost:c}))}))}))}))}function parseQueryStringItemValue(e,t){if(Array.isArray(t)){t=t.filter(((e,r)=>t.indexOf(e)===r));if(t.length===1)t=t[0]}else if(t.indexOf(":")>0){t=t.split(",").reduce(((t,r)=>{const n=r.split(":");t[n[0]]=parseQueryStringItemValue(e,n[1]);return t}),{})}else if(t.indexOf(",")>0){t=t.split(",").map((t=>parseQueryStringItemValue(e,t)))}else if(t.toLowerCase()==="true"||t.toLowerCase()==="false"){t=t.toLowerCase()==="true"}else if(!Number.isNaN(t)&&!h.has(e)){const e=parseFloat(t);if(!Number.isNaN(e)){t=parseFloat(t)}}return t}const u=new Set(["slaveok","slave_ok","sslvalidate","fsync","safe","retrywrites","j"]);const h=new Set(["authsource","replicaset"]);const d=new Set(["GSSAPI","MONGODB-AWS","MONGODB-X509","MONGODB-CR","DEFAULT","SCRAM-SHA-1","SCRAM-SHA-256","PLAIN"]);const g={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 applyConnectionStringOption(e,t,r,n){if(t==="journal"){t="j"}else if(t==="wtimeoutms"){t="wtimeout"}if(u.has(t)){r=r==="true"||r===true}else if(t==="appname"){r=decodeURIComponent(r)}else if(t==="readconcernlevel"){e["readConcernLevel"]=r;t="readconcern";r={level:r}}if(t==="compressors"){r=Array.isArray(r)?r:[r];if(!r.every((e=>e==="snappy"||e==="zlib"))){throw new i("Value for `compressors` must be at least one of: `snappy`, `zlib`")}}if(t==="authmechanism"&&!d.has(r)){throw new i(`Value for authMechanism must be one of: ${Array.from(d).join(", ")}, found: ${r}`)}if(t==="readpreference"&&!a.isValid(r)){throw new i("Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`")}if(t==="zlibcompressionlevel"&&(r<-1||r>9)){throw new i("zlibCompressionLevel must be an integer between -1 and 9")}if(t==="compressors"||t==="zlibcompressionlevel"){e.compression=e.compression||{};e=e.compression}if(t==="authmechanismproperties"){if(typeof r.SERVICE_NAME==="string")e.gssapiServiceName=r.SERVICE_NAME;if(typeof r.SERVICE_REALM==="string")e.gssapiServiceRealm=r.SERVICE_REALM;if(typeof r.CANONICALIZE_HOST_NAME!=="undefined"){e.gssapiCanonicalizeHostName=r.CANONICALIZE_HOST_NAME}}if(t==="readpreferencetags"){r=Array.isArray(r)?splitArrayOfMultipleReadPreferenceTags(r):[r]}if(n.caseTranslate&&g[t]){e[g[t]]=r;return}e[t]=r}const p=new Set(["GSSAPI","MONGODB-CR","PLAIN","SCRAM-SHA-1","SCRAM-SHA-256"]);function splitArrayOfMultipleReadPreferenceTags(e){const t=[];for(let r=0;r{const n=e.split(":");t[r][n[0]]=n[1]}))}return t}function applyAuthExpectations(e){if(e.options==null){return}const t=e.options;const r=t.authsource||t.authSource;if(r!=null){e.auth=Object.assign({},e.auth,{db:r})}const n=t.authmechanism||t.authMechanism;if(n!=null){if(p.has(n)&&(!e.auth||e.auth.username==null)){throw new i(`Username required for mechanism \`${n}\``)}if(n==="GSSAPI"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-AWS"){if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="MONGODB-X509"){if(e.auth&&e.auth.password!=null){throw new i(`Password not allowed for mechanism \`${n}\``)}if(r!=null&&r!=="$external"){throw new i(`Invalid source \`${r}\` for mechanism \`${n}\` specified.`)}e.auth=Object.assign({},e.auth,{db:"$external"})}if(n==="PLAIN"){if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"$external"})}}}if(e.auth&&e.auth.db==null){e.auth=Object.assign({},e.auth,{db:"admin"})}return e}function parseQueryString(e,t){const r={};let n=o.parse(e);checkTLSOptions(n);for(const e in n){const o=n[e];if(o===""||o==null){throw new i("Incomplete key value pair for option")}const s=e.toLowerCase();if(s==="serverapi"){throw new i("URI cannot contain `serverApi`, it can only be passed to the client")}const a=l.has(s)?o:parseQueryStringItemValue(s,o);applyConnectionStringOption(r,s,a,t)}if(r.wtimeout&&r.wtimeoutms){delete r.wtimeout;A("Unsupported option `wtimeout` specified")}return Object.keys(r).length?r:null}function translateTLSOptions(e){if(e.tls){e.ssl=e.tls}if(e.tlsInsecure){e.checkServerIdentity=false;e.sslValidate=false}else{Object.assign(e,{checkServerIdentity:e.tlsAllowInvalidHostnames?false:true,sslValidate:e.tlsAllowInvalidCertificates?false:true})}if(e.tlsCAFile){e.ssl=true;e.sslCA=e.tlsCAFile}if(e.tlsCertificateKeyFile){e.ssl=true;if(e.tlsCertificateFile){e.sslCert=e.tlsCertificateFile;e.sslKey=e.tlsCertificateKeyFile}else{e.sslKey=e.tlsCertificateKeyFile;e.sslCert=e.tlsCertificateKeyFile}}if(e.tlsCertificateKeyFilePassword){e.ssl=true;e.sslPass=e.tlsCertificateKeyFilePassword}return e}function checkTLSOptions(e){const t=Object.keys(e);if(t.indexOf("tlsInsecure")!==-1&&(t.indexOf("tlsAllowInvalidCertificates")!==-1||t.indexOf("tlsAllowInvalidHostnames")!==-1)){throw new i("The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.")}const r=assertTlsOptionsAreEqual("tls",e,t);const n=assertTlsOptionsAreEqual("ssl",e,t);if(r!=null&&n!=null){if(r!==n){throw new i("All values of `tls` and `ssl` must be the same.")}}}function assertTlsOptionsAreEqual(e,t,r){const n=r.indexOf(e)!==-1;let o;if(Array.isArray(t[e])){o=t[e][0]}else{o=t[e]}if(n){if(Array.isArray(t[e])){const r=t[e][0];t[e].forEach((t=>{if(t!==r){throw new i(`All values of ${e} must be the same.`)}}))}}return o}const E="mongodb";const m="mongodb+srv";const C=[E,m];function parseConnectionString(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},{caseTranslate:true},t);try{n.parse(e)}catch(e){return r(new i("URI malformed, cannot be parsed"))}const s=e.match(c);if(!s){return r(new i("Invalid connection string"))}const a=s[1];if(C.indexOf(a)===-1){return r(new i("Invalid protocol provided"))}const A=s[4].split("?");const l=A.length>0?A[0]:null;const u=A.length>1?A[1]:null;let h;try{h=parseQueryString(u,t)}catch(e){return r(e)}h=Object.assign({},h,t);if(Object.keys(h).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new i("Load balancer mode requires driver version 4+"))}if(a===m){return parseSrvConnectionString(e,h,r)}const d={username:null,password:null,db:l&&l!==""?o.unescape(l):null};if(h.auth){if(h.auth.username)d.username=h.auth.username;if(h.auth.user)d.username=h.auth.user;if(h.auth.password)d.password=h.auth.password}else{if(h.username)d.username=h.username;if(h.user)d.username=h.user;if(h.password)d.password=h.password}if(s[4].split("?")[0].indexOf("@")!==-1){return r(new i("Unescaped slash in userinfo section"))}const g=s[3].split("@");if(g.length>2){return r(new i("Unescaped at-sign in authority section"))}if(g[0]==null||g[0]===""){return r(new i("No username provided in authority section"))}if(g.length>1){const e=g.shift().split(":");if(e.length>2){return r(new i("Unescaped colon in authority section"))}if(e[0]===""){return r(new i("Invalid empty username provided"))}if(!d.username)d.username=o.unescape(e[0]);if(!d.password)d.password=e[1]?o.unescape(e[1]):null}let p=null;const E=g.shift().split(",").map((e=>{let t=n.parse(`mongodb://${e}`);if(t.path==="/:"){p=new i("Double colon in host identifier");return null}if(e.match(/\.sock/)){t.hostname=o.unescape(e);t.port=null}if(Number.isNaN(t.port)){p=new i("Invalid port (non-numeric string)");return}const r={host:t.hostname,port:t.port?parseInt(t.port):27017};if(r.port===0){p=new i("Invalid port (zero) with hostname");return}if(r.port>65535){p=new i("Invalid port (larger than 65535) with hostname");return}if(r.port<0){p=new i("Invalid port (negative number)");return}return r})).filter((e=>!!e));if(p){return r(p)}if(E.length===0||E[0].host===""||E[0].host===null){return r(new i("No hostname or hostnames provided in connection string"))}const I=!!h.directConnection;if(I&&E.length!==1){return r(new i("directConnection option requires exactly one host"))}if(h.directConnection==null&&E.length===1&&h.replicaSet==null){h.directConnection=true}const y={hosts:E,auth:d.db||d.username?d:null,options:Object.keys(h).length?h:null};if(y.auth&&y.auth.db){y.defaultDatabase=y.auth.db}else{y.defaultDatabase="test"}y.options=translateTLSOptions(y.options);try{applyAuthExpectations(y)}catch(e){return r(e)}r(null,y)}e.exports=parseConnectionString},1178:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6113);const s=r(3182)(require);const uuidV4=()=>{const e=o.randomBytes(16);e[6]=e[6]&15|64;e[8]=e[8]&63|128;return e};function relayEvents(e,t,r){r.forEach((r=>e.on(r,(e=>t.emit(r,e)))))}function retrieveKerberos(){let e;try{e=s("kerberos")}catch(e){if(e.code==="MODULE_NOT_FOUND"){throw new Error("The `kerberos` module was not found. Please install it and try again.")}throw e}return e}const noEJSONError=function(){throw new Error("The `mongodb-extjson` module was not found. Please install it and try again.")};function retrieveEJSON(){let e=s("mongodb-extjson");if(!e){e={parse:noEJSONError,deserialize:noEJSONError,serialize:noEJSONError,stringify:noEJSONError,setBSONModule:noEJSONError,BSON:noEJSONError}}return e}function maxWireVersion(e){if(e){if(e.ismaster){return e.ismaster.maxWireVersion}if(typeof e.lastIsMaster==="function"){const t=e.lastIsMaster();if(t){return t.maxWireVersion}}if(e.description){return e.description.maxWireVersion}}return 0}function collationNotSupported(e,t){return t&&t.collation&&maxWireVersion(e)<5}function isPromiseLike(e){return e&&typeof e.then==="function"}function eachAsync(e,t,r){e=e||[];let n=0;let o=0;for(n=0;ne===t[r]))}function tagsStrictEqual(e,t){const r=Object.keys(e);const n=Object.keys(t);return r.length===n.length&&r.every((r=>t[r]===e[r]))}function errorStrictEqual(e,t){if(e===t){return true}if(e==null&&t!=null||e!=null&&t==null){return false}if(e.constructor.name!==t.constructor.name){return false}if(e.message!==t.message){return false}return true}function makeStateMachine(e){return function stateTransition(t,r){const n=e[t.s.state];if(n&&n.indexOf(r)<0){throw new TypeError(`illegal state transition from [${t.s.state}] => [${r}], allowed: [${n}]`)}t.emit("stateChanged",t.s.state,r);t.s.state=r}}function makeClientMetadata(e){e=e||{};const t={driver:{name:"nodejs",version:r(1693).i8},os:{type:n.type(),name:process.platform,architecture:process.arch,version:n.release()},platform:`'Node.js ${process.version}, ${n.endianness} (${e.useUnifiedTopology?"unified":"legacy"})`};if(e.driverInfo){if(e.driverInfo.name){t.driver.name=`${t.driver.name}|${e.driverInfo.name}`}if(e.driverInfo.version){t.version=`${t.driver.version}|${e.driverInfo.version}`}if(e.driverInfo.platform){t.platform=`${t.platform}|${e.driverInfo.platform}`}}if(e.appname){const r=Buffer.from(e.appname);t.application={name:r.length>128?r.slice(0,128).toString("utf8"):e.appname}}return t}const noop=()=>{};e.exports={uuidV4:uuidV4,relayEvents:relayEvents,collationNotSupported:collationNotSupported,retrieveEJSON:retrieveEJSON,retrieveKerberos:retrieveKerberos,maxWireVersion:maxWireVersion,isPromiseLike:isPromiseLike,eachAsync:eachAsync,eachAsyncSeries:eachAsyncSeries,isUnifiedTopology:isUnifiedTopology,arrayStrictEqual:arrayStrictEqual,tagsStrictEqual:tagsStrictEqual,errorStrictEqual:errorStrictEqual,makeStateMachine:makeStateMachine,makeClientMetadata:makeClientMetadata,noop:noop}},7276:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(8988).Msg;const s=r(3111).MongoError;const i=r(7272).getReadPreference;const a=r(7272).isSharded;const A=r(7272).databaseNamespace;const c=r(1707).isTransactionCommand;const l=r(5474).applySession;const u=r(3111).MongoNetworkError;const h=r(1178).maxWireVersion;function isClientEncryptionEnabled(e){const t=h(e);return t&&e.autoEncrypter}function command(e,t,r,n,o){if(typeof n==="function")o=n,n={};n=n||{};if(r==null){return o(new s(`command ${JSON.stringify(r)} does not return a cursor`))}if(!isClientEncryptionEnabled(e)){_command(e,t,r,n,o);return}const i=h(e);if(typeof i!=="number"||i<8){o(new s("Auto-encryption requires a minimum MongoDB version of 4.2"));return}_cryptCommand(e,t,r,n,o)}function _command(e,t,r,h,d){const g=e.s.bson;const p=e.s.pool;const E=i(r,h);const m=supportsOpMsg(e);const C=h.session;const I=e.clusterTime;let y=I;let B=Object.assign({},r);const Q=h.serverApi;if(Q){B.apiVersion=Q.version||Q;if(Q.strict!=null){B.apiStrict=Q.strict}if(Q.deprecationErrors!=null){B.apiDeprecationErrors=Q.deprecationErrors}}if(hasSessionSupport(e)&&C){const e=C.clusterTime;if(I&&I.clusterTime&&e&&e.clusterTime&&e.clusterTime.greaterThan(I.clusterTime)){y=e}if(!C.transaction.isActive&&C.transaction.isPinned&&!B.startTransaction&&!B.commitTransaction){C.transaction.unpinServer()}const t=l(C,B,h);if(t){return d(t)}}if(y){B.$clusterTime=y}if(a(e)&&!m&&E&&E.mode!=="primary"){B={$query:B,$readPreference:E.toJSON()}}const b=Object.assign({command:true,numberToSkip:0,numberToReturn:-1,checkKeys:false},h);b.slaveOk=E.slaveOk();const w=`${A(t)}.$cmd`;const S=m?new o(g,w,B,b):new n(g,w,B,b);const v=C&&(C.inTransaction()||c(B));const R=v?function(e){if(e&&e instanceof u&&!e.hasErrorLabel("TransientTransactionError")){e.addErrorLabel("TransientTransactionError")}if(!r.commitTransaction&&e&&e instanceof s&&e.hasErrorLabel("TransientTransactionError")){C.transaction.unpinServer()}return d.apply(null,arguments)}:d;try{p.write(S,b,R)}catch(e){R(e)}}function hasSessionSupport(e){if(e==null)return false;if(e.description){return e.description.maxWireVersion>=6}return e.ismaster==null?false:e.ismaster.maxWireVersion>=6}function supportsOpMsg(e){const t=e.ismaster?e.ismaster:e.description;if(t==null){return false}return t.maxWireVersion>=6&&t.__nodejs_mock_server__==null}function _cryptCommand(e,t,r,n,o){const s=e.autoEncrypter;function commandResponseHandler(e,t){if(e||t==null){o(e,t);return}s.decrypt(t.result,n,((e,r)=>{if(e){o(e,null);return}t.result=r;t.message.documents=[r];o(null,t)}))}s.encrypt(t,r,n,((r,s)=>{if(r){o(r,null);return}_command(e,t,s,n,commandResponseHandler)}))}e.exports=command},7793:(e,t,r)=>{"use strict";const n=r(7746).retrieveSnappy();const o=r(9796);const s={snappy:1,zlib:2};const i=new Set(["ismaster","saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);function compress(e,t,r){switch(e.options.agreedCompressor){case"snappy":n.compress(t,r);break;case"zlib":var s={};if(e.options.zlibCompressionLevel){s.level=e.options.zlibCompressionLevel}o.deflate(t,s,r);break;default:throw new Error('Attempt to compress message using unknown compressor "'+e.options.agreedCompressor+'".')}}function decompress(e,t,r){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:n.uncompress(t,r);break;case s.zlib:o.inflate(t,r);break;default:r(null,t)}}e.exports={compressorIDs:s,uncompressibleCommands:i,compress:compress,decompress:decompress}},7161:e=>{"use strict";const t="2.6";const r="5.0";const n=2;const o=13;e.exports={MIN_SUPPORTED_SERVER_VERSION:t,MAX_SUPPORTED_SERVER_VERSION:r,MIN_SUPPORTED_WIRE_VERSION:n,MAX_SUPPORTED_WIRE_VERSION:o}},1971:(e,t,r)=>{"use strict";const n=r(9814).GetMore;const o=r(7746).retrieveBSON;const s=r(3111).MongoError;const i=r(3111).MongoNetworkError;const a=o();const A=a.Long;const c=r(7272).collectionNamespace;const l=r(1178).maxWireVersion;const u=r(7272).applyCommonQueryOptions;const h=r(7276);function getMore(e,t,r,o,a,d){a=a||{};const g=l(e);function queryCallback(e,t){if(e)return d(e);const n=t.message;if(n.cursorNotFound){return d(new i("cursor killed or timed out"),null)}if(g<4){const e=typeof n.cursorId==="number"?A.fromNumber(n.cursorId):n.cursorId;r.documents=n.documents;r.cursorId=e;d(null,null,n.connection);return}if(n.documents[0].ok===0){return d(new s(n.documents[0]))}const o=typeof n.documents[0].cursor.id==="number"?A.fromNumber(n.documents[0].cursor.id):n.documents[0].cursor.id;r.documents=n.documents[0].cursor.nextBatch;r.cursorId=o;d(null,n.documents[0],n.connection)}if(g<4){const s=e.s.bson;const i=new n(s,t,r.cursorId,{numberToReturn:o});const a=u({},r);e.s.pool.write(i,a,queryCallback);return}const p=r.cursorId instanceof A?r.cursorId:A.fromNumber(r.cursorId);const E={getMore:p,collection:c(t),batchSize:Math.abs(o)};if(r.cmd.tailable&&typeof r.cmd.maxAwaitTimeMS==="number"){E.maxTimeMS=r.cmd.maxAwaitTimeMS}const m=Object.assign({returnFieldSelector:null,documentsReturnedIn:"nextBatch"},a);if(r.session){m.session=r.session}h(e,t,E,m,queryCallback)}e.exports=getMore},9206:(e,t,r)=>{"use strict";const n=r(779);e.exports={insert:function insert(e,t,r,o,s){n(e,"insert","documents",t,r,o,s)},update:function update(e,t,r,o,s){n(e,"update","updates",t,r,o,s)},remove:function remove(e,t,r,o,s){n(e,"delete","deletes",t,r,o,s)},killCursors:r(6044),getMore:r(1971),query:r(1820),command:r(7276)}},6044:(e,t,r)=>{"use strict";const n=r(9814).KillCursor;const o=r(3111).MongoError;const s=r(3111).MongoNetworkError;const i=r(7272).collectionNamespace;const a=r(1178).maxWireVersion;const A=r(1178).emitWarning;const c=r(7276);function killCursors(e,t,r,l,u){if(typeof l==="function"){u=l;l={}}u=typeof u==="function"?u:()=>{};const h=r.cursorId;if(a(e)<4){const o=e.s.bson;const s=e.s.pool;const i=new n(o,t,[h]);const a={immediateRelease:true,noResponse:true};if(typeof r.session==="object"){a.session=r.session}if(s&&s.isConnected()){try{s.write(i,a,u)}catch(e){if(typeof u==="function"){u(e,null)}else{A(e)}}}return}const d={killCursors:i(t),cursors:[h]};const g=l||{};if(typeof r.session==="object")g.session=r.session;c(e,t,d,g,((e,t)=>{if(e){return u(e)}const r=t.message;if(r.cursorNotFound){return u(new s("cursor killed or timed out"),null)}if(!Array.isArray(r.documents)||r.documents.length===0){return u(new o(`invalid killCursors result returned for cursor id ${h}`))}u(null,r.documents[0])}))}e.exports=killCursors},1820:(e,t,r)=>{"use strict";const n=r(9814).Query;const o=r(3111).MongoError;const s=r(7272).getReadPreference;const i=r(7272).collectionNamespace;const a=r(7272).isSharded;const A=r(1178).maxWireVersion;const c=r(7272).applyCommonQueryOptions;const l=r(7276);const u=r(1371).decorateWithExplain;const h=r(5293).Explain;function query(e,t,r,n,i,a){i=i||{};if(n.cursorId!=null){return a()}if(r==null){return a(new o(`command ${JSON.stringify(r)} does not return a cursor`))}if(A(e)<4){const o=prepareLegacyFindQuery(e,t,r,n,i);const s=c({},n);if(typeof o.documentsReturnedIn==="string"){s.documentsReturnedIn=o.documentsReturnedIn}e.s.pool.write(o,s,a);return}const d=s(r,i);let g=prepareFindCommand(e,t,r,n,i);try{const e=h.fromOptions(i);if(e){g=u(g,e)}}catch(e){return a(e)}r.virtual=false;const p=Object.assign({documentsReturnedIn:"firstBatch",numberToReturn:1,slaveOk:d.slaveOk()},i);if(r.readPreference){p.readPreference=d}if(n.session){p.session=n.session}l(e,t,g,p,a)}function prepareFindCommand(e,t,r,n){n.batchSize=r.batchSize||n.batchSize;const o={find:i(t)};if(r.query){if(r.query["$query"]){o.filter=r.query["$query"]}else{o.filter=r.query}}let s=r.sort;if(Array.isArray(s)){const e={};if(s.length>0&&!Array.isArray(s[0])){let t=s[1];if(t==="asc"){t=1}else if(t==="desc"){t=-1}e[s[0]]=t}else{for(let t=0;t0&&i.batchSize===0){u=i.limit}else{u=i.batchSize}const h=i.skip||0;const d={};if(a(e)&&l){d["$readPreference"]=l.toJSON()}if(r.sort)d["$orderby"]=r.sort;if(r.hint)d["$hint"]=r.hint;if(r.snapshot)d["$snapshot"]=r.snapshot;if(typeof r.returnKey!=="undefined")d["$returnKey"]=r.returnKey;if(r.maxScan)d["$maxScan"]=r.maxScan;if(r.min)d["$min"]=r.min;if(r.max)d["$max"]=r.max;if(typeof r.showDiskLoc!=="undefined")d["$showDiskLoc"]=r.showDiskLoc;if(r.comment)d["$comment"]=r.comment;if(r.maxTimeMS)d["$maxTimeMS"]=r.maxTimeMS;if(A.explain!==undefined){u=-Math.abs(r.limit||0);d["$explain"]=true}d["$query"]=r.query;if(r.readConcern&&r.readConcern.level!=="local"){throw new o(`server find command does not support a readConcern level of ${r.readConcern.level}`)}if(r.readConcern){r=Object.assign({},r);delete r["readConcern"]}const g=typeof A.serializeFunctions==="boolean"?A.serializeFunctions:false;const p=typeof A.ignoreUndefined==="boolean"?A.ignoreUndefined:false;const E=new n(c,t,d,{numberToSkip:h,numberToReturn:u,pre32Limit:typeof r.limit!=="undefined"?r.limit:undefined,checkKeys:false,returnFieldSelector:r.fields,serializeFunctions:g,ignoreUndefined:p});if(typeof r.tailable==="boolean")E.tailable=r.tailable;if(typeof r.oplogReplay==="boolean")E.oplogReplay=r.oplogReplay;if(typeof r.noCursorTimeout==="boolean")E.noCursorTimeout=r.noCursorTimeout;if(typeof r.awaitData==="boolean")E.awaitData=r.awaitData;if(typeof r.partial==="boolean")E.partial=r.partial;E.slaveOk=l.slaveOk();return E}e.exports=query},7272:(e,t,r)=>{"use strict";const n=r(4485);const o=r(3111).MongoError;const s=r(2291).ServerType;const i=r(7962).TopologyDescription;const a=16;const A=9;var c={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};var getReadPreference=function(e,t){var r=e.readPreference||new n("primary");if(t.readPreference){r=t.readPreference}if(typeof r==="string"){r=new n(r)}if(!(r instanceof n)){throw new o("read preference must be a ReadPreference instance")}return r};var parseHeader=function(e){return{length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)}};function applyCommonQueryOptions(e,t){Object.assign(e,{raw:typeof t.raw==="boolean"?t.raw:false,promoteLongs:typeof t.promoteLongs==="boolean"?t.promoteLongs:true,promoteValues:typeof t.promoteValues==="boolean"?t.promoteValues:true,promoteBuffers:typeof t.promoteBuffers==="boolean"?t.promoteBuffers:false,bsonRegExp:typeof t.bsonRegExp==="boolean"?t.bsonRegExp:false,monitoring:typeof t.monitoring==="boolean"?t.monitoring:false,fullResult:typeof t.fullResult==="boolean"?t.fullResult:false});if(typeof t.socketTimeout==="number"){e.socketTimeout=t.socketTimeout}if(t.session){e.session=t.session}if(typeof t.documentsReturnedIn==="string"){e.documentsReturnedIn=t.documentsReturnedIn}return e}function isSharded(e){if(e.type==="mongos")return true;if(e.description&&e.description.type===s.Mongos){return true}if(e.description&&e.description instanceof i){const t=Array.from(e.description.servers.values());return t.some((e=>e.type===s.Mongos))}return false}function databaseNamespace(e){return e.split(".")[0]}function collectionNamespace(e){return e.split(".").slice(1).join(".")}e.exports={getReadPreference:getReadPreference,MESSAGE_HEADER_SIZE:a,COMPRESSION_DETAILS_SIZE:A,opcodes:c,parseHeader:parseHeader,applyCommonQueryOptions:applyCommonQueryOptions,isSharded:isSharded,databaseNamespace:databaseNamespace,collectionNamespace:collectionNamespace}},779:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(7272).collectionNamespace;const s=r(7276);const i=r(1371).decorateWithExplain;const a=r(5293).Explain;function writeCommand(e,t,r,A,c,l,u){if(c.length===0)throw new n(`${t} must contain at least one document`);if(typeof l==="function"){u=l;l={}}l=l||{};const h=typeof l.ordered==="boolean"?l.ordered:true;const d=l.writeConcern;let g={};g[t]=o(A);g[r]=c;g.ordered=h;if(d&&Object.keys(d).length>0){g.writeConcern=d}if(l.collation){for(let e=0;e{"use strict";const n=r(2781).Transform;const o=r(2781).PassThrough;const s=r(3837).deprecate;const i=r(1371).handleCallback;const a=r(3994).ReadPreference;const A=r(3994).MongoError;const c=r(4847).CoreCursor;const l=r(4847).CursorState;const u=r(3994).BSON.Map;const h=r(1371).maybePromise;const d=r(2548);const g=r(1371).formattedOrderClause;const p=r(5293).Explain;const E=r(1018).Aspect;const m=r(3554).each;const C=r(7885);const I=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];const y=["numberOfRetries","tailableRetryInterval"];class Cursor extends c{constructor(e,t,r,n){super(e,t,r,n);if(this.operation){n=this.operation.options}const o=n.numberOfRetries||5;const s=n.tailableRetryInterval||500;const i=o;const a=n.promiseLibrary||Promise;this.s={numberOfRetries:o,tailableRetryInterval:s,currentNumberOfRetries:i,state:l.INIT,promiseLibrary:a,explicitlyIgnoreSession:!!n.explicitlyIgnoreSession};if(!n.explicitlyIgnoreSession&&n.session){this.cursorState.session=n.session}if(this.options.noCursorTimeout===true){this.addCursorFlag("noCursorTimeout",true)}let A=1e3;if(this.cmd.cursor&&this.cmd.cursor.batchSize){A=this.cmd.cursor.batchSize}else if(n.cursor&&n.cursor.batchSize){A=n.cursor.batchSize}else if(typeof n.batchSize==="number"){A=n.batchSize}this.setCursorBatchSize(A)}get readPreference(){if(this.operation){return this.operation.readPreference}return this.options.readPreference}get sortValue(){return this.cmd.sort}set session(e){this.cursorState.session=e}_initializeCursor(e){if(this.operation&&this.operation.session!=null){this.cursorState.session=this.operation.session}else{if(!this.s.explicitlyIgnoreSession&&!this.cursorState.session&&this.topology.hasSessionSupport()){this.cursorState.session=this.topology.startSession({owner:this});if(this.operation){this.operation.session=this.cursorState.session}}}super._initializeCursor(e)}hasNext(e){if(this.s.state===l.CLOSED||this.isDead&&this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}return h(this,e,(e=>{const t=this;if(t.isNotified()){return e(null,false)}t._next(((r,n)=>{if(r)return e(r);if(n==null||t.s.state===Cursor.CLOSED||t.isDead()){return e(null,false)}t.s.state=l.OPEN;t.cursorState.cursorIndex--;if(t.cursorState.limit>0){t.cursorState.currentLimit--}e(null,true)}))}))}next(e){return h(this,e,(e=>{const t=this;if(t.s.state===l.CLOSED||t.isDead&&t.isDead()){e(A.create({message:"Cursor is closed",driver:true}));return}if(t.s.state===l.INIT&&t.cmd.sort){try{t.cmd.sort=g(t.cmd.sort)}catch(t){return e(t)}}t._next(((r,n)=>{if(r)return e(r);t.s.state=l.OPEN;e(null,n)}))}))}filter(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.query=e;return this}maxScan(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxScan=e;return this}hint(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.hint=e;return this}min(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.min=e;return this}max(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.max=e;return this}returnKey(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.returnKey=e;return this}showRecordId(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.showDiskLoc=e;return this}snapshot(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.snapshot=e;return this}setCursorOption(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(y.indexOf(e)===-1){throw A.create({message:`option ${e} is not a supported option ${y}`,driver:true})}this.s[e]=t;if(e==="numberOfRetries")this.s.currentNumberOfRetries=t;return this}addCursorFlag(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(I.indexOf(e)===-1){throw A.create({message:`flag ${e} is not a supported flag ${I}`,driver:true})}if(typeof t!=="boolean"){throw A.create({message:`flag ${e} must be a boolean value`,driver:true})}this.cmd[e]=t;return this}addQueryModifier(e,t){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(e[0]!=="$"){throw A.create({message:`${e} is not a valid query modifier`,driver:true})}const r=e.substr(1);this.cmd[r]=t;if(r==="orderby")this.cmd.sort=this.cmd[r];return this}comment(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.comment=e;return this}maxAwaitTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxAwaitTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxAwaitTimeMS=e;return this}maxTimeMS(e){if(typeof e!=="number"){throw A.create({message:"maxTimeMS must be a number",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.maxTimeMS=e;return this}project(e){if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}this.cmd.fields=e;return this}sort(e,t){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support sorting",driver:true})}if(this.s.state===l.CLOSED||this.s.state===l.OPEN||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}let r=e;if(Array.isArray(r)&&Array.isArray(r[0])){r=new u(r.map((e=>{const t=[e[0],null];if(e[1]==="asc"){t[1]=1}else if(e[1]==="desc"){t[1]=-1}else if(e[1]===1||e[1]===-1||e[1].$meta){t[1]=e[1]}else{throw new A("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]")}return t})))}if(t!=null){r=[[e,t]]}this.cmd.sort=r;return this}batchSize(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support batchSize",driver:true})}if(this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"batchSize requires an integer",driver:true})}this.cmd.batchSize=e;this.setCursorBatchSize(e);return this}collation(e){this.cmd.collation=e;return this}limit(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support limit",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"limit requires an integer",driver:true})}this.cmd.limit=e;this.setCursorLimit(e);return this}skip(e){if(this.options.tailable){throw A.create({message:"Tailable cursor doesn't support skip",driver:true})}if(this.s.state===l.OPEN||this.s.state===l.CLOSED||this.isDead()){throw A.create({message:"Cursor is closed",driver:true})}if(typeof e!=="number"){throw A.create({message:"skip requires an integer",driver:true})}this.cmd.skip=e;this.setCursorSkip(e);return this}each(e){this.rewind();this.s.state=l.INIT;m(this,e)}forEach(e,t){this.rewind();this.s.state=l.INIT;if(typeof t==="function"){m(this,((r,n)=>{if(r){t(r);return false}if(n!=null){try{e(n)}catch(e){t(e);return false}return true}if(n==null&&t){const e=t;t=null;e(null);return false}}))}else{return new this.s.promiseLibrary(((t,r)=>{m(this,((n,o)=>{if(n){r(n);return false}else if(o==null){t(null);return false}else{try{e(o)}catch(e){r(e);return false}return true}}))}))}}setReadPreference(e){if(this.s.state!==l.INIT){throw A.create({message:"cannot change cursor readPreference after cursor has been accessed",driver:true})}if(e instanceof a){this.options.readPreference=e}else if(typeof e==="string"){this.options.readPreference=new a(e)}else{throw new TypeError("Invalid read preference: "+e)}return this}toArray(e){if(this.options.tailable){throw A.create({message:"Tailable cursor cannot be converted to array",driver:true})}return h(this,e,(e=>{const t=this;const r=[];t.rewind();t.s.state=l.INIT;const fetchDocs=()=>{t._next(((n,o)=>{if(n){return i(e,n)}if(o==null){return t.close({skipKillCursors:true},(()=>i(e,null,r)))}r.push(o);if(t.bufferedCount()>0){let e=t.readBufferedDocuments(t.bufferedCount());Array.prototype.push.apply(r,e)}fetchDocs()}))};fetchDocs()}))}count(e,t,r){if(this.cmd.query==null)throw A.create({message:"count can only be used with find command",driver:true});if(typeof t==="function")r=t,t={};t=t||{};if(typeof e==="function"){r=e;e=true}if(this.cursorState.session){t=Object.assign({},t,{session:this.cursorState.session})}const n=new C(this,e,t);return d(this.topology,n,r)}close(e,t){if(typeof e==="function")t=e,e={};e=Object.assign({},{skipKillCursors:false},e);return h(this,t,(t=>{this.s.state=l.CLOSED;if(!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=r=>e(t(r))}else{this.cursorState.transforms={doc:e}}return this}isClosed(){return this.isDead()}destroy(e){if(e)this.emit("error",e);this.pause();this.close()}stream(e){this.cursorState.streamOptions=e||{};return this}transformStream(e){const t=e||{};if(typeof t.transform==="function"){const e=new n({objectMode:true,transform:function(e,r,n){this.push(t.transform(e));n()}});return this.pipe(e)}return this.pipe(new o({objectMode:true}))}explain(e,t){if(typeof e==="function")t=e,e=true;if(e===undefined)e=true;if(!this.operation||!this.operation.hasAspect(E.EXPLAINABLE)){throw new A("This command cannot be explained")}this.operation.explain=new p(e);return h(this,t,(e=>{c.prototype._next.apply(this,[e])}))}getLogger(){return this.logger}}Cursor.prototype.maxTimeMs=Cursor.prototype.maxTimeMS;s(Cursor.prototype.each,"Cursor.each is deprecated. Use Cursor.forEach instead.");s(Cursor.prototype.maxScan,"Cursor.maxScan is deprecated, and will be removed in a later version");s(Cursor.prototype.snapshot,"Cursor Snapshot is deprecated, and will be removed in a later version");e.exports=Cursor},6662:(e,t,r)=>{"use strict";const n=r(2361).EventEmitter;const o=r(3837).inherits;const s=r(1371).getSingleProperty;const i=r(538);const a=r(1371).handleCallback;const A=r(1371).filterOptions;const c=r(1371).toError;const l=r(3994).ReadPreference;const u=r(3994).MongoError;const h=r(3994).ObjectID;const d=r(3994).Logger;const g=r(5193);const p=r(1371).conditionallyMergeWriteConcern;const E=r(1371).executeLegacyOperation;const m=r(1117);const C=r(3837).deprecate;const I=r(1371).deprecateOptions;const y=r(1371).MongoDBNamespace;const B=r(147);const Q=r(2481);const b=r(7289);const w=r(7429);const S=r(2226).createListener;const v=r(2226).ensureIndex;const R=r(2226).evaluate;const k=r(2226).profilingInfo;const D=r(2226).validateDatabaseName;const N=r(1554);const T=r(7057);const O=r(286);const _=r(499);const M=r(1363);const L=r(5561);const F=r(6394);const U=r(2360).DropCollectionOperation;const P=r(2360).DropDatabaseOperation;const G=r(1681);const Y=r(4245);const V=r(840);const W=r(3969);const J=r(1969);const q=r(2808);const j=r(6301);const z=r(2548);const $=["w","wtimeout","fsync","j","writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","bufferMaxEntries","authSource","ignoreUndefined","promiseLibrary","readConcern","retryMiliSeconds","numberOfRetries","parentDb","noListener","loggerLevel","logger","promoteBuffers","promoteLongs","promoteValues","bsonRegExp","compression","retryWrites"];function Db(e,t,r){r=r||{};if(!(this instanceof Db))return new Db(e,t,r);n.call(this);const o=r.promiseLibrary||Promise;r=A(r,$);r.promiseLibrary=o;this.s={dbCache:{},children:[],topology:t,options:r,logger:d("Db",r),bson:t?t.bson:null,readPreference:l.fromOptions(r),bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:-1,parentDb:r.parentDb||null,pkFactory:r.pkFactory||h,nativeParser:r.nativeParser||r.native_parser,promiseLibrary:o,noListener:typeof r.noListener==="boolean"?r.noListener:false,readConcern:b.fromOptions(r),writeConcern:Q.fromOptions(r),namespace:new y(e)};D(e);s(this,"serverConfig",this.s.topology);s(this,"bufferMaxEntries",this.s.bufferMaxEntries);s(this,"databaseName",this.s.namespace.db);if(r.parentDb)return;if(this.s.noListener)return;t.on("error",S(this,"error",this));t.on("timeout",S(this,"timeout",this));t.on("close",S(this,"close",this));t.on("parseError",S(this,"parseError",this));t.once("open",S(this,"open",this));t.once("fullsetup",S(this,"fullsetup",this));t.once("all",S(this,"all",this));t.on("reconnect",S(this,"reconnect",this))}o(Db,n);Db.prototype.on=C((function(){return Db.super_.prototype.on.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Db.prototype.once=C((function(){return Db.super_.prototype.once.apply(this,arguments)}),"Listening to events on the Db class has been deprecated and will be removed in the next major version.");Object.defineProperty(Db.prototype,"topology",{enumerable:true,get:function(){return this.s.topology}});Object.defineProperty(Db.prototype,"options",{enumerable:true,get:function(){return this.s.options}});Object.defineProperty(Db.prototype,"slaveOk",{enumerable:true,get:function(){if(this.s.options.readPreference!=null&&(this.s.options.readPreference!=="primary"||this.s.options.readPreference.mode!=="primary")){return true}return false}});Object.defineProperty(Db.prototype,"readConcern",{enumerable:true,get:function(){return this.s.readConcern}});Object.defineProperty(Db.prototype,"readPreference",{enumerable:true,get:function(){if(this.s.readPreference==null){return l.primary}return this.s.readPreference}});Object.defineProperty(Db.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(Db.prototype,"namespace",{enumerable:true,get:function(){return this.s.namespace.toString()}});Db.prototype.command=function(e,t,r){if(typeof t==="function")r=t,t={};t=Object.assign({},t);const n=new M(this,e,t);return z(this.s.topology,n,r)};Db.prototype.aggregate=function(e,t,r){if(typeof t==="function"){r=t;t={}}if(t==null&&r==null){t={}}const n=new w(this.s.topology,new N(this,e,t),t);if(typeof r==="function"){r(null,n);return}return n};Db.prototype.admin=function(){const e=r(3238);return new e(this,this.s.topology,this.s.promiseLibrary)};const K=["pkFactory","readPreference","serializeFunctions","strict","readConcern","ignoreUndefined","promoteValues","promoteBuffers","promoteLongs","bsonRegExp"];Db.prototype.collection=I({name:"Db.collection",deprecatedOptions:["strict"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t=Object.assign({},t);t.promiseLibrary=this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;if(this.s.options.ignoreUndefined){t.ignoreUndefined=this.s.options.ignoreUndefined}for(const e of K){if(!(e in t)&&this.s.options[e]!==undefined){t[e]=this.s.options[e]}}t=p(t,this.s.options);if(t==null||!t.strict){try{const n=new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t);if(r)r(null,n);return n}catch(e){if(e instanceof u&&r)return r(e);throw e}}if(typeof r!=="function"){throw c(`A callback is required in strict mode. While getting collection ${e}`)}if(this.serverConfig&&this.serverConfig.isDestroyed()){return r(new u("topology was destroyed"))}const n=Object.assign({},t,{nameOnly:true});this.listCollections({name:e},n).toArray(((n,o)=>{if(n!=null)return a(r,n,null);if(o.length===0)return a(r,c(`Collection ${e} does not exist. Currently in strict mode.`),null);try{return a(r,null,new g(this,this.s.topology,this.databaseName,e,this.s.pkFactory,t))}catch(n){return a(r,n,null)}}))}));Db.prototype.createCollection=I({name:"Db.createCollection",deprecatedOptions:["autoIndexId","strict","w","wtimeout","j"],optionsIndex:1},(function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.promiseLibrary=t.promiseLibrary||this.s.promiseLibrary;t.readConcern=t.readConcern?new b(t.readConcern.level):this.readConcern;const n=new L(this,e,t);return z(this.s.topology,n,r)}));Db.prototype.stats=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r={dbStats:true};if(e["scale"]!=null)r["scale"]=e["scale"];if(e.readPreference==null&&this.s.readPreference){e.readPreference=this.s.readPreference}const n=new _(this,e,null,r);return z(this.s.topology,n,t)};Db.prototype.listCollections=function(e,t){e=e||{};t=t||{};return new i(this.s.topology,new V(this,e,t),t)};Db.prototype.eval=C((function(e,t,r,n){const o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():t;r=o.length?o.shift()||{}:{};return E(this.s.topology,R,[this,e,t,r,n])}),"Db.eval is deprecated as of MongoDB version 3.2");Db.prototype.renameCollection=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=Object.assign({},r,{readPreference:l.PRIMARY});r.new_collection=true;const o=new q(this.collection(e),t,r);return z(this.s.topology,o,n)};Db.prototype.dropCollection=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new U(this,e,t);return z(this.s.topology,n,r)};Db.prototype.dropDatabase=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new P(this,e);return z(this.s.topology,r,t)};Db.prototype.collections=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new O(this,e);return z(this.s.topology,r,t)};Db.prototype.executeDbAdminCommand=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};t.readPreference=l.resolve(this,t);const n=new G(this,e,t);return z(this.s.topology,n,r)};Db.prototype.createIndex=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r?Object.assign({},r):{};const o=new F(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.ensureIndex=C((function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return E(this.s.topology,v,[this,e,t,r,n])}),"Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0");Db.prototype.addChild=function(e){if(this.s.parentDb)return this.s.parentDb.addChild(e);this.s.children.push(e)};Db.prototype.addUser=function(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};if(typeof e==="string"&&t!=null&&typeof t==="object"){r=t;t=null}const o=new T(this,e,t,r);return z(this.s.topology,o,n)};Db.prototype.removeUser=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new J(this,e,t);return z(this.s.topology,n,r)};Db.prototype.setProfilingLevel=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new j(this,e,t);return z(this.s.topology,n,r)};Db.prototype.profilingInfo=C((function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return E(this.s.topology,k,[this,e,t])}),"Db.profilingInfo is deprecated. Query the system.profile collection directly.");Db.prototype.profilingLevel=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};const r=new W(this,e);return z(this.s.topology,r,t)};Db.prototype.indexInformation=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};const n=new Y(this,e,t);return z(this.s.topology,n,r)};Db.prototype.unref=function(){this.s.topology.unref()};Db.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new m(this,e,t)};Db.prototype.getLogger=function(){return this.s.logger};Db.SYSTEM_NAMESPACE_COLLECTION=B.SYSTEM_NAMESPACE_COLLECTION;Db.SYSTEM_INDEX_COLLECTION=B.SYSTEM_INDEX_COLLECTION;Db.SYSTEM_PROFILE_COLLECTION=B.SYSTEM_PROFILE_COLLECTION;Db.SYSTEM_USER_COLLECTION=B.SYSTEM_USER_COLLECTION;Db.SYSTEM_COMMAND_COLLECTION=B.SYSTEM_COMMAND_COLLECTION;Db.SYSTEM_JS_COLLECTION=B.SYSTEM_JS_COLLECTION;e.exports=Db},8275:(e,t,r)=>{"use strict";let n;let o;let s;function loadCollection(){if(!n){n=r(5193)}return n}function loadCursor(){if(!o){o=r(7159)}return o}function loadDb(){if(!s){s=r(6662)}return s}e.exports={loadCollection:loadCollection,loadCursor:loadCursor,loadDb:loadDb}},3012:(e,t,r)=>{"use strict";const n=r(1545);const o=r(7746).retrieveBSON();const s=r(3111).MongoError;let i=undefined;try{i=r(5764)}catch(e){throw new s("Auto-encryption requested, but the module is not installed. "+"Please add `mongodb-client-encryption` as a dependency of your project")}if(i===undefined||typeof i.extension!=="function"){throw new s("loaded version of `mongodb-client-encryption` does not have property `extension`. "+"Please make sure you are loading the correct version of `mongodb-client-encryption`")}const a=i.extension(r(5517)).AutoEncrypter;const A=Symbol("internalClient");class Encrypter{constructor(e,t){this.bypassAutoEncryption=!!t.autoEncryption.bypassAutoEncryption;this.needsConnecting=false;if(t.maxPoolSize===0&&t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=e}else if(t.autoEncryption.keyVaultClient==null){t.autoEncryption.keyVaultClient=this.getInternalClient(e)}if(this.bypassAutoEncryption){t.autoEncryption.metadataClient=undefined}else if(t.maxPoolSize===0){t.autoEncryption.metadataClient=e}else{t.autoEncryption.metadataClient=this.getInternalClient(e)}t.autoEncryption.bson=Encrypter.makeBSON(t);this.autoEncrypter=new a(e,t.autoEncryption)}getInternalClient(e){if(!this[A]){const t={};for(const r of Object.keys(e.s.options)){if(["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].indexOf(r)!==-1)continue;t[r]=e.s.options[r]}t.minPoolSize=0;const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha","connectionPoolCreated","connectionPoolClosed","connectionCreated","connectionReady","connectionClosed","connectionCheckOutStarted","connectionCheckOutFailed","connectionCheckedOut","connectionCheckedIn","connectionPoolCleared"];this[A]=new n(e.s.url,t);for(const t of r){for(const r of e.listeners(t)){this[A].on(t,r)}}e.on("newListener",((e,t)=>{this[A].on(e,t)}));this.needsConnecting=true}return this[A]}connectInternalClient(e){if(this.needsConnecting){this.needsConnecting=false;return this[A].connect(e)}return e()}close(e,t,r){this.autoEncrypter.teardown((n=>{if(this[A]&&e!==this[A]){return this[A].close(t,r)}r(n)}))}static makeBSON(e){return(e||{}).bson||new o([o.Binary,o.Code,o.DBRef,o.Decimal128,o.Double,o.Int32,o.Long,o.Map,o.MaxKey,o.MinKey,o.ObjectId,o.BSONRegExp,o.Symbol,o.Timestamp])}}e.exports={Encrypter:Encrypter}},9386:(e,t,r)=>{"use strict";const n=r(3994).MongoNetworkError;const o=r(8072).MONGODB_ERROR_CODES;const s=new Set([o.HostUnreachable,o.HostNotFound,o.NetworkTimeout,o.ShutdownInProgress,o.PrimarySteppedDown,o.ExceededTimeLimit,o.SocketException,o.NotMaster,o.InterruptedAtShutdown,o.InterruptedDueToReplStateChange,o.NotMasterNoSlaveOk,o.NotMasterOrSecondary,o.StaleShardVersion,o.StaleEpoch,o.StaleConfig,o.RetryChangeStream,o.FailedToSatisfyReadPreference,o.CursorNotFound]);function isResumableError(e,t){if(e instanceof n){return true}if(t>=9){if(e.code===o.CursorNotFound){return true}return e.hasErrorLabel("ResumableChangeStreamError")}return s.has(e.code)}e.exports={GET_MORE_RESUMABLE_CODES:s,isResumableError:isResumableError,MONGODB_ERROR_CODES:o}},8072:e=>{"use strict";const t=Object.freeze({HostUnreachable:6,HostNotFound:7,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotMaster:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotMasterNoSlaveOk:13435,NotMasterOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernFailed:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,DuplicateKey:11e3,CannotCreateIndex:67,IndexOptionsConflict:85,IndexKeySpecsConflict:86,InvalidIndexSpecificationOption:197});e.exports=Object.freeze({MONGODB_ERROR_CODES:t})},5293:(e,t,r)=>{"use strict";const n=r(3111).MongoError;class Explain{constructor(e){if(typeof e==="boolean"){this.verbosity=e?"allPlansExecution":"queryPlanner"}else{this.verbosity=e}}static fromOptions(e){if(e==null||e.explain===undefined){return}const t=e.explain;if(typeof t==="boolean"||typeof t==="string"){return new Explain(e.explain)}throw new n(`explain must be a string or a boolean`)}}e.exports={Explain:Explain}},4190:(e,t,r)=>{"use strict";var n=r(2781),o=r(3837);e.exports=GridFSBucketReadStream;function GridFSBucketReadStream(e,t,r,o,s){this.s={bytesRead:0,chunks:e,cursor:null,expected:0,files:t,filter:o,init:false,expectedEnd:0,file:null,options:s,readPreference:r};n.Readable.call(this)}o.inherits(GridFSBucketReadStream,n.Readable);GridFSBucketReadStream.prototype._read=function(){var e=this;if(this.destroyed){return}waitForFile(e,(function(){doRead(e)}))};GridFSBucketReadStream.prototype.start=function(e){throwIfInitialized(this);this.s.options.start=e;return this};GridFSBucketReadStream.prototype.end=function(e){throwIfInitialized(this);this.s.options.end=e;return this};GridFSBucketReadStream.prototype.abort=function(e){var t=this;this.push(null);this.destroyed=true;if(this.s.cursor){this.s.cursor.close((function(r){t.emit("close");e&&e(r)}))}else{if(!this.s.init){t.emit("close")}e&&e()}};function throwIfInitialized(e){if(e.s.init){throw new Error("You cannot change options after the stream has entered"+"flowing mode!")}}function doRead(e){if(e.destroyed){return}e.s.cursor.next((function(t,r){if(e.destroyed){return}if(t){return __handleError(e,t)}if(!r){e.push(null);process.nextTick((()=>{e.s.cursor.close((function(t){if(t){__handleError(e,t);return}e.emit("close")}))}));return}var n=e.s.file.length-e.s.bytesRead;var o=e.s.expected++;var s=Math.min(e.s.file.chunkSize,n);if(r.n>o){var i="ChunkIsMissing: Got unexpected n: "+r.n+", expected: "+o;return __handleError(e,new Error(i))}if(r.n0){i["n"]={$gte:a}}}e.s.cursor=e.s.chunks.find(i).sort({n:1});if(e.s.readPreference){e.s.cursor.setReadPreference(e.s.readPreference)}e.s.expectedEnd=Math.ceil(r.length/r.chunkSize);e.s.file=r;try{e.s.bytesToTrim=handleEndOption(e,r,e.s.cursor,e.s.options)}catch(t){return __handleError(e,t)}e.emit("file",r)}))}function waitForFile(e,t){if(e.s.file){return t()}if(!e.s.init){init(e);e.s.init=true}e.once("file",(function(){t()}))}function handleStartOption(e,t,r){if(r&&r.start!=null){if(r.start>t.length){throw new Error("Stream start ("+r.start+") must not be "+"more than the length of the file ("+t.length+")")}if(r.start<0){throw new Error("Stream start ("+r.start+") must not be "+"negative")}if(r.end!=null&&r.endt.length){throw new Error("Stream end ("+n.end+") must not be "+"more than the length of the file ("+t.length+")")}if(n.start<0){throw new Error("Stream end ("+n.end+") must not be "+"negative")}var o=n.start!=null?Math.floor(n.start/t.chunkSize):0;r.limit(Math.ceil(n.end/t.chunkSize)-o);e.s.expectedEnd=Math.ceil(n.end/t.chunkSize);return Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}}function __handleError(e,t){e.emit("error",t)}},2573:(e,t,r)=>{"use strict";var n=r(2361).EventEmitter;var o=r(4190);var s=r(1413);var i=r(1371).shallowClone;var a=r(1371).toError;var A=r(3837);var c=r(1371).executeLegacyOperation;const l=r(1371).deprecateOptions;var u={bucketName:"fs",chunkSizeBytes:255*1024};e.exports=GridFSBucket;function GridFSBucket(e,t){n.apply(this);this.setMaxListeners(0);if(t&&typeof t==="object"){t=i(t);var r=Object.keys(u);for(var o=0;o=0){r={uploadDate:1};n=t.revision}else{n=-t.revision-1}}var s={filename:e};t={sort:r,skip:n,start:t&&t.start,end:t&&t.end};return new o(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,s,t)};GridFSBucket.prototype.rename=function(e,t,r){return c(this.s.db.s.topology,_rename,[this,e,t,r],{skipSessions:true})};function _rename(e,t,r,n){var o={_id:t};var s={$set:{filename:r}};e.s._filesCollection.updateOne(o,s,(function(e,r){if(e){return n(e)}if(!r.result.n){return n(a("File with id "+t+" not found"))}n()}))}GridFSBucket.prototype.drop=function(e){return c(this.s.db.s.topology,_drop,[this,e],{skipSessions:true})};GridFSBucket.prototype.getLogger=function(){return this.s.db.s.logger};function _drop(e,t){e.s._filesCollection.drop((function(r){if(r){return t(r)}e.s._chunksCollection.drop((function(e){if(e){return t(e)}return t()}))}))}},1413:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(3994);const s=r(6113);const i=r(2781);const a=r(3837);const A=r(1867).Buffer;const c=r(1371).deprecateOptions;const l=c({name:"GridFSBucketWriteStream",deprecatedOptions:["disableMD5"],optionsIndex:2},(function(e,t,r){r=r||{};i.Writable.call(this,r);this.bucket=e;this.chunks=e.s._chunksCollection;this.filename=t;this.files=e.s._filesCollection;this.options=r;this.done=false;this.id=r.id?r.id:o.BSON.ObjectId();this.chunkSizeBytes=this.options.chunkSizeBytes;this.bufToStore=A.alloc(this.chunkSizeBytes);this.length=0;this.md5=!r.disableMD5&&s.createHash("md5");this.n=0;this.pos=0;this.state={streamEnd:false,outstandingRequests:0,errored:false,aborted:false,promiseLibrary:this.bucket.s.promiseLibrary};if(!this.bucket.s.calledOpenUploadStream){this.bucket.s.calledOpenUploadStream=true;var n=this;checkIndexes(this,(function(){n.bucket.s.checkedIndexes=true;n.bucket.emit("index")}))}}));a.inherits(l,i.Writable);l.prototype.write=function(e,t,r){var n=this;return waitForIndexes(this,(function(){return doWrite(n,e,t,r)}))};l.prototype.abort=function(e){if(this.state.streamEnd){var t=new Error("Cannot abort a stream that has already completed");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}if(this.state.aborted){t=new Error("Cannot call abort() on a stream twice");if(typeof e==="function"){return e(t)}return this.state.promiseLibrary.reject(t)}this.state.aborted=true;this.chunks.deleteMany({files_id:this.id},(function(t){if(typeof e==="function")e(t)}))};l.prototype.end=function(e,t,r){var n=this;if(typeof e==="function"){r=e,e=null,t=null}else if(typeof t==="function"){r=t,t=null}if(checkAborted(this,r)){return}this.state.streamEnd=true;if(r){this.once("finish",(function(e){r(null,e)}))}if(!e){waitForIndexes(this,(function(){writeRemnant(n)}));return}this.write(e,t,(function(){writeRemnant(n)}))};function __handleError(e,t,r){if(e.state.errored){return}e.state.errored=true;if(r){return r(t)}e.emit("error",t)}function createChunkDoc(e,t,r){return{_id:o.BSON.ObjectId(),files_id:e,n:t,data:r}}function checkChunksIndex(e,t){e.chunks.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={files_id:1,n:1};e.chunks.createIndex(s,{background:false,unique:true},(function(e){if(e){return t(e)}t()}));return}return t(r)}var i=false;o.forEach((function(e){if(e.key){var t=Object.keys(e.key);if(t.length===2&&e.key.files_id===1&&e.key.n===1){i=true}}}));if(i){t()}else{s={files_id:1,n:1};var a=getWriteOptions(e);a.background=false;a.unique=true;e.chunks.createIndex(s,a,(function(e){if(e){return t(e)}t()}))}}))}function checkDone(e,t){if(e.done)return true;if(e.state.streamEnd&&e.state.outstandingRequests===0&&!e.state.errored){e.done=true;var r=createFilesDoc(e.id,e.length,e.chunkSizeBytes,e.md5&&e.md5.digest("hex"),e.filename,e.options.contentType,e.options.aliases,e.options.metadata);if(checkAborted(e,t)){return false}e.files.insertOne(r,getWriteOptions(e),(function(n){if(n){return __handleError(e,n,t)}e.emit("finish",r);e.emit("close")}));return true}return false}function checkIndexes(e,t){e.files.findOne({},{_id:1},(function(r,o){if(r){return t(r)}if(o){return t()}e.files.listIndexes().toArray((function(r,o){if(r){if(r.code===n.NamespaceNotFound){var s={filename:1,uploadDate:1};e.files.createIndex(s,{background:false},(function(r){if(r){return t(r)}checkChunksIndex(e,t)}));return}return t(r)}var i=false;o.forEach((function(e){var t=Object.keys(e.key);if(t.length===2&&e.key.filename===1&&e.key.uploadDate===1){i=true}}));if(i){checkChunksIndex(e,t)}else{s={filename:1,uploadDate:1};var a=getWriteOptions(e);a.background=false;e.files.createIndex(s,a,(function(r){if(r){return t(r)}checkChunksIndex(e,t)}))}}))}))}function createFilesDoc(e,t,r,n,o,s,i,a){var A={_id:e,length:t,chunkSize:r,uploadDate:new Date,filename:o};if(n){A.md5=n}if(s){A.contentType=s}if(i){A.aliases=i}if(a){A.metadata=a}return A}function doWrite(e,t,r,n){if(checkAborted(e,n)){return false}var o=A.isBuffer(t)?t:A.from(t,r);e.length+=o.length;if(e.pos+o.length0){var l=o.length-s;o.copy(e.bufToStore,e.pos,l,l+a);e.pos+=a;i-=a;if(i===0){if(e.md5){e.md5.update(e.bufToStore)}var u=createChunkDoc(e.id,e.n,A.from(e.bufToStore));++e.state.outstandingRequests;++c;if(checkAborted(e,n)){return false}e.chunks.insertOne(u,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;--c;if(!c){e.emit("drain",u);n&&n();checkDone(e)}}));i=e.chunkSizeBytes;e.pos=0;++e.n}s-=a;a=Math.min(i,s)}return false}function getWriteOptions(e){var t={};if(e.options.writeConcern){t.w=e.options.writeConcern.w;t.wtimeout=e.options.writeConcern.wtimeout;t.j=e.options.writeConcern.j}return t}function waitForIndexes(e,t){if(e.bucket.s.checkedIndexes){return t(false)}e.bucket.once("index",(function(){t(true)}));return true}function writeRemnant(e,t){if(e.pos===0){return checkDone(e,t)}++e.state.outstandingRequests;var r=A.alloc(e.pos);e.bufToStore.copy(r,0,0,e.pos);if(e.md5){e.md5.update(r)}var n=createChunkDoc(e.id,e.n,r);if(checkAborted(e,t)){return false}e.chunks.insertOne(n,getWriteOptions(e),(function(t){if(t){return __handleError(e,t)}--e.state.outstandingRequests;checkDone(e)}))}function checkAborted(e,t){if(e.state.aborted){if(typeof t==="function"){t(new Error("this stream has been aborted"))}return true}return false}e.exports=l},3890:(e,t,r)=>{"use strict";var n=r(3994).BSON.Binary,o=r(3994).BSON.ObjectID;var s=r(1867).Buffer;var Chunk=function(e,t,r){if(!(this instanceof Chunk))return new Chunk(e,t);this.file=e;var i=t==null?{}:t;this.writeConcern=r||{w:1};this.objectId=i._id==null?new o:i._id;this.chunkNumber=i.n==null?0:i.n;this.data=new n;if(typeof i.data==="string"){var a=s.alloc(i.data.length);a.write(i.data,0,i.data.length,"binary");this.data=new n(a)}else if(Array.isArray(i.data)){a=s.alloc(i.data.length);var A=i.data.join("");a.write(A,0,A.length,"binary");this.data=new n(a)}else if(i.data&&i.data._bsontype==="Binary"){this.data=i.data}else if(!s.isBuffer(i.data)&&!(i.data==null)){throw Error("Illegal chunk format")}this.internalPosition=0};Chunk.prototype.write=function(e,t){this.data.write(e,this.internalPosition,e.length,"binary");this.internalPosition=this.data.length();if(t!=null)return t(null,this);return this};Chunk.prototype.read=function(e){e=e==null||e===0?this.length():e;if(this.length()-this.internalPosition+1>=e){var t=this.data.read(this.internalPosition,e);this.internalPosition=this.internalPosition+e;return t}else{return""}};Chunk.prototype.readSlice=function(e){if(this.length()-this.internalPosition>=e){var t=null;if(this.data.buffer!=null){t=this.data.buffer.slice(this.internalPosition,this.internalPosition+e)}else{t=s.alloc(e);e=this.data.readInto(t,this.internalPosition)}this.internalPosition=this.internalPosition+e;return t}else{return null}};Chunk.prototype.eof=function(){return this.internalPosition===this.length()?true:false};Chunk.prototype.getc=function(){return this.read(1)};Chunk.prototype.rewind=function(){this.internalPosition=0;this.data=new n};Chunk.prototype.save=function(e,t){var r=this;if(typeof e==="function"){t=e;e={}}r.file.chunkCollection((function(n,o){if(n)return t(n);var s={upsert:true};for(var i in e)s[i]=e[i];for(i in r.writeConcern)s[i]=r.writeConcern[i];if(r.data.length()>0){r.buildMongoObject((function(e){var n={forceServerObjectId:true};for(var i in r.writeConcern){n[i]=r.writeConcern[i]}o.replaceOne({_id:r.objectId},e,s,(function(e){t(e,r)}))}))}else{t(null,r)}}))};Chunk.prototype.buildMongoObject=function(e){var t={files_id:this.file.fileId,n:this.chunkNumber,data:this.data};if(this.objectId!=null)t._id=this.objectId;e(t)};Chunk.prototype.length=function(){return this.data.length()};Object.defineProperty(Chunk.prototype,"position",{enumerable:true,get:function(){return this.internalPosition},set:function(e){this.internalPosition=e}});Chunk.DEFAULT_CHUNK_SIZE=1024*255;e.exports=Chunk},9406:(e,t,r)=>{"use strict";const n=r(3890);const o=r(3994).BSON.ObjectID;const s=r(3994).ReadPreference;const i=r(1867).Buffer;const a=r(7147);const A=r(3837).format;const c=r(3837);const l=r(3994).MongoError;const u=c.inherits;const h=r(2781).Duplex;const d=r(1371).shallowClone;const g=r(1371).executeLegacyOperation;const p=r(3837).deprecate;var E=0,m=1;const C=p((()=>{}),"GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead");var I=function GridStore(e,t,r,i,a){C();if(!(this instanceof GridStore))return new GridStore(e,t,r,i,a);this.db=e;if(typeof a==="undefined")a={};if(typeof i==="undefined"){i=r;r=undefined}else if(typeof i==="object"){a=i;i=r;r=undefined}if(t&&t._bsontype==="ObjectID"){this.referenceBy=m;this.fileId=t;this.filename=r}else if(typeof r==="undefined"){this.referenceBy=E;this.filename=t;if(i.indexOf("w")!=null){this.fileId=new o}}else{this.referenceBy=m;this.fileId=t;this.filename=r}this.mode=i==null?"r":i;this.options=a||{};this.isOpen=false;this.root=this.options["root"]==null?GridStore.DEFAULT_ROOT_COLLECTION:this.options["root"];this.position=0;this.readPreference=this.options.readPreference||e.options.readPreference||s.primary;this.writeConcern=_getWriteConcern(e,this.options);this.internalChunkSize=this.options["chunkSize"]==null?n.DEFAULT_CHUNK_SIZE:this.options["chunkSize"];var A=this.options.promiseLibrary||Promise;this.promiseLibrary=A;Object.defineProperty(this,"chunkSize",{enumerable:true,get:function(){return this.internalChunkSize},set:function(e){if(!(this.mode[0]==="w"&&this.position===0&&this.uploadDate==null)){this.internalChunkSize=this.internalChunkSize}else{this.internalChunkSize=e}}});Object.defineProperty(this,"md5",{enumerable:true,get:function(){return this.internalMd5}});Object.defineProperty(this,"chunkNumber",{enumerable:true,get:function(){return this.currentChunk&&this.currentChunk.chunkNumber?this.currentChunk.chunkNumber:null}})};I.prototype.open=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};if(this.mode!=="w"&&this.mode!=="w+"&&this.mode!=="r"){throw l.create({message:"Illegal mode "+this.mode,driver:true})}return g(this.db.s.topology,open,[this,e,t],{skipSessions:true})};var open=function(e,t,r){var n=_getWriteConcern(e.db,e.options);if(e.mode==="w"||e.mode==="w+"){var o=e.collection();o.ensureIndex([["filename",1]],n,(function(){var t=e.chunkCollection();var o=d(n);o.unique=true;t.ensureIndex([["files_id",1],["n",1]],o,(function(){_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}))}))}else{_open(e,n,(function(t,n){if(t)return r(t);e.isOpen=true;r(t,n)}))}};I.prototype.eof=function(){return this.position===this.length?true:false};I.prototype.getc=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,getc,[this,e,t],{skipSessions:true})};var getc=function(e,t,r){if(e.eof()){r(null,null)}else if(e.currentChunk.eof()){nthChunk(e,e.currentChunk.chunkNumber+1,(function(t,n){e.currentChunk=n;e.position=e.position+1;r(t,e.currentChunk.getc())}))}else{e.position=e.position+1;r(null,e.currentChunk.getc())}};I.prototype.puts=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};var n=e.match(/\n$/)==null?e+"\n":e;return g(this.db.s.topology,this.write.bind(this),[n,t,r],{skipSessions:true})};I.prototype.stream=function(){return new GridStoreStream(this)};I.prototype.write=function write(e,t,r,n){if(typeof r==="function")n=r,r={};r=r||{};return g(this.db.s.topology,_writeNormal,[this,e,t,r,n],{skipSessions:true})};I.prototype.destroy=function destroy(){if(!this.writable)return;this.readable=false;if(this.writable){this.writable=false;this._q.length=0;this.emit("close")}};I.prototype.writeFile=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};return g(this.db.s.topology,writeFile,[this,e,t,r],{skipSessions:true})};var writeFile=function(e,t,r,o){if(typeof t==="string"){a.open(t,"r",(function(t,r){if(t)return o(t);e.writeFile(r,o)}));return}e.open((function(e,r){if(e)return o(e,r);a.fstat(t,(function(e,s){if(e)return o(e,r);var A=0;var c=0;var writeChunk=function(){var e=i.alloc(r.chunkSize);a.read(t,e,0,e.length,A,(function(e,i,l){if(e)return o(e,r);A=A+i;var u=new n(r,{n:c++},r.writeConcern);u.write(l.slice(0,i),(function(e,n){if(e)return o(e,r);n.save({},(function(e){if(e)return o(e,r);r.position=r.position+i;r.currentChunk=n;if(A>=s.size){a.close(t,(function(e){if(e)return o(e);r.close((function(e){if(e)return o(e,r);return o(null,r)}))}))}else{return process.nextTick(writeChunk)}}))}))}))};process.nextTick(writeChunk)}))}))};I.prototype.close=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,close,[this,e,t],{skipSessions:true})};var close=function(e,t,r){if(e.mode[0]==="w"){t=Object.assign({},e.writeConcern,t);if(e.currentChunk!=null&&e.currentChunk.position>0){e.currentChunk.save({},(function(n){if(n&&typeof r==="function")return r(n);e.collection((function(n,o){if(n&&typeof r==="function")return r(n);if(e.uploadDate!=null){buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}else{e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}}))}))}else{e.collection((function(n,o){if(n&&typeof r==="function")return r(n);e.uploadDate=new Date;buildMongoObject(e,(function(e,n){if(e){if(typeof r==="function")return r(e);else throw e}o.save(n,t,(function(e){if(typeof r==="function")r(e,n)}))}))}))}}else if(e.mode[0]==="r"){if(typeof r==="function")r(null,null)}else{if(typeof r==="function")r(l.create({message:A("Illegal mode %s",e.mode),driver:true}))}};I.prototype.chunkCollection=function(e){if(typeof e==="function")return this.db.collection(this.root+".chunks",e);return this.db.collection(this.root+".chunks")};I.prototype.unlink=function(e,t){if(typeof e==="function")t=e,e={};e=e||{};return g(this.db.s.topology,unlink,[this,e,t],{skipSessions:true})};var unlink=function(e,t,r){deleteChunks(e,(function(t){if(t!==null){t.message="at deleteChunks: "+t.message;return r(t)}e.collection((function(t,n){if(t!==null){t.message="at collection: "+t.message;return r(t)}n.remove({_id:e.fileId},e.writeConcern,(function(t){r(t,e)}))}))}))};I.prototype.collection=function(e){if(typeof e==="function")this.db.collection(this.root+".files",e);return this.db.collection(this.root+".files")};I.prototype.readlines=function(e,t,r){var n=Array.prototype.slice.call(arguments,0);r=typeof n[n.length-1]==="function"?n.pop():undefined;e=n.length?n.shift():"\n";e=e||"\n";t=n.length?n.shift():{};return g(this.db.s.topology,readlines,[this,e,t,r],{skipSessions:true})};var readlines=function(e,t,r,n){e.read((function(e,r){if(e)return n(e);var o=r.toString().split(t);o=o.length>0?o.splice(0,o.length-1):[];for(var s=0;s=s){var A=e.currentChunk.readSlice(s-a._index);A.copy(a,a._index);e.position=e.position+a.length;if(s===0&&a.length===0)return o(l.create({message:"File does not exist",driver:true}),null);return o(null,a)}A=e.currentChunk.readSlice(e.currentChunk.length()-e.currentChunk.position);A.copy(a,a._index);a._index+=A.length;nthChunk(e,e.currentChunk.chunkNumber+1,(function(r,n){if(r)return o(r);if(n.length()>0){e.currentChunk=n;e.read(t,a,o)}else{if(a._index>0){o(null,a)}else{o(l.create({message:"no chunks found for file, possibly corrupt",driver:true}),null)}}}))};I.prototype.tell=function(e){var t=this;if(typeof e==="function")return e(null,this.position);return new t.promiseLibrary((function(e){e(t.position)}))};I.prototype.seek=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,1);n=typeof o[o.length-1]==="function"?o.pop():undefined;t=o.length?o.shift():null;r=o.length?o.shift():{};return g(this.db.s.topology,seek,[this,e,t,r,n],{skipSessions:true})};var seek=function(e,t,r,n,o){if(e.mode!=="r"){return o(l.create({message:"seek is only supported for mode r",driver:true}))}var s=r==null?I.IO_SEEK_SET:r;var i=t;var a=0;if(s===I.IO_SEEK_CUR){a=e.position+i}else if(s===I.IO_SEEK_END){a=e.length+i}else{a=i}var A=Math.floor(a/e.chunkSize);var seekChunk=function(){nthChunk(e,A,(function(t,r){if(t)return o(t,null);if(r==null)return o(new Error("no chunk found"));e.currentChunk=r;e.position=a;e.currentChunk.position=e.position%e.chunkSize;o(t,e)}))};seekChunk()};var _open=function(e,t,r){var s=e.collection();var i=e.referenceBy===m?{_id:e.fileId}:{filename:e.filename};i=null==e.fileId&&e.filename==null?null:i;t.readPreference=e.readPreference;if(i!=null){s.findOne(i,t,(function(s,i){if(s){return error(s)}if(i!=null){e.fileId=i._id;e.filename=e.mode==="r"||e.filename===undefined?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(e.mode!=="r"){e.fileId=e.fileId==null?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0}else{e.length=0;var a=e.fileId._bsontype==="ObjectID"?e.fileId.toHexString():e.fileId;return error(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?a:e.filename),driver:true}),e)}if(e.mode==="r"){nthChunk(e,0,t,(function(t,n){if(t)return error(t);e.currentChunk=n;e.position=0;r(null,e)}))}else if(e.mode==="w"&&i){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w"){e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}))}else{e.fileId=null==e.fileId?new o:e.fileId;e.contentType=I.DEFAULT_CONTENT_TYPE;e.internalChunkSize=e.internalChunkSize==null?n.DEFAULT_CHUNK_SIZE:e.internalChunkSize;e.length=0;if(e.mode==="w"){deleteChunks(e,t,(function(t){if(t)return error(t);e.currentChunk=new n(e,{n:0},e.writeConcern);e.contentType=e.options["content_type"]==null?e.contentType:e.options["content_type"];e.internalChunkSize=e.options["chunk_size"]==null?e.internalChunkSize:e.options["chunk_size"];e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=0;r(null,e)}))}else if(e.mode==="w+"){nthChunk(e,lastChunkNumber(e),t,(function(t,o){if(t)return error(t);e.currentChunk=o==null?new n(e,{n:0},e.writeConcern):o;e.currentChunk.position=e.currentChunk.data.length();e.metadata=e.options["metadata"]==null?e.metadata:e.options["metadata"];e.aliases=e.options["aliases"]==null?e.aliases:e.options["aliases"];e.position=e.length;r(null,e)}))}}function error(e){if(error.err)return;r(error.err=e)}};var writeBuffer=function(e,t,r,o){if(typeof r==="function"){o=r;r=null}var s=typeof r==="boolean"?r:false;if(e.mode!=="w"){o(l.create({message:A("file with id %s not opened for writing",e.referenceBy===m?e.referenceBy:e.filename),driver:true}),null)}else{if(e.currentChunk.position+t.length>=e.chunkSize){var i=e.currentChunk.chunkNumber;var a=e.chunkSize-e.currentChunk.position;var c=t.slice(0,a);var u=t.slice(a);var h=[e.currentChunk.write(c)];while(u.length>=e.chunkSize){var d=new n(e,{n:i+1},e.writeConcern);c=u.slice(0,e.chunkSize);u=u.slice(e.chunkSize);i=i+1;d.write(c);h.push(d)}e.currentChunk=new n(e,{n:i+1},e.writeConcern);if(u.length>0)e.currentChunk.write(u);e.position=e.position+t.length;var g=h.length;for(var p=0;p=t.length)return s("offset larger than size of file",null);if(r&&r>t.length)return s("length is larger than the size of the file",null);if(n&&r&&n+r>t.length)return s("offset and length is larger than the size of the file",null);if(n!=null){t.seek(n,(function(e,t){if(e)return s(e);t.read(r,s)}))}else{t.read(r,s)}}))};I.readlines=function(e,t,r,n,o){var s=Array.prototype.slice.call(arguments,2);o=typeof s[s.length-1]==="function"?s.pop():undefined;r=s.length?s.shift():null;n=s.length?s.shift():null;n=n||{};return g(e.s.topology,readlinesStatic,[e,t,r,n,o],{skipSessions:true})};var readlinesStatic=function(e,t,r,n,o){var s=r==null?"\n":r;new I(e,t,"r",n).open((function(e,t){if(e)return o(e);t.readlines(s,o)}))};I.unlink=function(e,t,r,n){var o=Array.prototype.slice.call(arguments,2);n=typeof o[o.length-1]==="function"?o.pop():undefined;r=o.length?o.shift():{};r=r||{};return g(e.s.topology,unlinkStatic,[this,e,t,r,n],{skipSessions:true})};var unlinkStatic=function(e,t,r,n,o){var s=_getWriteConcern(t,n);if(r.constructor===Array){var i=0;for(var a=0;ae.totalBytesToRead){e.totalBytesToRead=e.totalBytesToRead-r._index;e.push(r.slice(0,r._index))}if(e.totalBytesToRead<=0){e.endCalled=true}}))};var t=e.gs.length{"use strict";const n=r(1117);const o=r(6662);const s=r(2361).EventEmitter;const i=r(3837).inherits;const a=r(3994).MongoError;const A=r(3994).ValidServerApiVersions;const c=r(3837).deprecate;const l=r(2481);const u=r(1371).MongoDBNamespace;const h=r(4485);const d=r(1371).maybePromise;const g=r(2632);const p=r(5210).connect;const E=r(5210).validOptions;function MongoClient(e,t){t=t||{};if(!(this instanceof MongoClient))return new MongoClient(e,t);s.call(this);if(t.autoEncryption)r(3012);if(t.serverApi){const e=typeof t.serverApi==="string"?{version:t.serverApi}:t.serverApi;const r=e&&e.version;if(!r){throw new a(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${A.join('", "')}"]`)}if(!A.some((e=>e===r))){throw new a(`Invalid server API version=${r}; must be in the following enum: ["${A.join('", "')}"]`)}t.serverApi=e}this.s={url:e,options:t,promiseLibrary:t&&t.promiseLibrary||Promise,dbCache:new Map,sessions:new Set,writeConcern:l.fromOptions(t),readPreference:h.fromOptions(t)||h.primary,namespace:new u("admin")}}i(MongoClient,s);Object.defineProperty(MongoClient.prototype,"writeConcern",{enumerable:true,get:function(){return this.s.writeConcern}});Object.defineProperty(MongoClient.prototype,"readPreference",{enumerable:true,get:function(){return this.s.readPreference}});MongoClient.prototype.connect=function(e){if(typeof e==="string"){throw new TypeError("`connect` only accepts a callback")}const t=this;return d(this,e,(e=>{const r=E(t.s.options);if(r)return e(r);p(t,t.s.url,t.s.options,(r=>{if(r)return e(r);e(null,t)}))}))};MongoClient.prototype.logout=c((function(e,t){if(typeof e==="function")t=e,e={};if(typeof t==="function")t(null,true)}),"Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient");MongoClient.prototype.close=function(e,t){if(typeof e==="function"){t=e;e=false}const r=this;return d(this,t,(t=>{const completeClose=e=>{r.emit("close",r);if(!(r.topology instanceof g)){for(const e of r.s.dbCache){e[1].emit("close",r)}}r.removeAllListeners("close");t(e)};if(r.topology==null){completeClose();return}r.topology.close(e,(t=>{const n=r.topology.s.options.encrypter;if(n){return n.close(r,e,(e=>{completeClose(t||e)}))}completeClose(t)}))}))};MongoClient.prototype.db=function(e,t){t=t||{};if(!e){e=this.s.options.dbName}const r=Object.assign({},this.s.options,t);if(this.s.dbCache.has(e)&&r.returnNonCachedInstance!==true){return this.s.dbCache.get(e)}r.promiseLibrary=this.s.promiseLibrary;if(!this.topology){throw new a("MongoClient must be connected before calling MongoClient.prototype.db")}const n=new o(e,this.topology,r);this.s.dbCache.set(e,n);return n};MongoClient.prototype.isConnected=c((function(e){e=e||{};if(!this.topology)return false;return this.topology.isConnected(e)}),"isConnected is deprecated and will be removed in the next major version");MongoClient.connect=function(e,t,r){const n=Array.prototype.slice.call(arguments,1);r=typeof n[n.length-1]==="function"?n.pop():undefined;t=n.length?n.shift():null;t=t||{};const o=new MongoClient(e,t);return o.connect(r)};MongoClient.prototype.startSession=function(e){e=Object.assign({explicit:true},e);if(!this.topology){throw new a("Must connect to a server before calling this method")}return this.topology.startSession(e,this.s.options)};MongoClient.prototype.withSession=function(e,t){if(typeof e==="function")t=e,e=undefined;const r=this.startSession(e);let cleanupHandler=(e,t,n)=>{cleanupHandler=()=>{throw new ReferenceError("cleanupHandler was called too many times")};n=Object.assign({throw:true},n);r.endSession();if(e){if(n.throw)throw e;return Promise.reject(e)}};try{const e=t(r);return Promise.resolve(e).then((e=>cleanupHandler(null,e))).catch((e=>cleanupHandler(e,null,{throw:true})))}catch(e){return cleanupHandler(e,null,{throw:false})}};MongoClient.prototype.watch=function(e,t){e=e||[];t=t||{};if(!Array.isArray(e)){t=e;e=[]}return new n(this,e,t)};MongoClient.prototype.getLogger=function(){return this.s.options.logger};e.exports=MongoClient},7057:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(6113);const a=r(1371).handleCallback;const A=r(1371).toError;const c=r(1371).emitWarning;class AddUserOperation extends o{constructor(e,t,r,n){super(e,n);this.username=t;this.password=r}_buildCommand(){const e=this.db;const t=this.username;const r=this.password;const n=this.options;let o=[];if(Array.isArray(n.roles))o=n.roles;if(typeof n.roles==="string")o=[n.roles];if(o.length===0){c("Creating a user without roles is deprecated in MongoDB >= 2.6")}if((e.databaseName.toLowerCase()==="admin"||n.dbName==="admin")&&!Array.isArray(n.roles)){o=["root"]}else if(!Array.isArray(n.roles)){o=["dbOwner"]}const s=e.s.topology.lastIsMaster().maxWireVersion>=7;let a=r;if(!s){const e=i.createHash("md5");e.update(t+":mongo:"+r);a=e.digest("hex")}const A={createUser:t,customData:n.customData||{},roles:o,digestPassword:s};if(typeof r==="string"){A.pwd=a}return A}execute(e){const t=this.options;if(t.digestPassword!=null){return e(A("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."))}super.execute(((t,r)=>{if(!t){return a(e,t,r)}return a(e,t,null)}))}}s(AddUserOperation,n.WRITE_OPERATION);e.exports=AddUserOperation},1554:(e,t,r)=>{"use strict";const n=r(1189);const o=r(3994).MongoError;const s=r(1178).maxWireVersion;const i=r(3994).ReadPreference;const a=r(1018).Aspect;const A=r(1018).defineAspects;const c=1;const l=8;class AggregateOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.target=e.s.namespace&&e.s.namespace.collection?e.s.namespace.collection:c;this.pipeline=t;this.hasWriteStage=false;if(typeof r.out==="string"){this.pipeline=this.pipeline.concat({$out:r.out});this.hasWriteStage=true}else if(t.length>0){const e=t[t.length-1];if(e.$out||e.$merge){this.hasWriteStage=true}}if(this.hasWriteStage){this.readPreference=i.primary}if(this.explain&&this.writeConcern){throw new o('"explain" cannot be used on an aggregate call with writeConcern')}if(r.cursor!=null&&typeof r.cursor!=="object"){throw new o("cursor options must be an object")}}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}execute(e,t){const r=this.options;const n=s(e);const o={aggregate:this.target,pipeline:this.pipeline};if(this.hasWriteStage&&n=5){if(this.hasWriteStage&&this.writeConcern){Object.assign(o,{writeConcern:this.writeConcern})}}if(r.bypassDocumentValidation===true){o.bypassDocumentValidation=r.bypassDocumentValidation}if(typeof r.allowDiskUse==="boolean"){o.allowDiskUse=r.allowDiskUse}if(r.hint){o.hint=r.hint}if(this.explain){r.full=false}o.cursor=r.cursor||{};if(r.batchSize&&!this.hasWriteStage){o.cursor.batchSize=r.batchSize}super.executeCommand(e,o,t)}}A(AggregateOperation,[a.READ_OPERATION,a.RETRYABLE,a.EXECUTE_WITH_SELECTION,a.EXPLAINABLE]);e.exports=AggregateOperation},6976:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(3994).MongoError;const i=r(1018).OperationBase;class BulkWriteOperation extends i{constructor(e,t,r){super(r);this.collection=e;this.operations=t}execute(e){const t=this.collection;const r=this.operations;let i=this.options;if(t.s.options.ignoreUndefined){i=Object.assign({},i);i.ignoreUndefined=t.s.options.ignoreUndefined}const a=i.ordered===true||i.ordered==null?t.initializeOrderedBulkOp(i):t.initializeUnorderedBulkOp(i);let A=false;try{for(let e=0;e{if(!r&&t){return e(t,null)}e(null,r)}))}}e.exports=BulkWriteOperation},6716:(e,t,r)=>{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(2226).createIndex;const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(2226).ensureIndex;const c=r(2226).evaluate;const l=r(2226).executeCommand;const u=r(1371).handleCallback;const h=r(2226).indexInformation;const d=r(3994).BSON.Long;const g=r(3994).MongoError;const p=r(3994).ReadPreference;const E=r(2296).insertDocuments;const m=r(2296).updateDocuments;const C='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}';function createIndex(e,t,r,n){s(e.s.db,e.collectionName,t,r,n)}function createIndexes(e,t,r,n){const o=e.s.topology.capabilities();for(let e=0;e{e[t]=1}));h.group.key=e}d=Object.assign({},d);d.readPreference=p.resolve(e,d);a(h,e,d);try{i(h,e,d)}catch(e){return g(e,null)}l(e.s.db,h,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.retval)}))}else{const i=s!=null&&s._bsontype==="Code"?s.scope:{};i.ns=e.collectionName;i.keys=t;i.condition=r;i.initial=n;const a=C.replace(/ reduce;/,s.toString()+";");c(e.s.db,new o(a,i),null,d,((e,t)=>{if(e)return u(g,e,null);u(g,null,t.result||t)}))}}function indexes(e,t,r){t=Object.assign({},{full:true},t);h(e.s.db,e.collectionName,t,r)}function indexExists(e,t,r,n){indexInformation(e,r,((e,r)=>{if(e!=null)return u(n,e,null);if(!Array.isArray(t))return u(n,null,r[t]!=null);for(let e=0;e{if(n)return u(r,n,null);if(s==null)return u(r,new Error("no result returned for parallelCollectionScan"),null);t=Object.assign({explicitlyIgnoreSession:true},t);const i=[];if(o)t.raw=o;for(let r=0;r{if(o==null)return;if(t==null)return u(o,null,null);if(e)return u(o,e,null);u(o,null,r)}))}e.exports={createIndex:createIndex,createIndexes:createIndexes,ensureIndex:ensureIndex,group:group,indexes:indexes,indexExists:indexExists,indexInformation:indexInformation,parallelCollectionScan:parallelCollectionScan,save:save}},286:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;let s;function loadCollection(){if(!s){s=r(5193)}return s}class CollectionsOperation extends n{constructor(e,t){super(t);this.db=e}execute(e){const t=this.db;let r=this.options;let n=loadCollection();r=Object.assign({},r,{nameOnly:true});t.listCollections({},r).toArray(((r,s)=>{if(r!=null)return o(e,r,null);s=s.filter((e=>e.name.indexOf("$")===-1));o(e,null,s.map((e=>new n(t,t.s.topology,t.databaseName,e.name,t.s.pkFactory,t.s.options))))}))}}e.exports=CollectionsOperation},499:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(1371).applyWriteConcern;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=r(1371).MongoDBNamespace;const u=r(7703).extractCommand;const h=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];class CommandOperation extends o{constructor(e,t,r,o){super(t);if(!this.hasAspect(n.WRITE_OPERATION)){if(r!=null){this.options.readPreference=c.resolve(r,t)}else{this.options.readPreference=c.resolve(e,t)}}else{if(r!=null){s(this.options,{db:e,coll:r},this.options)}else{s(this.options,{db:e},this.options)}this.options.readPreference=c.primary}this.db=e;if(o!=null){this.command=o}if(r!=null){this.collection=r}}_buildCommand(){if(this.command!=null){return this.command}}execute(e){const t=this.db;const r=Object.assign({},this.options);if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new A("topology was destroyed"))}let o;try{o=this._buildCommand()}catch(t){return e(t)}const s=r.dbName||r.authdb||t.databaseName;if(this.hasAspect(n.WRITE_OPERATION)){if(r.writeConcern&&(!r.session||!r.session.inTransaction())){o.writeConcern=r.writeConcern}}if(t.s.logger.isDebug()){const e=u(o);t.s.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:o)} against ${s}.$cmd with options [${JSON.stringify(i(h,r))}]`)}const c=this.namespace!=null?this.namespace:new l(s,"$cmd");t.s.topology.command(c,o,r,((t,n)=>{if(t)return a(e,t);if(r.full)return a(e,null,n);a(e,null,n.result)}))}}e.exports=CommandOperation},1189:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).OperationBase;const s=r(3994).ReadPreference;const i=r(7289);const a=r(2481);const A=r(1178).maxWireVersion;const c=r(1371).decorateWithExplain;const l=r(5474).commandSupportsReadConcern;const u=r(3111).MongoError;const h=r(7703).extractCommand;const d=5;class CommandOperationV2 extends o{constructor(e,t,r){super(t);this.ns=e.s.namespace.withCollection("$cmd");const o=this.hasAspect(n.NO_INHERIT_OPTIONS)?undefined:e;this.readPreference=this.hasAspect(n.WRITE_OPERATION)?s.primary:s.resolve(o,this.options);this.readConcern=resolveReadConcern(o,this.options);this.writeConcern=resolveWriteConcern(o,this.options);if(r&&typeof r.fullResponse==="boolean"){this.fullResponse=true}this.options.readPreference=this.readPreference;if(e.s.logger){this.logger=e.s.logger}else if(e.s.db&&e.s.db.logger){this.logger=e.s.db.logger}}executeCommand(e,t,r){this.server=e;const o=this.options;const s=A(e);const i=this.session&&this.session.inTransaction();if(this.readConcern&&l(t)&&!i){Object.assign(t,{readConcern:this.readConcern})}if(o.collation&&s=d){if(this.writeConcern&&this.hasAspect(n.WRITE_OPERATION)){Object.assign(t,{writeConcern:this.writeConcern})}if(o.collation&&typeof o.collation==="object"){Object.assign(t,{collation:o.collation})}}if(typeof o.maxTimeMS==="number"){t.maxTimeMS=o.maxTimeMS}if(typeof o.comment==="string"){t.comment=o.comment}if(this.hasAspect(n.EXPLAINABLE)&&this.explain){if(s<6&&t.aggregate){t.explain=true}else{t=c(t,this.explain)}}if(this.logger&&this.logger.isDebug()){const e=h(t);this.logger.debug(`executing command ${JSON.stringify(e.shouldRedact?`${e.name} details REDACTED`:t)} against ${this.ns}`)}e.command(this.ns.toString(),t,this.options,((e,t)=>{if(e){r(e,null);return}if(this.fullResponse){r(null,t);return}r(null,t.result)}))}}function resolveWriteConcern(e,t){return a.fromOptions(t)||e&&e.writeConcern}function resolveReadConcern(e,t){return i.fromOptions(t)||e&&e.readConcern}e.exports=CommandOperationV2},2296:(e,t,r)=>{"use strict";const n=r(1371).applyRetryableWrites;const o=r(1371).applyWriteConcern;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).MongoError;const u=r(3994).ReadPreference;const h=r(1371).toError;const d=r(4847).CursorState;const g=r(1178).maxWireVersion;function buildCountCommand(e,t,r){const n=r.skip;const o=r.limit;let a=r.hint;const A=r.maxTimeMS;t=t||{};const c={count:r.collectionName,query:t};if(e.s.numberOfRetries){if(e.options.hint){a=e.options.hint}else if(e.cmd.hint){a=e.cmd.hint}s(c,e,e.cmd)}else{s(c,e,r)}if(typeof n==="number")c.skip=n;if(typeof o==="number")c.limit=o;if(typeof A==="number")c.maxTimeMS=A;if(a)c.hint=a;i(c,e);return c}function findAndModify(e,t,r,i,l,h){const d={findAndModify:e.collectionName,query:t};r=A(r);if(r){d.sort=r}d.new=l.new?true:false;d.remove=l.remove?true:false;d.upsert=l.upsert?true:false;const g=l.projection||l.fields;if(g){d.fields=g}if(l.arrayFilters){d.arrayFilters=l.arrayFilters;delete l.arrayFilters}if(i&&!l.remove){d.update=i}if(l.maxTimeMS)d.maxTimeMS=l.maxTimeMS;l.serializeFunctions=l.serializeFunctions||e.s.serializeFunctions;l.checkKeys=false;let p=Object.assign({},l);p=n(p,e.s.db);p=o(p,{db:e.s.db,collection:e},l);if(p.writeConcern){d.writeConcern=p.writeConcern}if(p.bypassDocumentValidation===true){d.bypassDocumentValidation=p.bypassDocumentValidation}p.readPreference=u.primary;try{s(d,e,p)}catch(e){return h(e,null)}a(e.s.db,d,p,((e,t)=>{if(e)return c(h,e,null);return c(h,null,t)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new l("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(h(e));if(!Array.isArray(t))return c(n,null,[]);if(o)return c(n,null,t);c(n,null,processResults(t))}))}function prepareDocs(e,t,r){const n=typeof r.forceServerObjectId==="boolean"?r.forceServerObjectId:e.s.db.options.forceServerObjectId;if(n===true){return t}return t.map((t=>{if(n!==true&&t._id==null){t._id=e.s.pkFactory.createPk()}return t}))}function nextObject(e,t){if(e.s.state===d.CLOSED||e.isDead&&e.isDead()){return c(t,l.create({message:"Cursor is closed",driver:true}))}if(e.s.state===d.INIT&&e.cmd&&e.cmd.sort){try{e.cmd.sort=A(e.cmd.sort)}catch(e){return c(t,e)}}e._next(((r,n)=>{e.s.state=d.OPEN;if(r)return c(t,r);c(t,null,n)}))}function insertDocuments(e,t,r,s){if(typeof r==="function")s=r,r={};r=r||{};t=Array.isArray(t)?t:[t];let i=Object.assign({},r);i=n(i,e.s.db);i=o(i,{db:e.s.db,collection:e},r);if(i.keepGoing===true)i.ordered=false;i.serializeFunctions=r.serializeFunctions||e.s.serializeFunctions;t=prepareDocs(e,t,r);e.s.topology.insert(e.s.namespace,t,i,((e,r)=>{if(s==null)return;if(e)return c(s,e);if(r==null)return c(s,null,null);if(r.result.code)return c(s,h(r.result));if(r.result.writeErrors)return c(s,h(r.result.writeErrors[0]));r.ops=t;c(s,null,r)}))}function removeDocuments(e,t,r,i){if(typeof r==="function"){i=r,r={}}else if(typeof t==="function"){i=t;r={};t={}}r=r||{};let a=Object.assign({},r);a=n(a,e.s.db);a=o(a,{db:e.s.db,collection:e},r);if(t==null)t={};const A={q:t,limit:0};if(r.single){A.limit=1}else if(a.retryWrites){a.retryWrites=false}if(r.hint){A.hint=r.hint}try{s(a,e,r)}catch(e){return i(e,null)}if(r.explain!==undefined&&g(e.s.topology)<3){return i?i(new l(`server does not support explain on remove`)):undefined}e.s.topology.remove(e.s.namespace,[A],a,((e,t)=>{if(i==null)return;if(e)return c(i,e,null);if(t==null)return c(i,null,null);if(t.result.code)return c(i,h(t.result));if(t.result.writeErrors){return c(i,h(t.result.writeErrors[0]))}c(i,null,t)}))}function updateDocuments(e,t,r,i,a){if("function"===typeof i)a=i,i=null;if(i==null)i={};if(!("function"===typeof a))a=null;if(t==null||typeof t!=="object")return a(h("selector must be a valid JavaScript object"));if(r==null||typeof r!=="object")return a(h("document must be a valid JavaScript object"));let A=Object.assign({},i);A=n(A,e.s.db);A=o(A,{db:e.s.db,collection:e},i);A.serializeFunctions=i.serializeFunctions||e.s.serializeFunctions;const u={q:t,u:r};u.upsert=i.upsert!==void 0?!!i.upsert:false;u.multi=i.multi!==void 0?!!i.multi:false;if(i.hint){u.hint=i.hint}if(A.arrayFilters){u.arrayFilters=A.arrayFilters;delete A.arrayFilters}if(A.retryWrites&&u.multi){A.retryWrites=false}try{s(A,e,i)}catch(e){return a(e,null)}if(i.explain!==undefined&&g(e.s.topology)<3){return a?a(new l(`server does not support explain on update`)):undefined}e.s.topology.update(e.s.namespace,[u],A,((e,t)=>{if(a==null)return;if(e)return c(a,e,null);if(t==null)return c(a,null,null);if(t.result.code)return c(a,h(t.result));if(t.result.writeErrors)return c(a,h(t.result.writeErrors[0]));c(a,null,t)}))}e.exports={buildCountCommand:buildCountCommand,findAndModify:findAndModify,indexInformation:indexInformation,nextObject:nextObject,prepareDocs:prepareDocs,insertDocuments:insertDocuments,removeDocuments:removeDocuments,updateDocuments:updateDocuments}},5210:(e,t,r)=>{"use strict";const n=r(3837).deprecate;const o=r(3994).Logger;const s=r(3994).MongoCredentials;const i=r(3994).MongoError;const a=r(2048);const A=r(2632);const c=r(3994).parseConnectionString;const l=r(7289);const u=r(3994).ReadPreference;const h=r(382);const d=r(8421);const g=r(3994).Sessions.ServerSessionPool;const p=r(1371).emitDeprecationWarning;const E=r(1371).emitWarningOnce;const m=r(7147);const C=r(2481);const I=r(897).CMAP_EVENT_NAMES;let y;function loadClient(){if(!y){y=r(1545)}return y}const B=n(r(8729),"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.");const Q={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"};const b=["timeout","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha","all","fullsetup","open"];const w=new Set(["DEFAULT","PLAIN","GSSAPI","MONGODB-CR","MONGODB-X509","MONGODB-AWS","SCRAM-SHA-1","SCRAM-SHA-256"]);const S=["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","writeConcern","forceServerObjectId","serializeFunctions","ignoreUndefined","raw","bufferMaxEntries","readPreference","pkFactory","promiseLibrary","readConcern","maxStalenessSeconds","loggerLevel","logger","promoteValues","promoteBuffers","promoteLongs","bsonRegExp","domainsEnabled","checkServerIdentity","validateOptions","appname","auth","user","password","authMechanism","compression","fsync","readPreferenceTags","numberOfRetries","auto_reconnect","minSize","monitorCommands","serverApi","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"];const v=["native_parser"];const R=["server","replset","replSet","mongos","db"];function validOptions(e){const t=S.concat(R);for(const r in e){if(v.indexOf(r)!==-1){continue}if(t.indexOf(r)===-1){if(e.validateOptions){return new i(`option ${r} is not supported`)}else{E(`the options [${r}] is not supported`)}}if(R.indexOf(r)!==-1){E(`the server/replset/mongos/db options are deprecated, `+`all their options are supported at the top level of the options object [${S}]`)}}}const k=S.reduce(((e,t)=>{e[t.toLowerCase()]=t;return e}),{});function addListeners(e,t){t.on("authenticated",createListener(e,"authenticated"));t.on("error",createListener(e,"error"));t.on("timeout",createListener(e,"timeout"));t.on("close",createListener(e,"close"));t.on("parseError",createListener(e,"parseError"));t.once("open",createListener(e,"open"));t.once("fullsetup",createListener(e,"fullsetup"));t.once("all",createListener(e,"all"));t.on("reconnect",createListener(e,"reconnect"))}function assignTopology(e,t){e.topology=t;if(!(t instanceof A)){t.s.sessionPool=new g(t.s.coreTopology)}}function clearAllEvents(e){b.forEach((t=>e.removeAllListeners(t)))}function collectEvents(e,t){let r=loadClient();const n=[];if(e instanceof r){b.forEach((r=>{t.on(r,((t,o)=>{if(r==="open"){n.push({event:r,object1:e})}else{n.push({event:r,object1:t,object2:o})}}))}))}return n}function resolveTLSOptions(e){if(e.tls==null){return}["sslCA","sslKey","sslCert"].forEach((t=>{if(e[t]){e[t]=m.readFileSync(e[t])}}))}function connect(e,t,r,n){r=Object.assign({},r);if(n==null){throw new Error("no callback function provided")}let s=false;const A=o("MongoClient",r);if(t instanceof d||t instanceof h||t instanceof a){return connectWithUrl(e,t,r,connectCallback)}const l=r.useNewUrlParser!==false;const g=l?c:B;const p=l?transformUrlOptions:legacyTransformUrlOptions;g(t,r,((t,o)=>{if(t)return n(t);const i=p(o);const a=createUnifiedOptions(i,r);if(a.socketTimeoutMS==null)a.socketTimeoutMS=0;if(a.connectTimeoutMS==null)a.connectTimeoutMS=1e4;if(a.retryWrites==null)a.retryWrites=true;if(a.useRecoveryToken==null)a.useRecoveryToken=true;if(a.readPreference==null)a.readPreference="primary";if(a.db_options&&a.db_options.auth){delete a.db_options.auth}resolveTLSOptions(a);e.s.options=a;e.s.readPreference=u.fromOptions(a);e.s.writeConcern=C.fromOptions(a);if(i.servers.length===0){return n(new Error("connection string must contain at least one seed host"))}if(a.auth&&!a.credentials){try{s=true;a.credentials=generateCredentials(e,a.auth.user,a.auth.password,a)}catch(t){return n(t)}}if(a.useUnifiedTopology){return createTopology(e,"unified",a,connectCallback)}E("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.");if(a.replicaSet||a.rs_name){return createTopology(e,"replicaset",a,connectCallback)}else if(i.servers.length>1){return createTopology(e,"mongos",a,connectCallback)}else{return createServer(e,a,connectCallback)}}));function connectCallback(t,r){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&&t.message==="no mongos proxies found in seed list"){if(A.isWarn()){A.warn(o)}return n(new i(o))}if(s){e.emit("authenticated",null,true)}n(t,r)}}function connectWithUrl(e,t,r,n){assignTopology(e,t);addListeners(e,t);relayEvents(e,t);let o=Object.assign({},r);if(typeof r.readPreference==="string"||typeof r.read_preference==="string"){o.readPreference=new u(r.readPreference||r.read_preference)}const s=o.user||o.password||o.authMechanism;if(s&&!o.credentials){try{o.credentials=generateCredentials(e,o.user,o.password,o)}catch(e){return n(e,t)}}return t.connect(o,n)}function createListener(e,t){const r=new Set(["all","fullsetup","open","reconnect"]);return(n,o)=>{if(r.has(t)){return e.emit(t,e)}e.emit(t,n,o)}}function createServer(e,t,r){t.promiseLibrary=e.s.promiseLibrary;const n=translateOptions(t);const o=n[0];const s=collectEvents(e,o);o.connect(t,((n,i)=>{if(n){o.close(true);return r(n)}clearAllEvents(o);relayEvents(e,o);addListeners(e,o);const a=i.lastIsMaster();assignTopology(e,i);if(a&&a.msg==="isdbgrid"){i.close();return createTopology(e,"mongos",t,r)}replayEvents(e,s);r(n,i)}))}const D=new Set(["reconnect","reconnectFailed","attemptReconnect","joined","left","ping","ha","all","fullsetup","open"]);function registerDeprecatedEventNotifiers(e){e.on("newListener",(e=>{if(D.has(e)){p(`The \`${e}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,"DeprecationWarning")}}))}function createTopology(e,t,n,o){n.promiseLibrary=e.s.promiseLibrary;const s={};if(t==="unified")s.createServers=false;const i=translateOptions(n,s);if(n.autoEncryption!=null){const t=r(3012).Encrypter;n.encrypter=new t(e,n);n.autoEncrypter=n.encrypter.autoEncrypter}let c;if(t==="mongos"){c=new a(i,n)}else if(t==="replicaset"){c=new h(i,n)}else if(t==="unified"){c=new A(n.servers,n);registerDeprecatedEventNotifiers(e)}addListeners(e,c);relayEvents(e,c);assignTopology(e,c);if(n.autoEncrypter){n.autoEncrypter.init((e=>{if(e){o(e);return}c.connect(n,(e=>{if(e){c.close(true);o(e);return}n.encrypter.connectInternalClient((e=>{if(e)return o(e);o(undefined,c)}))}))}));return}c.connect(n,(e=>{if(e){c.close(true);return o(e)}o(undefined,c);return}))}function createUnifiedOptions(e,t){const r=["mongos","server","db","replset","db_options","server_options","rs_options","mongos_options"];const n=["readconcern","compression","autoencryption"];const o=["w","wtimeout","j","journal","fsync","writeconcern"];for(const s in t){if(o.indexOf(s.toLowerCase())!==-1){continue}else if(n.indexOf(s.toLowerCase())!==-1){e[s]=t[s]}else if(r.indexOf(s.toLowerCase())!==-1){e=mergeOptions(e,t[s],false)}else{if(t[s]&&typeof t[s]==="object"&&!Buffer.isBuffer(t[s])&&!Array.isArray(t[s])){e=mergeOptions(e,t[s],true)}else{e[s]=t[s]}}}const s=C.fromOptions(t);if(s){e.writeConcern=Object.assign({},e.writeConcern,s)}return e}function generateCredentials(e,t,r,n){n=Object.assign({},n);const o=n.authSource||n.authdb||n.dbName;const a=n.authMechanism||"DEFAULT";const A=a.toUpperCase();const c=n.authMechanismProperties;if(!w.has(A)){throw i.create({message:`authentication mechanism ${a} not supported', options.authMechanism`,driver:true})}return new s({mechanism:Q[A],mechanismProperties:c,source:o,username:t,password:r})}function legacyTransformUrlOptions(e){return mergeOptions(createUnifiedOptions({},e),e,false)}function mergeOptions(e,t,r){for(const n in t){if(t[n]&&typeof t[n]==="object"&&r){e=mergeOptions(e,t[n],r)}else{e[n]=t[n]}}return e}function relayEvents(e,t){const r=["commandStarted","commandSucceeded","commandFailed","serverOpening","serverClosed","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","topologyOpening","topologyClosed","topologyDescriptionChanged","joined","left","ping","ha"].concat(I);r.forEach((r=>{t.on(r,((t,n)=>{e.emit(r,t,n)}))}))}function replayEvents(e,t){for(let r=0;rt.domain_socket?new d(t.domain_socket,27017,e):new d(t.host,t.port,e)))}e.exports={validOptions:validOptions,connect:connect}},7885:(e,t,r)=>{"use strict";const n=r(2296).buildCountCommand;const o=r(1018).OperationBase;class CountOperation extends o{constructor(e,t,r){super(r);this.cursor=e;this.applySkipLimit=t}execute(e){const t=this.cursor;const r=this.applySkipLimit;const o=this.options;if(r){if(typeof t.cursorSkip()==="number")o.skip=t.cursorSkip();if(typeof t.cursorLimit()==="number")o.limit=t.cursorLimit()}if(o.readPreference){t.setReadPreference(o.readPreference)}if(typeof o.maxTimeMS!=="number"&&t.cmd&&typeof t.cmd.maxTimeMS==="number"){o.maxTimeMS=t.cmd.maxTimeMS}let s={};s.skip=o.skip;s.limit=o.limit;s.hint=o.hint;s.maxTimeMS=o.maxTimeMS;s.collectionName=t.namespace.collection;let i;try{i=n(t,t.cmd.query,s)}catch(t){return e(t)}t.server=t.topology.s.coreTopology;t.topology.command(t.namespace.withCollection("$cmd"),i,t.options,((t,r)=>{e(t,r?r.result.n:null)}))}}e.exports=CountOperation},5131:(e,t,r)=>{"use strict";const n=r(1554);class CountDocumentsOperation extends n{constructor(e,t,r){const n=[{$match:t}];if(typeof r.skip==="number"){n.push({$skip:r.skip})}if(typeof r.limit==="number"){n.push({$limit:r.limit})}n.push({$group:{_id:1,n:{$sum:1}}});super(e,n,r)}execute(e,t){super.execute(e,((e,r)=>{if(e){t(e,null);return}const n=r.result;if(n.cursor==null||n.cursor.firstBatch==null){t(null,0);return}const o=n.cursor.firstBatch;t(null,o.length?o[0].n:0)}))}}e.exports=CountDocumentsOperation},5561:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(8275).loadCollection;const A=r(3994).MongoError;const c=r(3994).ReadPreference;const l=new Set(["w","wtimeout","j","fsync","autoIndexId","strict","serializeFunctions","pkFactory","raw","readPreference","session","readConcern","writeConcern"]);class CreateCollectionOperation extends s{constructor(e,t,r){super(e,r);this.name=t}_buildCommand(){const e=this.name;const t=this.options;const r={create:e};for(let e in t){if(t[e]!=null&&typeof t[e]!=="function"&&!l.has(e)){r[e]=t[e]}}return r}execute(e){const t=this.db;const r=this.name;const n=this.options;const o=a();let s=Object.assign({nameOnly:true,strict:false},n);s=i(s,{db:t},s);function done(s){if(s){return e(s)}try{e(null,new o(t,t.s.topology,t.databaseName,r,t.s.pkFactory,n))}catch(s){e(s)}}const l=s.strict;if(l){t.listCollections({name:r},s).setReadPreference(c.PRIMARY).toArray(((t,n)=>{if(t){return e(t)}if(n.length>0){return e(new A(`Collection ${r} already exists. Currently in strict mode.`))}super.execute(done)}));return}super.execute(done)}}o(CreateCollectionOperation,n.WRITE_OPERATION);e.exports=CreateCollectionOperation},6394:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(3994).MongoError;const a=r(1371).parseIndexOptions;const A=r(1178).maxWireVersion;const c=new Set(["background","unique","name","partialFilterExpression","sparse","expireAfterSeconds","storageEngine","collation","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class CreateIndexesOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=t;if(!Array.isArray(r)||Array.isArray(r[0])){this.onlyReturnNameOfCreatedIndex=true;const e=a(r);const t=typeof n.name==="string"?n.name:e.name;const o={name:t,key:e.fieldHash};for(let e in n){if(c.has(e)){o[e]=n[e]}}this.indexes=[o];return}this.indexes=r}execute(e,t){const r=this.options;const n=this.indexes;const o=A(e);for(let r=0;r{if(e){t(e);return}t(null,this.onlyReturnNameOfCreatedIndex?n[0].name:r)}))}}o(CreateIndexesOperation,[n.WRITE_OPERATION,n.EXECUTE_WITH_SELECTION]);e.exports=CreateIndexesOperation},3554:(e,t,r)=>{"use strict";const n=r(6716).buildCountCommand;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=Array.prototype.push;const a=r(4847).CursorState;function count(e,t,r,o){if(t){if(typeof e.cursorSkip()==="number")r.skip=e.cursorSkip();if(typeof e.cursorLimit()==="number")r.limit=e.cursorLimit()}if(r.readPreference){e.setReadPreference(r.readPreference)}if(typeof r.maxTimeMS!=="number"&&e.cmd&&typeof e.cmd.maxTimeMS==="number"){r.maxTimeMS=e.cmd.maxTimeMS}let s={};s.skip=r.skip;s.limit=r.limit;s.hint=r.hint;s.maxTimeMS=r.maxTimeMS;s.collectionName=e.namespace.collection;let i;try{i=n(e,e.cmd.query,s)}catch(e){return o(e)}e.server=e.topology.s.coreTopology;e.topology.command(e.namespace.withCollection("$cmd"),i,e.options,((e,t)=>{o(e,t?t.result.n:null)}))}function each(e,t){if(!t)throw s.create({message:"callback is mandatory",driver:true});if(e.isNotified())return;if(e.s.state===a.CLOSED||e.isDead()){return o(t,s.create({message:"Cursor is closed",driver:true}))}if(e.s.state===a.INIT){e.s.state=a.OPEN}let r=null;if(e.bufferedCount()>0){while(r=loop(e,t))r(e,t);each(e,t)}else{e.next(((r,n)=>{if(r)return o(t,r);if(n==null){return e.close({skipKillCursors:true},(()=>o(t,null,null)))}if(o(t,null,n)===false)return;each(e,t)}))}}function loop(e,t){if(e.bufferedCount()===0)return;e._next(t);return loop}function toArray(e,t){const r=[];e.rewind();e.s.state=a.INIT;const fetchDocs=()=>{e._next(((n,s)=>{if(n){return o(t,n)}if(s==null){return e.close({skipKillCursors:true},(()=>o(t,null,r)))}r.push(s);if(e.bufferedCount()>0){let t=e.readBufferedDocuments(e.bufferedCount());if(e.s.transforms&&typeof e.s.transforms.doc==="function"){t=t.map(e.s.transforms.doc)}i.apply(r,t)}fetchDocs()}))};fetchDocs()}e.exports={count:count,each:each,toArray:toArray}},2226:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1371).applyWriteConcern;const s=r(3994).BSON.Code;const i=r(1371).debugOptions;const a=r(1371).handleCallback;const A=r(3994).MongoError;const c=r(1371).parseIndexOptions;const l=r(3994).ReadPreference;const u=r(1371).toError;const h=r(7703).extractCommand;const d=r(147);const g=r(1371).MongoDBNamespace;const p=["authSource","w","wtimeout","j","native_parser","forceServerObjectId","serializeFunctions","raw","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","bufferMaxEntries","numberOfRetries","retryMiliSeconds","readPreference","pkFactory","parentDb","promiseLibrary","noListener"];function createIndex(e,t,r,s,i){let c=Object.assign({},{readPreference:l.PRIMARY},s);c=o(c,{db:e},s);if(c.writeConcern&&typeof i!=="function"){throw A.create({message:"Cannot use a writeConcern without a provided callback",driver:true})}if(e.serverConfig&&e.serverConfig.isDestroyed())return i(new A("topology was destroyed"));createIndexUsingCreateIndexes(e,t,r,c,((o,l)=>{if(o==null)return a(i,o,l);if(o.code===n.CannotCreateIndex||o.code===n.DuplicateKey||o.code===n.IndexOptionsConflict||o.code===n.IndexKeySpecsConflict||o.code===n.InterruptedAtShutdown||o.code===n.InvalidIndexSpecificationOption){return a(i,o,l)}const u=createCreateIndexCommand(e,t,r,s);c.checkKeys=false;e.s.topology.insert(e.s.namespace.withCollection(d.SYSTEM_INDEX_COLLECTION),u,c,((e,t)=>{if(i==null)return;if(e)return a(i,e);if(t==null)return a(i,null,null);if(t.result.writeErrors)return a(i,A.create(t.result.writeErrors[0]),null);a(i,null,u.name)}))}))}function createListener(e,t,r){function listener(n){if(r.listeners(t).length>0){r.emit(t,n,e);for(let r=0;r{if(o!=null&&o.code!==n.NamespaceNotFound){return a(i,o,null)}if(A==null||!A[h]){createIndex(e,t,r,s,i)}else{if(typeof i==="function")return a(i,null,h)}}))}function evaluate(e,t,r,n,o){let i=t;let c=[];if(e.serverConfig&&e.serverConfig.isDestroyed())return o(new A("topology was destroyed"));if(!(i&&i._bsontype==="Code"))i=new s(i);if(r!=null&&!Array.isArray(r)&&typeof r!=="function"){c=[r]}else if(r!=null&&Array.isArray(r)&&typeof r!=="function"){c=r}let u={$eval:i,args:c};if(n["nolock"]){u["nolock"]=n["nolock"]}n.readPreference=new l(l.PRIMARY);executeCommand(e,u,n,((e,t)=>{if(e)return a(o,e,null);if(t&&t.ok===1)return a(o,null,t.retval);if(t)return a(o,A.create({message:`eval failed: ${t.errmsg}`,driver:true}),null);a(o,e,t)}))}function executeCommand(e,t,r,n){if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));const o=r.dbName||r.authdb||e.databaseName;r.readPreference=l.resolve(e,r);if(e.s.logger.isDebug()){const n=h(t);e.s.logger.debug(`executing command ${JSON.stringify(n.shouldRedact?`${n.name} details REDACTED`:t)} against ${o}.$cmd with options [${JSON.stringify(i(p,r))}]`)}e.s.topology.command(e.s.namespace.withCollection("$cmd"),t,r,((e,t)=>{if(e)return a(n,e);if(r.full)return a(n,null,t);a(n,null,t.result)}))}function executeDbAdminCommand(e,t,r,n){const o=new g("admin","$cmd");e.s.topology.command(o,t,r,((t,r)=>{if(e.serverConfig&&e.serverConfig.isDestroyed()){return n(new A("topology was destroyed"))}if(t)return a(n,t);a(n,null,r.result)}))}function indexInformation(e,t,r,n){const o=r["full"]==null?false:r["full"];if(e.serverConfig&&e.serverConfig.isDestroyed())return n(new A("topology was destroyed"));function processResults(e){let t={};for(let r=0;r{if(e)return n(u(e));if(!Array.isArray(t))return a(n,null,[]);if(o)return a(n,null,t);a(n,null,processResults(t))}))}function profilingInfo(e,t,r){try{e.collection("system.profile").find({},t).toArray(r)}catch(e){return r(e,null)}}function validateDatabaseName(e){if(typeof e!=="string")throw A.create({message:"database name must be a string",driver:true});if(e.length===0)throw A.create({message:"database name cannot be the empty string",driver:true});if(e==="$external")return;const t=[" ",".","$","/","\\"];for(let r=0;r{if(e)return a(s,e,null);if(t.ok===0)return a(s,u(t),null);a(s,null,h)}))}e.exports={createListener:createListener,createIndex:createIndex,ensureIndex:ensureIndex,evaluate:evaluate,executeCommand:executeCommand,executeDbAdminCommand:executeDbAdminCommand,indexInformation:indexInformation,profilingInfo:profilingInfo,validateDatabaseName:validateDatabaseName}},323:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=false;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteManyOperation,[s.EXPLAINABLE]);e.exports=DeleteManyOperation},6352:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).removeDocuments;const s=r(1018).Aspect;const i=r(1018).defineAspects;class DeleteOneOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.filter=t}execute(e){const t=this.collection;const r=this.filter;const n=this.options;n.single=true;o(t,r,n,((t,r)=>{if(e==null)return;if(t&&e)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.deletedCount=r.result.n;e(null,r)}))}}i(DeleteOneOperation,[s.EXPLAINABLE]);e.exports=DeleteOneOperation},6469:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(1371).decorateWithCollation;const a=r(1371).decorateWithReadConcern;const A=r(1178).maxWireVersion;const c=r(9386).MongoError;class DistinctOperation extends s{constructor(e,t,r,n){super(e,n);this.collection=e;this.key=t;this.query=r}execute(e,t){const r=this.collection;const n=this.key;const o=this.query;const s=this.options;const l={distinct:r.collectionName,key:n,query:o};if(typeof s.maxTimeMS==="number"){l.maxTimeMS=s.maxTimeMS}a(l,r,s);try{i(l,r,s)}catch(e){return t(e,null)}if(this.explain&&A(e)<4){t(new c(`server does not support explain on distinct`));return}super.executeCommand(e,l,((e,r)=>{if(e){t(e);return}t(null,this.options.full||this.explain?r:r.values)}))}}o(DistinctOperation,[n.READ_OPERATION,n.RETRYABLE,n.EXECUTE_WITH_SELECTION,n.EXPLAINABLE]);e.exports=DistinctOperation},2360:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;class DropOperation extends o{constructor(e,t){const r=Object.assign({},t,e.s.options);if(t.session){r.session=t.session}super(e,r)}execute(e){super.execute(((t,r)=>{if(t)return i(e,t);if(r.ok)return i(e,null,true);i(e,null,false)}))}}s(DropOperation,n.WRITE_OPERATION);class DropCollectionOperation extends DropOperation{constructor(e,t,r){super(e,r);this.name=t;this.namespace=`${e.namespace}.${t}`}_buildCommand(){return{drop:this.name}}}class DropDatabaseOperation extends DropOperation{_buildCommand(){return{dropDatabase:1}}}e.exports={DropOperation:DropOperation,DropCollectionOperation:DropCollectionOperation,DropDatabaseOperation:DropDatabaseOperation}},3560:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(499);const i=r(1371).applyWriteConcern;const a=r(1371).handleCallback;class DropIndexOperation extends s{constructor(e,t,r){super(e.s.db,r,e);this.collection=e;this.indexName=t}_buildCommand(){const e=this.collection;const t=this.indexName;const r=this.options;let n={dropIndexes:e.collectionName,index:t};n=i(n,{db:e.s.db,collection:e},r);return n}execute(e){super.execute(((t,r)=>{if(typeof e!=="function")return;if(t)return a(e,t,null);a(e,null,r)}))}}o(DropIndexOperation,n.WRITE_OPERATION);e.exports=DropIndexOperation},5328:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(3560);const i=r(1371).handleCallback;class DropIndexesOperation extends s{constructor(e,t){super(e,"*",t)}execute(e){super.execute((t=>{if(t)return i(e,t,false);i(e,null,true)}))}}o(DropIndexesOperation,n.WRITE_OPERATION);e.exports=DropIndexesOperation},4451:(e,t,r)=>{"use strict";const n=r(8072).MONGODB_ERROR_CODES;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1189);const a=r(1178).maxWireVersion;const A=r(5131);class EstimatedDocumentCountOperation extends i{constructor(e,t){super(e,t);this.collection=e;this.collectionName=e.s.namespace.collection}execute(e,t){if(a(e)<12){return this.executeLegacy(e,t)}if(this.options.query){const r=new A(this.collection,this.options.query,this.options);return r.execute(e,t)}const r=[{$collStats:{count:{}}},{$group:{_id:1,n:{$sum:"$count"}}}];const o={aggregate:this.collectionName,pipeline:r,cursor:{}};if(typeof this.options.maxTimeMS==="number"){o.maxTimeMS=this.options.maxTimeMS}super.executeCommand(e,o,((e,r)=>{if(e&&e.code!==n.NamespaceNotFound){t(e);return}t(undefined,r&&r.cursor&&r.cursor.firstBatch&&r.cursor.firstBatch[0].n||0)}))}executeLegacy(e,t){const r={count:this.collectionName};const n=this.options;if(n.query){r.query=n.query}if(n.hint){r.hint=n.hint}if(typeof n.maxTimeMS==="number"){r.maxTimeMS=n.maxTimeMS}if(typeof n.skip==="number"){r.skip=n.skip}if(typeof n.limit==="number"){r.limit=n.limit}super.executeCommand(e,r,((e,r)=>{if(e){t(e);return}t(null,r.n)}))}}s(EstimatedDocumentCountOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=EstimatedDocumentCountOperation},1681:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;const i=r(1371).MongoDBNamespace;class ExecuteDbAdminCommandOperation extends n{constructor(e,t,r){super(r);this.db=e;this.selector=t}execute(e){const t=this.db;const r=this.selector;const n=this.options;const a=new i("admin","$cmd");t.s.topology.command(a,r,n,((r,n)=>{if(t.serverConfig&&t.serverConfig.isDestroyed()){return e(new s("topology was destroyed"))}if(r)return o(e,r);o(e,null,n.result)}))}}e.exports=ExecuteDbAdminCommandOperation},2548:(e,t,r)=>{"use strict";const n=r(1371).maybePromise;const o=r(3111).MongoError;const s=r(1018).Aspect;const i=r(1018).OperationBase;const a=r(4485);const A=r(3111).isRetryableError;const c=r(1178).maxWireVersion;const l=r(1178).isUnifiedTopology;function executeOperation(e,t,r){if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!(t instanceof i)){throw new TypeError("This method requires a valid operation instance")}return n(e,r,(r=>{if(l(e)&&e.shouldCheckForSessionSupport()){return selectServerForSessionSupport(e,t,r)}let n,i;if(e.hasSessionSupport()){if(t.session==null){i=Symbol();n=e.startSession({owner:i});t.session=n}else if(t.session.hasEnded){return r(new o("Use of expired sessions is not permitted"))}}else if(t.session){return r(new o("Current topology does not support sessions"))}function executeCallback(e,o){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e,o)}try{if(t.hasAspect(s.EXECUTE_WITH_SELECTION)){executeWithServerSelection(e,t,executeCallback)}else{t.execute(executeCallback)}}catch(e){if(n&&n.owner===i){n.endSession();if(t.session===n){t.clearSession()}}r(e)}}))}function supportsRetryableReads(e){return c(e)>=6}function executeWithServerSelection(e,t,r){const n=t.readPreference||a.primary;const i=t.session&&t.session.inTransaction();if(i&&!n.equals(a.primary)){r(new o(`Read preference in a transaction must be primary, not: ${n.mode}`));return}const c={readPreference:n,session:t.session};function callbackWithRetry(n,o){if(n==null){return r(null,o)}if(!A(n)){return r(n)}e.selectServer(c,((e,n)=>{if(e||!supportsRetryableReads(n)){r(e,null);return}t.execute(n,r)}))}e.selectServer(c,((n,o)=>{if(n){r(n,null);return}const a=e.s.options.retryReads!==false&&t.session&&!i&&supportsRetryableReads(o)&&t.canRetryRead;if(t.hasAspect(s.RETRYABLE)&&a){t.execute(o,callbackWithRetry);return}t.execute(o,r)}))}function selectServerForSessionSupport(e,t,r){e.selectServer(a.primaryPreferred,(n=>{if(n){return r(n)}executeOperation(e,t,r)}))}e.exports=executeOperation},9961:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(3994).ReadPreference;const a=r(1178).maxWireVersion;const A=r(3111).MongoError;class FindOperation extends n{constructor(e,t,r,n){super(n);this.ns=t;this.cmd=r;this.readPreference=i.resolve(e,this.options)}execute(e,t){this.server=e;this.readPreference=i.resolve(this,this.options);if(typeof this.cmd.allowDiskUse!=="undefined"&&a(e)<4){t(new A("The `allowDiskUse` option is not supported on MongoDB < 3.2"));return}if(this.explain){this.options.explain=this.explain.verbosity}const r=this.cursorState||{};e.query(this.ns.toString(),this.cmd,r,this.options,t)}}s(FindOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION,o.EXPLAINABLE]);e.exports=FindOperation},711:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyRetryableWrites;const s=r(1371).applyWriteConcern;const i=r(1371).decorateWithCollation;const a=r(2226).executeCommand;const A=r(1371).formattedOrderClause;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1178).maxWireVersion;const h=r(9386).MongoError;const d=r(1018).Aspect;const g=r(1018).defineAspects;const p=r(1371).decorateWithExplain;class FindAndModifyOperation extends n{constructor(e,t,r,n,o){super(o);this.collection=e;this.query=t;this.sort=r;this.doc=n}execute(e){const t=this.collection;const r=this.query;const n=A(this.sort);const d=this.doc;let g=this.options;let E={findAndModify:t.collectionName,query:r};if(n){E.sort=n}E.new=g.new?true:false;E.remove=g.remove?true:false;E.upsert=g.upsert?true:false;const m=g.projection||g.fields;if(m){E.fields=m}if(g.arrayFilters){E.arrayFilters=g.arrayFilters}if(d&&!g.remove){E.update=d}if(g.maxTimeMS)E.maxTimeMS=g.maxTimeMS;g.serializeFunctions=g.serializeFunctions||t.s.serializeFunctions;g.checkKeys=false;g=o(g,t.s.db);g=s(g,{db:t.s.db,collection:t},g);if(g.writeConcern){E.writeConcern=g.writeConcern}if(g.bypassDocumentValidation===true){E.bypassDocumentValidation=g.bypassDocumentValidation}g.readPreference=l.primary;try{i(E,t,g)}catch(t){return e(t,null)}if(g.hint){const r=g.writeConcern&&g.writeConcern.w===0;if(r||u(t.s.topology)<8){e(new h("The current topology does not support a hint on findAndModify commands"));return}E.hint=g.hint}if(this.explain){if(u(t.s.topology)<4){e(new h(`server does not support explain on findAndModify`));return}E=p(E,this.explain)}a(t.s.db,E,g,((t,r)=>{if(t)return c(e,t,null);return c(e,null,r)}))}}g(FindAndModifyOperation,[d.EXPLAINABLE]);e.exports=FindAndModifyOperation},4497:(e,t,r)=>{"use strict";const n=r(1371).handleCallback;const o=r(1018).OperationBase;const s=r(1371).toError;const i=r(1018).Aspect;const a=r(1018).defineAspects;class FindOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.query=t}execute(e){const t=this.collection;const r=this.query;const o=this.options;try{const i=t.find(r,o).limit(-1).batchSize(1);i.next(((t,r)=>{if(t!=null)return n(e,s(t),null);n(e,null,r)}))}catch(t){e(t)}}}a(FindOneOperation,[i.EXPLAINABLE]);e.exports=FindOneOperation},5841:(e,t,r)=>{"use strict";const n=r(711);class FindOneAndDeleteOperation extends n{constructor(e,t,r){const n=Object.assign({},r);n.fields=r.projection;n.remove=true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}super(e,t,n.sort,null,n)}}e.exports=FindOneAndDeleteOperation},4316:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndReplaceOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndReplace option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Replacement parameter must be an object")}if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndReplaceOperation},1925:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(711);const s=r(1371).hasAtomicOperators;class FindOneAndUpdateOperation extends o{constructor(e,t,r,o){if("returnDocument"in o&&"returnOriginal"in o){throw new n("findOneAndUpdate option returnOriginal is deprecated in favor of returnDocument and cannot be combined")}const i=Object.assign({},o);i.fields=o.projection;i.update=true;i.new=o.returnDocument==="after"||o.returnOriginal===false;i.upsert=o.upsert===true;if(t==null||typeof t!=="object"){throw new TypeError("Filter parameter must be an object")}if(r==null||typeof r!=="object"){throw new TypeError("Update parameter must be an object")}if(!s(r)){throw new TypeError("Update document requires atomic operators")}super(e,t,i.sort,r,i)}}e.exports=FindOneAndUpdateOperation},8169:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1018).OperationBase;const i=r(1371).decorateCommand;const a=r(1371).decorateWithReadConcern;const A=r(2226).executeCommand;const c=r(1371).handleCallback;const l=r(3994).ReadPreference;const u=r(1371).toError;class GeoHaystackSearchOperation extends s{constructor(e,t,r,n){super(n);this.collection=e;this.x=t;this.y=r}execute(e){const t=this.collection;const r=this.x;const n=this.y;let o=this.options;let s={geoSearch:t.collectionName,near:[r,n]};s=i(s,o,["readPreference","session"]);o=Object.assign({},o);o.readPreference=l.resolve(t,o);a(s,t,o);A(t.s.db,s,o,((t,r)=>{if(t)return c(e,t);if(r.err||r.errmsg)c(e,u(r));c(e,null,r)}))}}o(GeoHaystackSearchOperation,n.READ_OPERATION);e.exports=GeoHaystackSearchOperation},7809:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(2226).indexInformation;class IndexExistsOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.indexes=t}execute(e){const t=this.collection;const r=this.indexes;const n=this.options;s(t.s.db,t.collectionName,n,((t,n)=>{if(t!=null)return o(e,t,null);if(!Array.isArray(r))return o(e,null,n[r]!=null);for(let t=0;t{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexInformationOperation extends n{constructor(e,t,r){super(r);this.db=e;this.name=t}execute(e){const t=this.db;const r=this.name;const n=this.options;o(t,r,n,e)}}e.exports=IndexInformationOperation},4218:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).indexInformation;class IndexesOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;let r=this.options;r=Object.assign({},{full:true},r);o(t.s.db,t.collectionName,r,e)}}e.exports=IndexesOperation},3592:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(6976);const s=r(3994).MongoError;const i=r(2296).prepareDocs;class InsertManyOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.docs=t}execute(e){const t=this.collection;let r=this.docs;const n=this.options;if(!Array.isArray(r)){return e(s.create({message:"docs parameter must be an array of documents",driver:true}))}n["serializeFunctions"]=n["serializeFunctions"]||t.s.serializeFunctions;r=i(t,r,n);const a=r.map((e=>({insertOne:{document:e}})));const A=new o(t,a,n);A.execute(((t,n)=>{if(t)return e(t,null);e(null,mapInsertManyResults(r,n))}))}}function mapInsertManyResults(e,t){const r={result:{ok:1,n:t.insertedCount},ops:e,insertedCount:t.insertedCount,insertedIds:t.insertedIds};if(t.getLastOp()){r.result.opTime=t.getLastOp()}return r}e.exports=InsertManyOperation},9915:(e,t,r)=>{"use strict";const n=r(3994).MongoError;const o=r(1018).OperationBase;const s=r(2296).insertDocuments;class InsertOneOperation extends o{constructor(e,t,r){super(r);this.collection=e;this.doc=t}execute(e){const t=this.collection;const r=this.doc;const o=this.options;if(Array.isArray(r)){return e(n.create({message:"doc parameter must be an object",driver:true}))}s(t,[r],o,((t,n)=>{if(e==null)return;if(t&&e)return e(t);if(n==null)return e(null,{result:{ok:1}});n.insertedCount=n.result.n;n.insertedId=r._id;if(e)e(null,n)}))}}e.exports=InsertOneOperation},4956:(e,t,r)=>{"use strict";const n=r(43);const o=r(1371).handleCallback;class IsCappedOperation extends n{constructor(e,t){super(e,t)}execute(e){super.execute(((t,r)=>{if(t)return o(e,t);o(e,null,!!(r&&r.capped))}))}}e.exports=IsCappedOperation},840:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=r(147);const A=3;function listCollectionsTransforms(e){const t=`${e}.`;return{doc:e=>{const r=e.name.indexOf(t);if(e.name&&r===0){e.name=e.name.substr(r+t.length)}return e}}}class ListCollectionsOperation extends n{constructor(e,t,r){super(e,r,{fullResponse:true});this.db=e;this.filter=t;this.nameOnly=!!this.options.nameOnly;if(typeof this.options.batchSize==="number"){this.batchSize=this.options.batchSize}}execute(e,t){if(i(e){if(r&&r.message&&r.message.documents&&Array.isArray(r.message.documents)){r.message.documents=r.message.documents.map(o.doc)}t(e,r)}));return}const r={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly};return super.executeCommand(e,r,t)}}s(ListCollectionsOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListCollectionsOperation},9929:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1371).MongoDBNamespace;class ListDatabasesOperation extends n{constructor(e,t){super(e,t);this.ns=new i("admin","$cmd")}execute(e,t){const r={listDatabases:1};if(this.options.nameOnly){r.nameOnly=Number(r.nameOnly)}if(this.options.filter){r.filter=this.options.filter}if(typeof this.options.authorizedDatabases==="boolean"){r.authorizedDatabases=this.options.authorizedDatabases}super.executeCommand(e,r,t)}}s(ListDatabasesOperation,[o.READ_OPERATION,o.RETRYABLE,o.EXECUTE_WITH_SELECTION]);e.exports=ListDatabasesOperation},28:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).Aspect;const s=r(1018).defineAspects;const i=r(1178).maxWireVersion;const a=3;class ListIndexesOperation extends n{constructor(e,t){super(e,t,{fullResponse:true});this.collectionNamespace=e.s.namespace}execute(e,t){const r=i(e);if(r{"use strict";const n=r(1371).applyWriteConcern;const o=r(3994).BSON.Code;const s=r(1371).decorateWithCollation;const i=r(1371).decorateWithReadConcern;const a=r(2226).executeCommand;const A=r(1371).handleCallback;const c=r(1371).isObject;const l=r(8275).loadDb;const u=r(1018).OperationBase;const h=r(3994).ReadPreference;const d=r(1371).toError;const g=r(1018).Aspect;const p=r(1018).defineAspects;const E=r(1371).decorateWithExplain;const m=r(1178).maxWireVersion;const C=r(9386).MongoError;const I=["explain","readPreference","session","bypassDocumentValidation","w","wtimeout","j","writeConcern"];class MapReduceOperation extends u{constructor(e,t,r,n){super(n);this.collection=e;this.map=t;this.reduce=r}execute(e){const t=this.collection;const r=this.map;const o=this.reduce;let c=this.options;let u={mapReduce:t.collectionName,map:r,reduce:o};for(let e in c){if("scope"===e){u[e]=processScope(c[e])}else{if(I.indexOf(e)===-1){u[e]=c[e]}}}c=Object.assign({},c);c.readPreference=h.resolve(t,c);if(c.readPreference!==false&&c.readPreference!=="primary"&&c["out"]&&c["out"].inline!==1&&c["out"]!=="inline"){c.readPreference="primary";n(u,{db:t.s.db,collection:t},c)}else{i(u,t,c)}if(c.bypassDocumentValidation===true){u.bypassDocumentValidation=c.bypassDocumentValidation}try{s(u,t,c)}catch(t){return e(t,null)}if(this.explain){if(m(t.s.topology)<9){e(new C(`server does not support explain on mapReduce`));return}u=E(u,this.explain)}a(t.s.db,u,c,((r,n)=>{if(r)return A(e,r);if(1!==n.ok||n.err||n.errmsg){return A(e,d(n))}if(this.explain)return e(undefined,n);const o={};if(n.timeMillis)o["processtime"]=n.timeMillis;if(n.counts)o["counts"]=n.counts;if(n.timing)o["timing"]=n.timing;if(n.results){if(c["verbose"]==null||!c["verbose"]){return A(e,null,n.results)}return A(e,null,{results:n.results,stats:o})}let s=null;if(n.result!=null&&typeof n.result==="object"){const e=n.result;let r=l();s=new r(e.db,t.s.db.s.topology,t.s.db.s.options).collection(e.collection)}else{s=t.s.db.collection(n.result)}if(c["verbose"]==null||!c["verbose"]){return A(e,r,s)}A(e,r,{collection:s,stats:o})}))}}function processScope(e){if(!c(e)||e._bsontype==="ObjectID"){return e}const t=Object.keys(e);let r;const n={};for(let s=t.length-1;s>=0;s--){r=t[s];if("function"===typeof e[r]){n[r]=new o(String(e[r]))}else{n[r]=processScope(e[r])}}return n}p(MapReduceOperation,[g.EXPLAINABLE]);e.exports=MapReduceOperation},1018:(e,t,r)=>{"use strict";const n=r(5293).Explain;const o=r(3111).MongoError;const s={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"),EXPLAINABLE:Symbol("EXPLAINABLE")};class OperationBase{constructor(e){this.options=Object.assign({},e);if(this.hasAspect(s.EXPLAINABLE)){this.explain=n.fromOptions(e)}else if(this.options.explain!==undefined){throw new o(`explain is not supported on this command`)}}hasAspect(e){if(this.constructor.aspects==null){return false}return 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 true}execute(){throw new TypeError("`execute` must be implemented for OperationBase subclasses")}}function defineAspects(e,t){if(!Array.isArray(t)&&!(t instanceof Set)){t=[t]}t=new Set(t);Object.defineProperty(e,"aspects",{value:t,writable:false});return t}e.exports={Aspect:s,defineAspects:defineAspects,OperationBase:OperationBase}},43:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).handleCallback;const s=r(3994).MongoError;class OptionsOperation extends n{constructor(e,t){super(t);this.collection=e}execute(e){const t=this.collection;const r=this.options;t.s.db.listCollections({name:t.collectionName},r).toArray(((r,n)=>{if(r)return o(e,r);if(n.length===0){return o(e,s.create({message:`collection ${t.namespace} not found`,driver:true}))}o(e,r,n[0].options||null)}))}}e.exports=OptionsOperation},3969:(e,t,r)=>{"use strict";const n=r(499);class ProfilingLevelOperation extends n{constructor(e,t,r){super(e,r)}_buildCommand(){const e={profile:-1};return e}execute(e){super.execute(((t,r)=>{if(t==null&&r.ok===1){const t=r.was;if(t===0)return e(null,"off");if(t===1)return e(null,"slow_only");if(t===2)return e(null,"all");return e(new Error("Error: illegal profiling level value "+t),null)}else{t!=null?e(t,null):e(new Error("Error with profile command"),null)}}))}}e.exports=ProfilingLevelOperation},6331:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(1018).defineAspects;const s=r(1189);const i=r(2291).serverType;const a=r(2291).ServerType;const A=r(3994).MongoError;class ReIndexOperation extends s{constructor(e,t){super(e,t);this.collectionName=e.collectionName}execute(e,t){if(i(e)!==a.Standalone){t(new A(`reIndex can only be executed on standalone servers.`));return}super.executeCommand(e,{reIndex:this.collectionName},((e,r)=>{if(e){t(e);return}t(null,!!r.ok)}))}}o(ReIndexOperation,[n.EXECUTE_WITH_SELECTION]);e.exports=ReIndexOperation},1969:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;const i=r(1371).handleCallback;const a=r(2481);class RemoveUserOperation extends o{constructor(e,t,r){const n={};const o=a.fromOptions(r);if(o!=null){n.writeConcern=o}if(r.dbName){n.dbName=r.dbName}if(typeof r.maxTimeMS==="number"){n.maxTimeMS=r.maxTimeMS}super(e,n);this.username=t}_buildCommand(){const e=this.username;const t={dropUser:e};return t}execute(e){super.execute(((t,r)=>{if(t)return i(e,t,null);i(e,t,r.ok?true:false)}))}}s(RemoveUserOperation,n.WRITE_OPERATION);e.exports=RemoveUserOperation},2808:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(1371).applyWriteConcern;const s=r(1371).checkCollectionName;const i=r(2226).executeDbAdminCommand;const a=r(1371).handleCallback;const A=r(8275).loadCollection;const c=r(1371).toError;class RenameOperation extends n{constructor(e,t,r){super(r);this.collection=e;this.newName=t}execute(e){const t=this.collection;const r=this.newName;const n=this.options;let l=A();s(r);const u=t.namespace;const h=t.s.namespace.withCollection(r).toString();const d=typeof n.dropTarget==="boolean"?n.dropTarget:false;const g={renameCollection:u,to:h,dropTarget:d};o(g,{db:t.s.db,collection:t},n);i(t.s.db.admin().s.db,g,n,((n,o)=>{if(n)return a(e,n,null);if(o.errmsg)return a(e,c(o),null);try{return a(e,null,new l(t.s.db,t.s.topology,t.s.namespace.db,r,t.s.pkFactory,t.s.options))}catch(n){return a(e,c(n),null)}}))}}e.exports=RenameOperation},2508:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;class ReplaceOneOperation extends n{constructor(e,t,r,n){super(n);if(s(r)){throw new TypeError("Replacement document must not contain atomic operators")}this.collection=e;this.filter=t;this.replacement=r}execute(e){const t=this.collection;const r=this.filter;const n=this.replacement;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>replaceCallback(t,r,n,e)))}}function replaceCallback(e,t,r,n){if(n==null)return;if(e&&n)return n(e);if(t==null)return n(null,{result:{ok:1}});t.modifiedCount=t.result.nModified!=null?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=[r];if(n)n(null,t)}e.exports=ReplaceOneOperation},1363:(e,t,r)=>{"use strict";const n=r(1189);const o=r(1018).defineAspects;const s=r(1018).Aspect;class RunCommandOperation extends n{constructor(e,t,r){super(e,r);this.command=t}execute(e,t){const r=this.command;this.executeCommand(e,r,t)}}o(RunCommandOperation,[s.EXECUTE_WITH_SELECTION,s.NO_INHERIT_OPTIONS]);e.exports=RunCommandOperation},6301:(e,t,r)=>{"use strict";const n=r(499);const o=new Set(["off","slow_only","all"]);class SetProfilingLevelOperation extends n{constructor(e,t,r){let n=0;if(t==="off"){n=0}else if(t==="slow_only"){n=1}else if(t==="all"){n=2}super(e,r);this.level=t;this.profile=n}_buildCommand(){const e=this.profile;const t={profile:e};return t}execute(e){const t=this.level;if(!o.has(t)){return e(new Error("Error: illegal profiling level value "+t))}super.execute(((r,n)=>{if(r==null&&n.ok===1)return e(null,t);return r!=null?e(r,null):e(new Error("Error with profile command"),null)}))}}e.exports=SetProfilingLevelOperation},968:(e,t,r)=>{"use strict";const n=r(1018).Aspect;const o=r(499);const s=r(1018).defineAspects;class StatsOperation extends o{constructor(e,t){super(e.s.db,t,e)}_buildCommand(){const e=this.collection;const t=this.options;const r={collStats:e.collectionName};if(t["scale"]!=null){r["scale"]=t["scale"]}return r}}s(StatsOperation,n.READ_OPERATION);e.exports=StatsOperation},9350:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateManyOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=true;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateManyOperation,[i.EXPLAINABLE]);e.exports=UpdateManyOperation},9068:(e,t,r)=>{"use strict";const n=r(1018).OperationBase;const o=r(2296).updateDocuments;const s=r(1371).hasAtomicOperators;const i=r(1018).Aspect;const a=r(1018).defineAspects;class UpdateOneOperation extends n{constructor(e,t,r,n){super(n);if(!s(r)){throw new TypeError("Update document requires atomic operators")}this.collection=e;this.filter=t;this.update=r}execute(e){const t=this.collection;const r=this.filter;const n=this.update;const s=this.options;s.multi=false;o(t,r,n,s,((t,r)=>{if(e==null)return;if(t)return e(t);if(r==null)return e(null,{result:{ok:1}});if(this.explain)return e(undefined,r.result);r.modifiedCount=r.result.nModified!=null?r.result.nModified:r.result.n;r.upsertedId=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?r.result.upserted[0]:null;r.upsertedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length?r.result.upserted.length:0;r.matchedCount=Array.isArray(r.result.upserted)&&r.result.upserted.length>0?0:r.result.n;e(null,r)}))}}a(UpdateOneOperation,[i.EXPLAINABLE]);e.exports=UpdateOneOperation},9263:(e,t,r)=>{"use strict";const n=r(499);class ValidateCollectionOperation extends n{constructor(e,t,r){let n={validate:t};const o=Object.keys(r);for(let e=0;e{if(r!=null)return e(r,null);if(n.ok===0)return e(new Error("Error with validate command"),null);if(n.result!=null&&n.result.constructor!==String)return e(new Error("Error with validation data"),null);if(n.result!=null&&n.result.match(/exception|corrupt/)!=null)return e(new Error("Error: invalid collection "+t),null);if(n.valid!=null&&!n.valid)return e(new Error("Error: invalid collection "+t),null);return e(null,n)}))}}e.exports=ValidateCollectionOperation},7289:e=>{"use strict";class ReadConcern{constructor(e){if(e!=null){this.level=e}}static fromOptions(e){if(e==null){return}if(e.readConcern){if(e.readConcern instanceof ReadConcern){return e.readConcern}return new ReadConcern(e.readConcern.level)}if(e.level){return new ReadConcern(e.level)}}static get MAJORITY(){return"majority"}static get AVAILABLE(){return"available"}static get LINEARIZABLE(){return"linearizable"}static get SNAPSHOT(){return"snapshot"}}e.exports=ReadConcern},2048:(e,t,r)=>{"use strict";const n=r(8589).oF;const o=r(3994).MongoError;const s=r(3994).Mongos;const i=r(7159);const a=r(8421);const A=r(8589).yh;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","loggerLevel","logger","reconnectTries","appname","domainsEnabled","servername","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","promiseLibrary","monitorCommands"];class Mongos extends n{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var n=0;n0?t.socketOptions:t;C=l(C,I);this.s={coreTopology:new s(E,C),sCapabilities:null,debug:C.debug,storeOptions:g,clonedOptions:C,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var n=["timeout","error","close"];n.forEach((function(e){r.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.close(true);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect");r.s.store.execute()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){var e=["timeout","error","close","fullsetup"];e.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.on("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r)}));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("joined",relay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.connect(e)}}Object.defineProperty(Mongos.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=Mongos},2632:(e,t,r)=>{"use strict";const n=r(3994).Topology;const o=r(8589).ug;const s=r(7159);const i=r(1371).translateOptions;class NativeTopology extends n{constructor(e,t){t=t||{};let r=Object.assign({},{cursorFactory:s,reconnect:false,emitError:typeof t.emitError==="boolean"?t.emitError:true,maxPoolSize:typeof t.maxPoolSize==="number"?t.maxPoolSize:typeof t.poolSize==="number"?t.poolSize:10,minPoolSize:typeof t.minPoolSize==="number"?t.minPoolSize:typeof t.minSize==="number"?t.minSize:0,monitorCommands:typeof t.monitorCommands==="boolean"?t.monitorCommands:false});r=i(r,t);var n=t.socketOptions&&Object.keys(t.socketOptions).length>0?t.socketOptions:t;r=i(r,n);r.serverApi=t.serverApi;r.useUnifiedTopology=t.useUnifiedTopology;super(e,r)}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.lastIsMaster()==null)return null;this.s.sCapabilities=new o(this.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){super.command(e.toString(),t,r,n)}insert(e,t,r,n){super.insert(e.toString(),t,r,n)}update(e,t,r,n){super.update(e.toString(),t,r,n)}remove(e,t,r,n){super.remove(e.toString(),t,r,n)}}e.exports=NativeTopology},382:(e,t,r)=>{"use strict";const n=r(8421);const o=r(7159);const s=r(3994).MongoError;const i=r(8589).oF;const a=r(8589).yh;const A=r(3994).ReplSet;const c=r(1371).MAX_JS_INT;const l=r(1371).translateOptions;const u=r(1371).filterOptions;const h=r(1371).mergeOptions;var d=["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","bsonRegExp","maxStalenessSeconds","promiseLibrary","minSize","monitorCommands"];class ReplSet extends i{constructor(e,t){super();t=t||{};var r=this;t=u(t,d);for(var i=0;i0?t.socketOptions:t;m=l(m,C);var I=new A(E,m);I.on("reconnect",(function(){r.emit("reconnect");p.execute()}));this.s={coreTopology:I,sCapabilities:null,tag:t.tag,storeOptions:g,clonedOptions:m,store:p,options:t,sessionPool:null,sessions:new Set,promiseLibrary:t.promiseLibrary||Promise};if(m.debug){Object.defineProperty(this,"replset",{enumerable:true,get:function(){return I}})}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e={};if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var n=["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed","joined","left","ping","ha"];n.forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));var relay=function(e){return function(t,n){r.emit(e,t,n)}};var replsetRelay=function(e){return function(t,n){r.emit(e,t,n.lastIsMaster(),n)}};var relayHa=function(e,t){r.emit("ha",e,t);if(e==="start"){r.emit("ha_connect",e,t)}else if(e==="end"){r.emit("ha_ismaster",e,t)}};r.s.coreTopology.on("joined",replsetRelay("joined"));r.s.coreTopology.on("left",relay("left"));r.s.coreTopology.on("ping",relay("ping"));r.s.coreTopology.on("ha",relayHa);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("fullsetup",(function(){r.emit("fullsetup",r,r)}));r.s.coreTopology.on("all",(function(){r.emit("all",null,r)}));var connectHandler=function(){r.s.coreTopology.once("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.once("close",errorHandler("close"));r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var connectErrorHandler=function(){return function(e){["timeout","error","close"].forEach((function(e){r.s.coreTopology.removeListener(e,connectErrorHandler)}));r.s.coreTopology.removeListener("connect",connectErrorHandler);r.s.coreTopology.destroy();try{t(e)}catch(e){if(!r.s.coreTopology.isConnected())process.nextTick((function(){throw e}))}}};r.s.coreTopology.once("timeout",connectErrorHandler("timeout"));r.s.coreTopology.once("error",connectErrorHandler("error"));r.s.coreTopology.once("close",connectErrorHandler("close"));r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.connect(e)}close(e,t){["timeout","error","close","joined","left"].forEach((e=>this.removeAllListeners(e)));super.close(e,t)}}Object.defineProperty(ReplSet.prototype,"haInterval",{enumerable:true,get:function(){return this.s.coreTopology.s.haInterval}});e.exports=ReplSet},8421:(e,t,r)=>{"use strict";const n=r(3994).Server;const o=r(7159);const s=r(8589).oF;const i=r(8589).yh;const a=r(3994).MongoError;const A=r(1371).MAX_JS_INT;const c=r(1371).translateOptions;const l=r(1371).filterOptions;const u=r(1371).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","bsonRegExp","compression","promiseLibrary","monitorCommands"];class Server extends s{constructor(e,t,r){super();var s=this;r=l(r,h);const d=r.promiseLibrary;var g={force:false,bufferMaxEntries:typeof r.bufferMaxEntries==="number"?r.bufferMaxEntries:A};var p=r.store||new i(s,g);if(e.indexOf("/")!==-1){if(t!=null&&typeof t==="object"){r=t;t=null}}else if(t==null){throw a.create({message:"port must be specified",driver:true})}var E=typeof r.auto_reconnect==="boolean"?r.auto_reconnect:true;E=typeof r.autoReconnect==="boolean"?r.autoReconnect:E;var m=u({},{host:e,port:t,disconnectHandler:p,cursorFactory:o,reconnect:E,emitError:typeof r.emitError==="boolean"?r.emitError:true,size:typeof r.poolSize==="number"?r.poolSize:5,monitorCommands:typeof r.monitorCommands==="boolean"?r.monitorCommands:false});m=c(m,r);var C=r.socketOptions&&Object.keys(r.socketOptions).length>0?r.socketOptions:r;m=c(m,C);this.s={coreTopology:new n(m),sCapabilities:null,clonedOptions:m,reconnect:m.reconnect,emitError:m.emitError,poolSize:m.size,storeOptions:g,store:p,host:e,port:t,options:r,sessionPool:null,sessions:new Set,promiseLibrary:d||Promise}}connect(e,t){var r=this;if("function"===typeof e)t=e,e={};if(e==null)e=this.s.clonedOptions;if(!("function"===typeof t))t=null;e=Object.assign({},this.s.clonedOptions,e);r.s.options=e;r.s.storeOptions.bufferMaxEntries=typeof e.bufferMaxEntries==="number"?e.bufferMaxEntries:-1;var connectErrorHandler=function(){return function(e){var o=["timeout","error","close"];o.forEach((function(e){r.s.coreTopology.removeListener(e,n[e])}));r.s.coreTopology.removeListener("connect",connectErrorHandler);try{t(e)}catch(e){process.nextTick((function(){throw e}))}}};var errorHandler=function(e){return function(t){if(e!=="error"){r.emit(e,t)}}};var reconnectHandler=function(){r.emit("reconnect",r);r.s.store.execute()};var reconnectFailedHandler=function(e){r.emit("reconnectFailed",e);r.s.store.flush(e)};var destroyHandler=function(){r.s.store.flush()};var relay=function(e){return function(t,n){r.emit(e,t,n)}};var connectHandler=function(){["timeout","error","close","destroy"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.on("timeout",errorHandler("timeout"));r.s.coreTopology.once("error",errorHandler("error"));r.s.coreTopology.on("close",errorHandler("close"));r.s.coreTopology.on("destroy",destroyHandler);r.emit("open",null,r);try{t(null,r)}catch(e){process.nextTick((function(){throw e}))}};var n={timeout:connectErrorHandler("timeout"),error:connectErrorHandler("error"),close:connectErrorHandler("close")};["timeout","error","close","serverOpening","serverDescriptionChanged","serverHeartbeatStarted","serverHeartbeatSucceeded","serverHeartbeatFailed","serverClosed","topologyOpening","topologyClosed","topologyDescriptionChanged","commandStarted","commandSucceeded","commandFailed"].forEach((function(e){r.s.coreTopology.removeAllListeners(e)}));r.s.coreTopology.once("timeout",n.timeout);r.s.coreTopology.once("error",n.error);r.s.coreTopology.once("close",n.close);r.s.coreTopology.once("connect",connectHandler);r.s.coreTopology.on("reconnect",reconnectHandler);r.s.coreTopology.on("reconnectFailed",reconnectFailedHandler);r.s.coreTopology.on("serverDescriptionChanged",relay("serverDescriptionChanged"));r.s.coreTopology.on("serverHeartbeatStarted",relay("serverHeartbeatStarted"));r.s.coreTopology.on("serverHeartbeatSucceeded",relay("serverHeartbeatSucceeded"));r.s.coreTopology.on("serverHeartbeatFailed",relay("serverHeartbeatFailed"));r.s.coreTopology.on("serverOpening",relay("serverOpening"));r.s.coreTopology.on("serverClosed",relay("serverClosed"));r.s.coreTopology.on("topologyOpening",relay("topologyOpening"));r.s.coreTopology.on("topologyClosed",relay("topologyClosed"));r.s.coreTopology.on("topologyDescriptionChanged",relay("topologyDescriptionChanged"));r.s.coreTopology.on("commandStarted",relay("commandStarted"));r.s.coreTopology.on("commandSucceeded",relay("commandSucceeded"));r.s.coreTopology.on("commandFailed",relay("commandFailed"));r.s.coreTopology.on("attemptReconnect",relay("attemptReconnect"));r.s.coreTopology.on("monitoring",relay("monitoring"));r.s.coreTopology.connect(e)}}Object.defineProperty(Server.prototype,"poolSize",{enumerable:true,get:function(){return this.s.coreTopology.connections().length}});Object.defineProperty(Server.prototype,"autoReconnect",{enumerable:true,get:function(){return this.s.reconnect}});Object.defineProperty(Server.prototype,"host",{enumerable:true,get:function(){return this.s.host}});Object.defineProperty(Server.prototype,"port",{enumerable:true,get:function(){return this.s.port}});e.exports=Server},8589:(e,t,r)=>{"use strict";const n=r(2361),o=r(3994).MongoError,s=r(3837).format,i=r(3994).ReadPreference,a=r(3994).Sessions.ClientSession;var Store=function(e,t){var r=this;var n=[];t=t||{force:false,bufferMaxEntries:-1};this.s={storedOps:n,storeOptions:t,topology:e};Object.defineProperty(this,"length",{enumerable:true,get:function(){return r.s.storedOps.length}})};Store.prototype.add=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,n:t,o:r,op:n,c:i})};Store.prototype.addObjectAndMethod=function(e,t,r,n,i){if(this.s.storeOptions.force){return i(o.create({message:"db closed by application",driver:true}))}if(this.s.storeOptions.bufferMaxEntries===0){return i(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}if(this.s.storeOptions.bufferMaxEntries>0&&this.s.storedOps.length>this.s.storeOptions.bufferMaxEntries){while(this.s.storedOps.length>0){var a=this.s.storedOps.shift();a.c(o.create({message:s("no connection available for operation and number of stored operation > %s",this.s.storeOptions.bufferMaxEntries),driver:true}))}return}this.s.storedOps.push({t:e,m:r,o:t,p:n,c:i})};Store.prototype.flush=function(e){while(this.s.storedOps.length>0){this.s.storedOps.shift().c(e||o.create({message:s("no connection available for operation"),driver:true}))}};var A=["primary","primaryPreferred","nearest","secondaryPreferred"];var c=["secondary","secondaryPreferred"];Store.prototype.execute=function(e){e=e||{};var t=this.s.storedOps;this.s.storedOps=[];var r=typeof e.executePrimary==="boolean"?e.executePrimary:true;var n=typeof e.executeSecondary==="boolean"?e.executeSecondary:true;while(t.length>0){var o=t.shift();if(o.t==="cursor"){if(r&&n){o.o[o.m].apply(o.o,o.p)}else if(r&&o.o.options&&o.o.options.readPreference&&A.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}else if(!r&&n&&o.o.options&&o.o.options.readPreference&&c.indexOf(o.o.options.readPreference.mode)!==-1){o.o[o.m].apply(o.o,o.p)}}else if(o.t==="auth"){this.s.topology[o.t].apply(this.s.topology,o.o)}else{if(r&&n){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(r&&o.op&&o.op.readPreference&&A.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}else if(!r&&n&&o.op&&o.op.readPreference&&c.indexOf(o.op.readPreference.mode)!==-1){this.s.topology[o.t](o.n,o.o,o.op,o.c)}}}};Store.prototype.all=function(){return this.s.storedOps};var ServerCapabilities=function(e){var setup_get_property=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var t=false;var r=false;var n=false;var o=false;var s=false;var i=false;var a=e.maxWriteBatchSize||1e3;var A=false;var c=false;if(e.minWireVersion>=0){n=true}if(e.maxWireVersion>=1){t=true;o=true}if(e.maxWireVersion>=2){r=true}if(e.maxWireVersion>=3){s=true;i=true}if(e.maxWireVersion>=5){A=true;c=true}if(e.minWireVersion==null){e.minWireVersion=0}if(e.maxWireVersion==null){e.maxWireVersion=0}setup_get_property(this,"hasAggregationCursor",t);setup_get_property(this,"hasWriteCommands",r);setup_get_property(this,"hasTextSearch",n);setup_get_property(this,"hasAuthCommands",o);setup_get_property(this,"hasListCollectionsCommand",s);setup_get_property(this,"hasListIndexesCommand",i);setup_get_property(this,"minWireVersion",e.minWireVersion);setup_get_property(this,"maxWireVersion",e.maxWireVersion);setup_get_property(this,"maxNumberOfDocsInBatch",a);setup_get_property(this,"commandsTakeWriteConcern",A);setup_get_property(this,"commandsTakeCollation",c)};class TopologyBase extends n{constructor(){super();this.setMaxListeners(Infinity)}hasSessionSupport(){return this.logicalSessionTimeoutMinutes!=null}startSession(e,t){const r=new a(this,this.s.sessionPool,e,t);r.once("ended",(()=>{this.s.sessions.delete(r)}));this.s.sessions.add(r);return r}endSessions(e,t){return this.s.coreTopology.endSessions(e,t)}get clientMetadata(){return this.s.coreTopology.s.options.metadata}capabilities(){if(this.s.sCapabilities)return this.s.sCapabilities;if(this.s.coreTopology.lastIsMaster()==null)return null;this.s.sCapabilities=new ServerCapabilities(this.s.coreTopology.lastIsMaster());return this.s.sCapabilities}command(e,t,r,n){this.s.coreTopology.command(e.toString(),t,i.translate(r),n)}insert(e,t,r,n){this.s.coreTopology.insert(e.toString(),t,r,n)}update(e,t,r,n){this.s.coreTopology.update(e.toString(),t,r,n)}remove(e,t,r,n){this.s.coreTopology.remove(e.toString(),t,r,n)}isConnected(e){e=e||{};e=i.translate(e);return this.s.coreTopology.isConnected(e)}isDestroyed(){return this.s.coreTopology.isDestroyed()}cursor(e,t,r){r=r||{};r=i.translate(r);r.disconnectHandler=this.s.store;r.topology=this;return this.s.coreTopology.cursor(e,t,r)}lastIsMaster(){return this.s.coreTopology.lastIsMaster()}selectServer(e,t,r){return this.s.coreTopology.selectServer(e,t,r)}unref(){return this.s.coreTopology.unref()}connections(){return this.s.coreTopology.connections()}close(e,t){this.s.sessions.forEach((e=>e.endSession()));if(this.s.sessionPool){this.s.sessionPool.endAllPooledSessions()}if(e===true){this.s.storeOptions.force=e;this.s.store.flush()}this.s.coreTopology.destroy({force:typeof e==="boolean"?e:false},t)}}Object.defineProperty(TopologyBase.prototype,"bson",{enumerable:true,get:function(){return this.s.coreTopology.s.bson}});Object.defineProperty(TopologyBase.prototype,"parserType",{enumerable:true,get:function(){return this.s.coreTopology.parserType}});Object.defineProperty(TopologyBase.prototype,"logicalSessionTimeoutMinutes",{enumerable:true,get:function(){return this.s.coreTopology.logicalSessionTimeoutMinutes}});Object.defineProperty(TopologyBase.prototype,"type",{enumerable:true,get:function(){return this.s.coreTopology.type}});t.yh=Store;t.ug=ServerCapabilities;t.oF=TopologyBase},8729:(e,t,r)=>{"use strict";const n=r(3994).ReadPreference;const o=r(7310);const s=r(3837).format;const i=r(3994).Logger;const a=r(7578);const A=r(7289);const c=r(3477);const l=r(3111).MongoParseError;e.exports=function(e,t,r){if(typeof t==="function")r=t,t={};t=t||{};let n;try{n=o.parse(e,true)}catch(e){return r(new Error("URL malformed, cannot be parsed"))}if(n.protocol!=="mongodb:"&&n.protocol!=="mongodb+srv:"){return r(new Error("Invalid schema, expected `mongodb` or `mongodb+srv`"))}if(n.protocol==="mongodb:"){return parseHandler(e,t,r)}if(n.hostname.split(".").length<3){return r(new Error("URI does not have hostname, domain name and tld"))}n.domainLength=n.hostname.split(".").length;const s=e.substring("mongodb+srv://".length).split("/")[0];if(s.match(",")){return r(new Error("Invalid URI, cannot contain multiple hostnames"))}if(n.port){return r(new Error("Ports not accepted with `mongodb+srv` URIs"))}let i=`_mongodb._tcp.${n.host}`;a.resolveSrv(i,(function(e,o){if(e)return r(e);if(o.length===0){return r(new Error("No addresses found at host"))}for(let e=0;e1){return r(new l("Multiple text records not allowed"))}n=n[0].join("");const e=c.parse(n);const t=Object.keys(e);if(Object.keys(t).some((e=>e.toLowerCase()==="loadbalanced"))){return r(new l("Load balancer mode requires driver version 4+"))}if(t.some((e=>e!=="authSource"&&e!=="replicaSet"))){return r(new l("Text record must only set `authSource` or `replicaSet`"))}if(t.length>0){u.push(n)}}if(u.length){A+=`?${u.join("&")}`}parseHandler(A,t,r)}))}))};function matchesParentDomain(e,t){let r=/^.*?\./;let n=`.${e.replace(r,"")}`;let o=`.${t.replace(r,"")}`;if(n.endsWith(o))return true;else return false}function parseHandler(e,t,r){let n,o;try{n=parseConnectionString(e,t)}catch(e){o=e}return o?r(o,null):r(null,n)}function parseConnectionString(e,t){let r="";let a="";let c="";let u="admin";let h=o.parse(e,true);if((h.hostname==null||h.hostname==="")&&e.indexOf(".sock")===-1){throw new Error("No hostname or hostnames provided in connection string")}if(h.port==="0"){throw new Error("Invalid port (zero) with hostname")}if(!isNaN(parseInt(h.port,10))&&parseInt(h.port,10)>65535){throw new Error("Invalid port (larger than 65535) with hostname")}if(h.path&&h.path.length>0&&h.path[0]!=="/"&&e.indexOf(".sock")===-1){throw new Error("Missing delimiting slash between hosts and options")}if(h.query){for(let e in h.query){if(e.indexOf("::")!==-1){throw new Error("Double colon in host identifier")}if(h.query[e]===""){throw new Error("Query parameter "+e+" is an incomplete value pair")}}}if(h.auth){let t=h.auth.split(":");if(e.indexOf(h.auth)!==-1&&t.length>2){throw new Error("Username with password containing an unescaped colon")}if(e.indexOf(h.auth)!==-1&&h.auth.indexOf("@")!==-1){throw new Error("Username containing an unescaped at-sign")}}let d=e.split("?").shift();let g=d.split(",");let p=[];for(let e=0;e1&&t.path.indexOf("::")===-1){throw new Error("Slash in host identifier")}else{throw new Error("Double colon in host identifier")}}}if(e.indexOf("?")!==-1){c=e.substr(e.indexOf("?")+1);r=e.substring("mongodb://".length,e.indexOf("?"))}else{r=e.substring("mongodb://".length)}if(r.indexOf("@")!==-1){a=r.split("@")[0];r=r.split("@")[1]}if(r.split("/").length>2){throw new Error("Unsupported host '"+r.split("?")[0]+"', hosts must be URL encoded and contain at most one unencoded slash")}if(r.indexOf(".sock")!==-1){if(r.indexOf(".sock/")!==-1){u=r.split(".sock/")[1];if(u.indexOf("/")!==-1){if(u.split("/").length===2&&u.split("/")[1].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}r=r.split("/",r.indexOf(".sock")+".sock".length)}}else if(r.indexOf("/")!==-1){if(r.split("/").length>2){if(r.split("/")[2].length===0){throw new Error("Illegal trailing backslash after database name")}throw new Error("More than 1 database name in URL")}u=r.split("/")[1];r=r.split("/")[0]}r=decodeURIComponent(r);let E={};let m=a||"";let C=m.split(":",2);let I=decodeURIComponent(C[0]);if(C[0]!==encodeURIComponent(I)){throw new Error("Username contains an illegal unescaped character")}C[0]=I;if(C[1]){let e=decodeURIComponent(C[1]);if(C[1]!==encodeURIComponent(e)){throw new Error("Password contains an illegal unescaped character")}C[1]=e}if(C.length===2)E.auth={user:C[0],password:C[1]};if(t&&t.auth!=null)E.auth=t.auth;let y;let B;let Q;let b;let w={socketOptions:{}};let S={read_preference_tags:[]};let v={socketOptions:{}};let R={socketOptions:{}};E.server_options=w;E.db_options=S;E.rs_options=v;E.mongos_options=R;if(e.match(/\.sock/)){let t=e.substring(e.indexOf("mongodb://")+"mongodb://".length,e.lastIndexOf(".sock")+".sock".length);if(t.indexOf("@")!==-1)t=t.split("@")[1];t=decodeURIComponent(t);Q=[{domain_socket:t}]}else{y=r;let e={};Q=y.split(",").map((function(t){let r,n,o;if(o=/\[([^\]]+)\](?::(.+))?/.exec(t)){r=o[1];n=parseInt(o[2],10)||27017}else{let e=t.split(":",2);r=e[0]||"localhost";n=e[1]!=null?parseInt(e[1],10):27017;if(r.indexOf("?")!==-1)r=r.split(/\?/)[0]}if(e[r+"_"+n])return null;e[r+"_"+n]=1;return{host:r,port:n}})).filter((function(e){return e!=null}))}E.dbName=u||"admin";B=(c||"").split(/[&;]/);if(B.some((e=>e.toLowerCase()==="loadbalanced"))){throw new l("Load balancer mode requires driver version 4+")}B.forEach((function(e){if(!e)return;var t=e.split("="),r=t[0],o=t[1];switch(r){case"slaveOk":case"slave_ok":w.slave_ok=o==="true";S.slaveOk=o==="true";break;case"maxPoolSize":case"poolSize":w.poolSize=parseInt(o,10);v.poolSize=parseInt(o,10);break;case"appname":E.appname=decodeURIComponent(o);break;case"autoReconnect":case"auto_reconnect":w.auto_reconnect=o==="true";break;case"ssl":if(o==="prefer"){w.ssl=o;v.ssl=o;R.ssl=o;break}w.ssl=o==="true";v.ssl=o==="true";R.ssl=o==="true";break;case"sslValidate":w.sslValidate=o==="true";v.sslValidate=o==="true";R.sslValidate=o==="true";break;case"replicaSet":case"rs_name":v.rs_name=o;break;case"reconnectWait":v.reconnectWait=parseInt(o,10);break;case"retries":v.retries=parseInt(o,10);break;case"readSecondary":case"read_secondary":v.read_secondary=o==="true";break;case"fsync":S.fsync=o==="true";break;case"journal":S.j=o==="true";break;case"safe":S.safe=o==="true";break;case"nativeParser":case"native_parser":S.native_parser=o==="true";break;case"readConcernLevel":S.readConcern=new A(o);break;case"connectTimeoutMS":w.socketOptions.connectTimeoutMS=parseInt(o,10);v.socketOptions.connectTimeoutMS=parseInt(o,10);R.socketOptions.connectTimeoutMS=parseInt(o,10);break;case"socketTimeoutMS":w.socketOptions.socketTimeoutMS=parseInt(o,10);v.socketOptions.socketTimeoutMS=parseInt(o,10);R.socketOptions.socketTimeoutMS=parseInt(o,10);break;case"w":S.w=parseInt(o,10);if(isNaN(S.w))S.w=o;break;case"authSource":S.authSource=o;break;case"gssapiServiceName":S.gssapiServiceName=o;break;case"authMechanism":if(o==="GSSAPI"){if(E.auth==null){let e=decodeURIComponent(m);if(e.indexOf("@")===-1)throw new Error("GSSAPI requires a provided principal");E.auth={user:e,password:null}}else{E.auth.user=decodeURIComponent(E.auth.user)}}else if(o==="MONGODB-X509"){E.auth={user:decodeURIComponent(m)}}if(o!=="GSSAPI"&&o!=="MONGODB-X509"&&o!=="MONGODB-CR"&&o!=="DEFAULT"&&o!=="SCRAM-SHA-1"&&o!=="SCRAM-SHA-256"&&o!=="PLAIN")throw new Error("Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism");S.authMechanism=o;break;case"authMechanismProperties":{let e=o.split(",");let t={};e.forEach((function(e){let r=e.split(":");t[r[0]]=r[1]}));S.authMechanismProperties=t;if(typeof t.SERVICE_NAME==="string")S.gssapiServiceName=t.SERVICE_NAME;if(typeof t.SERVICE_REALM==="string")S.gssapiServiceRealm=t.SERVICE_REALM;if(typeof t.CANONICALIZE_HOST_NAME==="string")S.gssapiCanonicalizeHostName=t.CANONICALIZE_HOST_NAME==="true"?true:false}break;case"wtimeoutMS":S.wtimeout=parseInt(o,10);break;case"readPreference":if(!n.isValid(o))throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");S.readPreference=o;break;case"maxStalenessSeconds":S.maxStalenessSeconds=parseInt(o,10);break;case"readPreferenceTags":{o=decodeURIComponent(o);let e={};if(o==null||o===""){S.read_preference_tags.push(e);break}let t=o.split(/,/);for(let r=0;r9){throw new Error("zlibCompressionLevel must be an integer between -1 and 9")}b.zlibCompressionLevel=e;w.compression=b}break;case"retryWrites":S.retryWrites=o==="true";break;case"minSize":S.minSize=parseInt(o,10);break;default:{let e=i("URL Parser");e.warn(`${r} is not supported as a connection string option`)}break}}));if(S.read_preference_tags.length===0){S.read_preference_tags=null}if((S.w===-1||S.w===0)&&(S.journal===true||S.fsync===true||S.safe===true))throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync");if(!S.readPreference){S.readPreference="primary"}S=Object.assign(S,t);E.servers=Q;return E}},1371:(e,t,r)=>{"use strict";const n=r(3111).MongoError;const o=r(2481);var shallowClone=function(e){var t={};for(var r in e)t[r]=e[r];return t};var getSingleProperty=function(e,t,r){Object.defineProperty(e,t,{enumerable:true,get:function(){return r}})};var s=t.formatSortValue=function(e){var t=(""+e).toLowerCase();switch(t){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)']]")}};var i=t.formattedOrderClause=function(e){var t=new Map;if(e==null)return null;if(Array.isArray(e)){if(e.length===0){return null}for(var r=0;r{if(e==null){throw new TypeError("This method requires a valid topology instance")}if(!Array.isArray(r)){throw new TypeError("This method requires an array of arguments to apply")}o=o||{};const s=e.s.promiseLibrary;let i=r[r.length-1];let a,A,c;if(!o.skipSessions&&e.hasSessionSupport()){A=r[r.length-2];if(A==null||A.session==null){c=Symbol();a=e.startSession({owner:c});const t=r.length-2;r[t]=Object.assign({},r[t],{session:a})}else if(A.session&&A.session.hasEnded){throw new n("Use of expired sessions is not permitted")}}const makeExecuteCallback=(e,t)=>function executeCallback(r,n){if(a&&a.owner===c&&!o.returnsCursor){a.endSession((()=>{delete A.session;if(r)return t(r);e(n)}))}else{if(r)return t(r);e(n)}};if(typeof i==="function"){i=r.pop();const e=makeExecuteCallback((e=>i(null,e)),(e=>i(e,null)));r.push(e);try{return t.apply(null,r)}catch(t){e(t);throw t}}if(r[r.length-1]!=null){throw new TypeError("final argument to `executeLegacyOperation` must be a callback")}return new s((function(e,n){const o=makeExecuteCallback(e,n);r[r.length-1]=o;try{return t.apply(null,r)}catch(e){o(e)}}))};function applyRetryableWrites(e,t){if(t&&t.s.options.retryWrites){e.retryWrites=true}return e}function applyWriteConcern(e,t,r){r=r||{};const n=t.db;const s=t.collection;if(r.session&&r.session.inTransaction()){if(e.writeConcern){delete e.writeConcern}return e}const i=o.fromOptions(r);if(i){return Object.assign(e,{writeConcern:i})}if(s&&s.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},s.writeConcern)})}if(n&&n.writeConcern){return Object.assign(e,{writeConcern:Object.assign({},n.writeConcern)})}return e}function isPromiseLike(e){return e&&typeof e.then==="function"}function decorateWithCollation(e,t,r){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(r.collation&&typeof r.collation==="object"){if(s&&s.commandsTakeCollation){e.collation=r.collation}else{throw new n(`Current topology does not support collation`)}}}function decorateWithReadConcern(e,t,r){if(r&&r.session&&r.session.inTransaction()){return}let n=Object.assign({},e.readConcern||{});if(t.s.readConcern){Object.assign(n,t.s.readConcern)}if(Object.keys(n).length>0){Object.assign(e,{readConcern:n})}}function decorateWithExplain(e,t){if(e.explain){return e}return{explain:e,verbosity:t.verbosity}}const u=+process.version.split(".")[0].substring(1);const emitProcessWarning=e=>u<=6?process.emitWarning(e,"DeprecationWarning",g):process.emitWarning(e,{type:"DeprecationWarning",code:g});const emitConsoleWarning=e=>console.error(e);const h=process.emitWarning?emitProcessWarning:emitConsoleWarning;function defaultMsgHandler(e,t){return`${e} option [${t}] is deprecated and will be removed in a later version.`}function deprecateOptions(e,t){if(process.noDeprecation===true){return t}const r=e.msgHandler?e.msgHandler:defaultMsgHandler;const n=new Set;function deprecated(){const o=arguments[e.optionsIndex];if(!c(o)||Object.keys(o).length===0){return t.apply(this,arguments)}e.deprecatedOptions.forEach((t=>{if(Object.prototype.hasOwnProperty.call(o,t)&&!n.has(t)){n.add(t);const o=r(e.name,t);h(o);if(this&&this.getLogger){const e=this.getLogger();if(e){e.warn(o)}}}}));return t.apply(this,arguments)}Object.setPrototypeOf(deprecated,t);if(t.prototype){deprecated.prototype=t.prototype}return deprecated}const d={};try{r(1749);d.ASYNC_ITERATOR=true}catch(e){d.ASYNC_ITERATOR=false}class MongoDBNamespace{constructor(e,t){this.db=e;this.collection=t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new MongoDBNamespace(this.db,e)}static fromString(e){if(!e){throw new Error(`Cannot parse namespace from "${e}"`)}const t=e.indexOf(".");return new MongoDBNamespace(e.substring(0,t),e.substring(t+1))}}function*makeCounter(e){let t=e||0;while(true){const e=t;t+=1;yield e}}function maybePromise(e,t,r){const n=e&&e.s&&e.s.promiseLibrary||Promise;let o;if(typeof t!=="function"){o=new n(((e,r)=>{t=(t,n)=>{if(t)return r(t);e(n)}}))}r((function(e,r){if(e!=null){try{t(e)}catch(e){return process.nextTick((()=>{throw e}))}return}t(e,r)}));return o}function now(){const e=process.hrtime();return Math.floor(e[0]*1e3+e[1]/1e6)}function calculateDurationInMs(e){if(typeof e!=="number"){throw TypeError("numeric value required to calculate duration")}const t=now()-e;return t<0?0:t}function makeInterruptableAsyncInterval(e,t){let r;let n;let o;let s=false;t=t||{};const i=t.interval||1e3;const a=t.minInterval||500;const A=typeof t.immediate==="boolean"?t.immediate:false;const c=typeof t.clock==="function"?t.clock:now;function wake(){const e=c();const t=e-o;const r=e-n;const s=i-r;o=e;if(ta){reschedule(a)}if(s<0){executeAndReschedule()}}function stop(){s=true;if(r){clearTimeout(r);r=null}n=0;o=0}function reschedule(e){if(s)return;clearTimeout(r);r=setTimeout(executeAndReschedule,e||i)}function executeAndReschedule(){o=0;n=c();e((e=>{if(e)throw e;reschedule(i)}))}if(A){executeAndReschedule()}else{n=c();reschedule()}return{wake:wake,stop:stop}}function hasAtomicOperators(e){if(Array.isArray(e)){return e.reduce(((e,t)=>e||hasAtomicOperators(t)),null)}return Object.keys(typeof e.toBSON!=="function"?e:e.toBSON()).map((e=>e[0])).indexOf("$")>=0}const g="MONGODB DRIVER";function emitWarning(e){if(process.emitWarning){return u<=6?process.emitWarning(e,undefined,g):process.emitWarning(e,{code:g})}else{return console.error(`[${g}] Warning:`,e)}}const p=new Set;function emitWarningOnce(e){if(!p.has(e)){p.add(e);return emitWarning(e)}}function isSuperset(e,t){e=Array.isArray(e)?new Set(e):e;t=Array.isArray(t)?new Set(t):t;for(const r of t){if(!e.has(r)){return false}}return true}function isRecord(e,t){const r=Object.prototype.toString;const n=Object.prototype.hasOwnProperty;const isObject=e=>r.call(e)==="[object Object]";if(!isObject(e)){return false}const o=e.constructor;if(o&&o.prototype){if(!isObject(o.prototype)){return false}if(!n.call(o.prototype,"isPrototypeOf")){return false}}if(t){const r=Object.keys(e);return isSuperset(r,t)}return true}function deepCopy(e){if(e==null){return e}else if(Array.isArray(e)){return e.map((e=>deepCopy(e)))}else if(isRecord(e)){const t={};for(const r in e){t[r]=deepCopy(e[r])}return t}const t=e.constructor;if(t){switch(t.name.toLowerCase()){case"date":return new t(Number(e));case"map":return new Map(e);case"set":return new Set(e);case"buffer":return Buffer.from(e)}}return e}function parsePackageVersion(e){const t=e.version.split(".").map((e=>Number.parseInt(e,10)));return{major:t[0],minor:t[1],patch:t[2]}}e.exports={filterOptions:filterOptions,mergeOptions:mergeOptions,translateOptions:translateOptions,shallowClone:shallowClone,getSingleProperty:getSingleProperty,checkCollectionName:a,toError:toError,formattedOrderClause:i,parseIndexOptions:parseIndexOptions,normalizeHintField:A,handleCallback:handleCallback,decorateCommand:decorateCommand,isObject:c,debugOptions:debugOptions,MAX_JS_INT:Number.MAX_SAFE_INTEGER+1,conditionallyMergeWriteConcern:conditionallyMergeWriteConcern,executeLegacyOperation:executeLegacyOperation,applyRetryableWrites:applyRetryableWrites,applyWriteConcern:applyWriteConcern,isPromiseLike:isPromiseLike,decorateWithCollation:decorateWithCollation,decorateWithReadConcern:decorateWithReadConcern,decorateWithExplain:decorateWithExplain,deprecateOptions:deprecateOptions,SUPPORTS:d,MongoDBNamespace:MongoDBNamespace,emitDeprecationWarning:h,makeCounter:makeCounter,maybePromise:maybePromise,now:now,calculateDurationInMs:calculateDurationInMs,makeInterruptableAsyncInterval:makeInterruptableAsyncInterval,hasAtomicOperators:hasAtomicOperators,MONGODB_WARNING_CODE:g,emitWarning:emitWarning,emitWarningOnce:emitWarningOnce,deepCopy:deepCopy,parsePackageVersion:parsePackageVersion}},2481:(e,t,r)=>{"use strict";const n=new Set(["w","wtimeout","j","journal","fsync"]);let o;class WriteConcern{constructor(e,t,r,n){if(e!=null){this.w=e}if(t!=null){this.wtimeout=t}if(r!=null){this.j=r}if(n!=null){this.fsync=n}}static fromOptions(e){if(e==null||e.writeConcern==null&&e.w==null&&e.wtimeout==null&&e.j==null&&e.journal==null&&e.fsync==null){return}if(e.writeConcern){if(typeof e.writeConcern==="string"){return new WriteConcern(e.writeConcern)}if(!Object.keys(e.writeConcern).some((e=>n.has(e)))){return}return new WriteConcern(e.writeConcern.w,e.writeConcern.wtimeout,e.writeConcern.j||e.writeConcern.journal,e.writeConcern.fsync)}if(!o)o=r(1371);o.emitWarningOnce(`Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.`);return new WriteConcern(e.w,e.wtimeout,e.j||e.journal,e.fsync)}}e.exports=WriteConcern},900:e=>{var t=1e3;var r=t*60;var n=r*60;var o=n*24;var s=o*7;var i=o*365.25;e.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0){return parse(e)}else if(r==="number"&&isFinite(e)){return t.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a){return}var A=parseFloat(a[1]);var c=(a[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return A*i;case"weeks":case"week":case"w":return A*s;case"days":case"day":case"d":return A*o;case"hours":case"hour":case"hrs":case"hr":case"h":return A*n;case"minutes":case"minute":case"mins":case"min":case"m":return A*r;case"seconds":case"second":case"secs":case"sec":case"s":return A*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return undefined}}function fmtShort(e){var s=Math.abs(e);if(s>=o){return Math.round(e/o)+"d"}if(s>=n){return Math.round(e/n)+"h"}if(s>=r){return Math.round(e/r)+"m"}if(s>=t){return Math.round(e/t)+"s"}return e+"ms"}function fmtLong(e){var s=Math.abs(e);if(s>=o){return plural(e,s,o,"day")}if(s>=n){return plural(e,s,n,"hour")}if(s>=r){return plural(e,s,r,"minute")}if(s>=t){return plural(e,s,t,"second")}return e+" ms"}function plural(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}},1156:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.findSync=t.find=t.findAsync=void 0;const n=r(4351);const o=r(1017);const s=r(7147);const i=r(8237);const a=i("new-find-package-json:main");function findAsync(e,t,r){return n.__asyncGenerator(this,arguments,(function*findAsync_1(){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const s=!!r?r:"package.json";const i=!!t||o.isAbsolute(t)?t:process.cwd();let A=o.resolve(i,e);let c=false;while(A){if(A===o.parse(A).root){c=true}const e=o.resolve(A,s);a(`findSync: testing path "${e}"`);const t=yield n.__await(statPathAsync(e));if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield yield n.__await(e);a(`findSync: after yield`)}if(c){break}A=o.resolve(A,"..")}}))}t.findAsync=findAsync;t.find=findAsync;function*findSync(e,t,r){a(`findSync: called with "${e}" and "${t}" and "${r}"`);t=!!t?t:"";const n=!!r?r:"package.json";const s=!!t||o.isAbsolute(t)?t:process.cwd();let i=o.resolve(s,e);let A=false;while(i){if(i===o.parse(i).root){A=true}const e=o.resolve(i,n);a(`findSync: testing path "${e}"`);const t=statPathSync(e);if(!!t&&t.isFile()){a(`findSync: path exists and is file "${e}"`);yield e;a(`findSync: after yield`)}if(A){break}i=o.resolve(i,"..")}}t.findSync=findSync;function statPathSync(e){try{return s.statSync(e)}catch(e){if(e.code==="ENOENT"){return undefined}throw e}}function statPathAsync(e){return n.__awaiter(this,void 0,void 0,(function*(){return s.promises.stat(e).catch((e=>{if(e.code==="ENOENT"){return undefined}throw e}))}))}},1223:(e,t,r)=>{var n=r(2940);e.exports=n(once);e.exports.strict=n(onceStrict);once.proto=once((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:true});Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:true})}));function once(e){var f=function(){if(f.called)return f.value;f.called=true;return f.value=e.apply(this,arguments)};f.called=false;return f}function onceStrict(e){var f=function(){if(f.called)throw new Error(f.onceError);f.called=true;return f.value=e.apply(this,arguments)};var t=e.name||"Function wrapped with `once`";f.onceError=t+" shouldn't be called more than once";f.called=false;return f}},9341:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __assign=this&&this.__assign||function(){__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{"use strict";const n=r(9341);e.exports=function(){return n.makeOptionalRequire.apply(n,arguments)};e.exports.tryRequire=n.tryRequire;e.exports.tryResolve=n.tryResolve;e.exports["try"]=n.tryRequire;e.exports.resolve=n.tryResolve;e.exports.makeOptionalRequire=n.makeOptionalRequire;e.exports.optionalRequire=n.optionalRequire;e.exports.optionalRequireCwd=n.optionalRequireCwd;e.exports.optionalRequireTop=n.optionalRequireTop;let o;Object.defineProperty(e.exports,"log",{set(e){o=e;n.setDefaultLog(e)},get(){return o}})},6978:(e,t,r)=>{"use strict";const n=r(7147);const{promisify:o}=r(3837);const s=o(n.access);e.exports=async e=>{try{await s(e);return true}catch(e){return false}};e.exports.sync=e=>{try{n.accessSync(e);return true}catch(e){return false}}},8714:e=>{"use strict";function posix(e){return e.charAt(0)==="/"}function win32(e){var t=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var r=t.exec(e);var n=r[1]||"";var o=Boolean(n&&n.charAt(1)!==":");return Boolean(r[2]||o)}e.exports=process.platform==="win32"?win32:posix;e.exports.posix=posix;e.exports.win32=win32},4833:e=>{e.exports=Pend;function Pend(){this.pending=0;this.max=Infinity;this.listeners=[];this.waiting=[];this.error=null}Pend.prototype.go=function(e){if(this.pending0&&e.pending{"use strict";const n=r(1017);const o=r(1812);const pkgDir=async e=>{const t=await o("package.json",{cwd:e});return t&&n.dirname(t)};e.exports=pkgDir;e.exports["default"]=pkgDir;e.exports.sync=e=>{const t=o.sync("package.json",{cwd:e});return t&&n.dirname(t)}},1812:(e,t,r)=>{"use strict";const n=r(1017);const o=r(5937);const s=r(6978);const i=Symbol("findUp.stop");e.exports=async(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=async t=>{if(typeof e!=="function"){return o(a,t)}const r=await e(t.cwd);if(typeof r==="string"){return o([r],t)}return r};while(true){const e=await runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.sync=(e,t={})=>{let r=n.resolve(t.cwd||"");const{root:s}=n.parse(r);const a=[].concat(e);const runMatcher=t=>{if(typeof e!=="function"){return o.sync(a,t)}const r=e(t.cwd);if(typeof r==="string"){return o.sync([r],t)}return r};while(true){const e=runMatcher({...t,cwd:r});if(e===i){return}if(e){return n.resolve(r,e)}if(r===s){return}r=n.dirname(r)}};e.exports.exists=s;e.exports.sync.exists=s.sync;e.exports.stop=i},5937:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const{promisify:s}=r(3837);const i=r(6249);const a=s(o.stat);const A=s(o.lstat);const c={directory:"isDirectory",file:"isFile"};function checkType({type:e}){if(e in c){return}throw new Error(`Invalid type specified: ${e}`)}const matchType=(e,t)=>e===undefined||t[c[e]]();e.exports=async(e,t)=>{t={cwd:process.cwd(),type:"file",allowSymlinks:true,...t};checkType(t);const r=t.allowSymlinks?a:A;return i(e,(async e=>{try{const o=await r(n.resolve(t.cwd,e));return matchType(t.type,o)}catch(e){return false}}),t)};e.exports.sync=(e,t)=>{t={cwd:process.cwd(),allowSymlinks:true,type:"file",...t};checkType(t);const r=t.allowSymlinks?o.statSync:o.lstatSync;for(const o of e){try{const e=r(n.resolve(t.cwd,o));if(matchType(t.type,e)){return o}}catch(e){}}}},4752:(e,t,r)=>{"use strict";const n=r(7471);const pLimit=e=>{if(!((Number.isInteger(e)||e===Infinity)&&e>0)){return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"))}const t=[];let r=0;const next=()=>{r--;if(t.length>0){t.shift()()}};const run=(e,t,...o)=>{r++;const s=n(e,...o);t(s);s.then(next,next)};const enqueue=(n,o,...s)=>{if(rnew Promise((r=>enqueue(e,r,...t)));Object.defineProperties(generator,{activeCount:{get:()=>r},pendingCount:{get:()=>t.length},clearQueue:{value:()=>{t.length=0}}});return generator};e.exports=pLimit;e.exports["default"]=pLimit},6249:(e,t,r)=>{"use strict";const n=r(4752);class EndError extends Error{constructor(e){super();this.value=e}}const testElement=async(e,t)=>t(await e);const finder=async e=>{const t=await Promise.all(e);if(t[1]===true){throw new EndError(t[0])}return false};const pLocate=async(e,t,r)=>{r={concurrency:Infinity,preserveOrder:true,...r};const o=n(r.concurrency);const s=[...e].map((e=>[e,o(testElement,e,t)]));const i=n(r.preserveOrder?1:Infinity);try{await Promise.all(s.map((e=>i(finder,e))))}catch(e){if(e instanceof EndError){return e.value}throw e}};e.exports=pLocate;e.exports["default"]=pLocate},7471:e=>{"use strict";const pTry=(e,...t)=>new Promise((r=>{r(e(...t))}));e.exports=pTry;e.exports["default"]=pTry},7214:e=>{"use strict";const t={};function createErrorType(e,r,n){if(!n){n=Error}function getMessage(e,t,n){if(typeof r==="string"){return r}else{return r(e,t,n)}}class NodeError extends n{constructor(e,t,r){super(getMessage(e,t,r))}}NodeError.prototype.name=n.name;NodeError.prototype.code=e;t[e]=NodeError}function oneOf(e,t){if(Array.isArray(e)){const r=e.length;e=e.map((e=>String(e)));if(r>2){return`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]}else if(r===2){return`one of ${t} ${e[0]} or ${e[1]}`}else{return`of ${t} ${e[0]}`}}else{return`of ${t} ${String(e)}`}}function startsWith(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function endsWith(e,t,r){if(r===undefined||r>e.length){r=e.length}return e.substring(r-t.length,r)===t}function includes(e,t,r){if(typeof r!=="number"){r=0}if(r+t.length>e.length){return false}else{return e.indexOf(t,r)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(e,t,r){let n;if(typeof t==="string"&&startsWith(t,"not ")){n="must not be";t=t.replace(/^not /,"")}else{n="must be"}let o;if(endsWith(e," argument")){o=`The ${e} ${n} ${oneOf(t,"type")}`}else{const r=includes(e,".")?"property":"argument";o=`The "${e}" ${r} ${n} ${oneOf(t,"type")}`}o+=`. Received type ${typeof r}`;return o}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");e.exports.q=t},1359:(e,t,r)=>{"use strict";var n=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=r(1433);var s=r(6993);r(4124)(Duplex,o);{var i=n(s.prototype);for(var a=0;a{"use strict";e.exports=PassThrough;var n=r(4415);r(4124)(PassThrough,n);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);n.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},1433:(e,t,r)=>{"use strict";e.exports=Readable;var n;Readable.ReadableState=ReadableState;var o=r(2361).EventEmitter;var s=function EElistenerCount(e,t){return e.listeners(t).length};var i=r(2387);var a=r(4300).Buffer;var A=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return a.from(e)}function _isUint8Array(e){return a.isBuffer(e)||e instanceof A}var c=r(3837);var l;if(c&&c.debuglog){l=c.debuglog("stream")}else{l=function debug(){}}var u=r(2746);var h=r(7049);var d=r(9948),g=d.getHighWaterMark;var p=r(7214).q,E=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,C=p.ERR_METHOD_NOT_IMPLEMENTED,I=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;var y;var B;var Q;r(4124)(Readable,i);var b=h.errorOrDestroy;var w=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(Array.isArray(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.readableObjectMode;this.highWaterMark=g(this,e,"readableHighWaterMark",o);this.buffer=new u;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.paused=true;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(4841).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){n=n||r(1359);if(!(this instanceof Readable))return new Readable(e);var t=this instanceof n;this._readableState=new ReadableState(e,this,t);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}i.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{enumerable:false,get:function get(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function set(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=h.destroy;Readable.prototype._undestroy=h.undestroy;Readable.prototype._destroy=function(e,t){t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var n;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=a.from(e,t);t=""}n=true}}else{n=true}return readableAddChunk(this,e,t,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,n,o){l("readableAddChunk",t);var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var i;if(!o)i=chunkInvalid(s,t);if(i){b(e,i)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==a.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(s.endEmitted)b(e,new I);else addChunk(e,s,t,true)}else if(s.ended){b(e,new m)}else if(s.destroyed){return false}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!n){s.reading=false;maybeReadMore(e,s)}}return!s.ended&&(s.length=S){e=S}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){l("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended)){l("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;l("need readable",n);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=t.length<=t.highWaterMark;e=0}else{t.length-=e;t.awaitDrain=0}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){l("onEofChunk");if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;if(t.sync){emitReadable(e)}else{t.needReadable=false;if(!t.emittedReadable){t.emittedReadable=true;emitReadable_(e)}}}function emitReadable(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable);t.needReadable=false;if(!t.emittedReadable){l("emitReadable",t.flowing);t.emittedReadable=true;process.nextTick(emitReadable_,e)}}function emitReadable_(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended);if(!t.destroyed&&(t.length||t.ended)){e.emit("readable");t.emittedReadable=false}t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark;flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;process.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){while(!t.reading&&!t.ended&&(t.length1&&indexOf(n.pipes,e)!==-1)&&!A){l("false write response, pause",n.awaitDrain);n.awaitDrain++}r.pause()}}function onerror(t){l("onerror",t);unpipe();e.removeListener("error",onerror);if(s(e,"error")===0)b(e,t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){l("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){l("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!n.flowing){l("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function pipeOnDrainFunctionResult(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&s(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var n=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s0;if(n.flowing!==false)this.resume()}else if(e==="readable"){if(!n.endEmitted&&!n.readableListening){n.readableListening=n.needReadable=true;n.flowing=false;n.emittedReadable=false;l("on readable",n.length,n.reading);if(n.length){emitReadable(this)}else if(!n.reading){process.nextTick(nReadingNextTick,this)}}}return r};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);if(e==="readable"){process.nextTick(updateReadableListening,this)}return r};Readable.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);if(e==="readable"||e===undefined){process.nextTick(updateReadableListening,this)}return t};function updateReadableListening(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0;if(t.resumeScheduled&&!t.paused){t.flowing=true}else if(e.listenerCount("data")>0){e.resume()}}function nReadingNextTick(e){l("readable nexttick read 0");e.read(0)}Readable.prototype.resume=function(){var e=this._readableState;if(!e.flowing){l("resume");e.flowing=!e.readableListening;resume(this,e)}e.paused=false;return this};function resume(e,t){if(!t.resumeScheduled){t.resumeScheduled=true;process.nextTick(resume_,e,t)}}function resume_(e,t){l("resume",t.reading);if(!t.reading){e.read(0)}t.resumeScheduled=false;e.emit("resume");flow(e);if(t.flowing&&!t.reading)e.read(0)}Readable.prototype.pause=function(){l("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){l("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(e){var t=e._readableState;l("flow",t.flowing);while(t.flowing&&e.read()!==null){}}Readable.prototype.wrap=function(e){var t=this;var r=this._readableState;var n=false;e.on("end",(function(){l("wrapped end");if(r.decoder&&!r.ended){var e=r.decoder.end();if(e&&e.length)t.push(e)}t.push(null)}));e.on("data",(function(o){l("wrapped data");if(r.decoder)o=r.decoder.write(o);if(r.objectMode&&(o===null||o===undefined))return;else if(!r.objectMode&&(!o||!o.length))return;var s=t.push(o);if(!s){n=true;e.pause()}}));for(var o in e){if(this[o]===undefined&&typeof e[o]==="function"){this[o]=function methodWrap(t){return function methodWrapReturnFunction(){return e[t].apply(e,arguments)}}(o)}}for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.first();else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=t.buffer.consume(e,t.decoder)}return r}function endReadable(e){var t=e._readableState;l("endReadable",t.endEmitted);if(!t.endEmitted){t.ended=true;process.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){l("endReadableNT",e.endEmitted,e.length);if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end");if(e.autoDestroy){var r=t._writableState;if(!r||r.autoDestroy&&r.finished){t.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(e,t){if(Q===undefined){Q=r(9082)}return Q(Readable,e,t)}}function indexOf(e,t){for(var r=0,n=e.length;r{"use strict";e.exports=Transform;var n=r(7214).q,o=n.ERR_METHOD_NOT_IMPLEMENTED,s=n.ERR_MULTIPLE_CALLBACK,i=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=n.ERR_TRANSFORM_WITH_LENGTH_0;var A=r(1359);r(4124)(Transform,A);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(n===null){return this.emit("error",new s)}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);n(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var n;Writable.WritableState=WritableState;var o={deprecate:r(5278)};var s=r(2387);var i=r(4300).Buffer;var a=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return i.from(e)}function _isUint8Array(e){return i.isBuffer(e)||e instanceof a}var A=r(7049);var c=r(9948),l=c.getHighWaterMark;var u=r(7214).q,h=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,g=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,E=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,C=u.ERR_STREAM_WRITE_AFTER_END,I=u.ERR_UNKNOWN_ENCODING;var y=A.errorOrDestroy;r(4124)(Writable,s);function nop(){}function WritableState(e,t,o){n=n||r(1359);e=e||{};if(typeof o!=="boolean")o=t instanceof n;this.objectMode=!!e.objectMode;if(o)this.objectMode=this.objectMode||!!e.writableObjectMode;this.highWaterMark=l(this,e,"writableHighWaterMark",o);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var s=e.decodeStrings===false;this.decodeStrings=!s;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.emitClose=e.emitClose!==false;this.autoDestroy=!!e.autoDestroy;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:o.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var B;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){B=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(e){if(B.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{B=function realHasInstance(e){return e instanceof this}}function Writable(e){n=n||r(1359);var t=this instanceof n;if(!t&&!B.call(Writable,this))return new Writable(e);this._writableState=new WritableState(e,this,t);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}s.call(this)}Writable.prototype.pipe=function(){y(this,new p)};function writeAfterEnd(e,t){var r=new C;y(e,r);process.nextTick(t,r)}function validChunk(e,t,r,n){var o;if(r===null){o=new m}else if(typeof r!=="string"&&!t.objectMode){o=new h("chunk",["string","Buffer"],r)}if(o){y(e,o);process.nextTick(n,o);return false}return true}Writable.prototype.write=function(e,t,r){var n=this._writableState;var o=false;var s=!n.objectMode&&_isUint8Array(e);if(s&&!i.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=n.defaultEncoding;if(typeof r!=="function")r=nop;if(n.ending)writeAfterEnd(this,r);else if(s||validChunk(this,n,e,r)){n.pendingcb++;o=writeOrBuffer(this,n,s,e,t,r)}return o};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new I(e);this._writableState.defaultEncoding=e;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=i.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,n,o,s){if(!r){var i=decodeChunk(t,n,o);if(n!==i){r=true;o="buffer";n=i}}var a=t.objectMode?1:n.length;t.length+=a;var A=t.length{"use strict";var n;function _defineProperty(e,t,r){if(t in e){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true})}else{e[t]=r}return e}var o=r(6080);var s=Symbol("lastResolve");var i=Symbol("lastReject");var a=Symbol("error");var A=Symbol("ended");var c=Symbol("lastPromise");var l=Symbol("handlePromise");var u=Symbol("stream");function createIterResult(e,t){return{value:e,done:t}}function readAndResolve(e){var t=e[s];if(t!==null){var r=e[u].read();if(r!==null){e[c]=null;e[s]=null;e[i]=null;t(createIterResult(r,false))}}}function onReadable(e){process.nextTick(readAndResolve,e)}function wrapForNext(e,t){return function(r,n){e.then((function(){if(t[A]){r(createIterResult(undefined,true));return}t[l](r,n)}),n)}}var h=Object.getPrototypeOf((function(){}));var d=Object.setPrototypeOf((n={get stream(){return this[u]},next:function next(){var e=this;var t=this[a];if(t!==null){return Promise.reject(t)}if(this[A]){return Promise.resolve(createIterResult(undefined,true))}if(this[u].destroyed){return new Promise((function(t,r){process.nextTick((function(){if(e[a]){r(e[a])}else{t(createIterResult(undefined,true))}}))}))}var r=this[c];var n;if(r){n=new Promise(wrapForNext(r,this))}else{var o=this[u].read();if(o!==null){return Promise.resolve(createIterResult(o,false))}n=new Promise(this[l])}this[c]=n;return n}},_defineProperty(n,Symbol.asyncIterator,(function(){return this})),_defineProperty(n,"return",(function _return(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){if(e){r(e);return}t(createIterResult(undefined,true))}))}))})),n),h);var g=function createReadableStreamAsyncIterator(e){var t;var r=Object.create(d,(t={},_defineProperty(t,u,{value:e,writable:true}),_defineProperty(t,s,{value:null,writable:true}),_defineProperty(t,i,{value:null,writable:true}),_defineProperty(t,a,{value:null,writable:true}),_defineProperty(t,A,{value:e._readableState.endEmitted,writable:true}),_defineProperty(t,l,{value:function value(e,t){var n=r[u].read();if(n){r[c]=null;r[s]=null;r[i]=null;e(createIterResult(n,false))}else{r[s]=e;r[i]=t}},writable:true}),t));r[c]=null;o(e,(function(e){if(e&&e.code!=="ERR_STREAM_PREMATURE_CLOSE"){var t=r[i];if(t!==null){r[c]=null;r[s]=null;r[i]=null;t(e)}r[a]=e;return}var n=r[s];if(n!==null){r[c]=null;r[s]=null;r[i]=null;n(createIterResult(undefined,true))}r[A]=true}));e.on("readable",onReadable.bind(null,r));return r};e.exports=g},2746:(e,t,r)=>{"use strict";function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t0)this.tail.next=t;else this.head=t;this.tail=t;++this.length}},{key:"unshift",value:function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r}},{key:"concat",value:function concat(e){if(this.length===0)return o.alloc(0);var t=o.allocUnsafe(e>>>0);var r=this.head;var n=0;while(r){copyBuffer(r.data,t,n);n+=r.data.length;r=r.next}return t}},{key:"consume",value:function consume(e,t){var r;if(eo.length?o.length:e;if(s===o.length)n+=o;else n+=o.slice(0,e);e-=s;if(e===0){if(s===o.length){++r;if(t.next)this.head=t.next;else this.head=this.tail=null}else{this.head=t;t.data=o.slice(s)}break}++r}this.length-=r;return n}},{key:"_getBuffer",value:function _getBuffer(e){var t=o.allocUnsafe(e);var r=this.head;var n=1;r.data.copy(t);e-=r.data.length;while(r=r.next){var s=r.data;var i=e>s.length?s.length:e;s.copy(t,t.length-e,0,i);e-=i;if(e===0){if(i===s.length){++n;if(r.next)this.head=r.next;else this.head=this.tail=null}else{this.head=r;r.data=s.slice(i)}break}++n}this.length-=n;return t}},{key:a,value:function value(e,t){return i(this,_objectSpread({},t,{depth:0,customInspect:false}))}}]);return BufferList}()},7049:e=>{"use strict";function destroy(e,t){var r=this;var n=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(n||o){if(t){t(e)}else if(e){if(!this._writableState){process.nextTick(emitErrorNT,this,e)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,e)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){if(!r._writableState){process.nextTick(emitErrorAndCloseNT,r,e)}else if(!r._writableState.errorEmitted){r._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,r,e)}else{process.nextTick(emitCloseNT,r)}}else if(t){process.nextTick(emitCloseNT,r);t(e)}else{process.nextTick(emitCloseNT,r)}}));return this}function emitErrorAndCloseNT(e,t){emitErrorNT(e,t);emitCloseNT(e)}function emitCloseNT(e){if(e._writableState&&!e._writableState.emitClose)return;if(e._readableState&&!e._readableState.emitClose)return;e.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}function errorOrDestroy(e,t){var r=e._readableState;var n=e._writableState;if(r&&r.autoDestroy||n&&n.autoDestroy)e.destroy(t);else e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},6080:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_STREAM_PREMATURE_CLOSE;function once(e){var t=false;return function(){if(t)return;t=true;for(var r=arguments.length,n=new Array(r),o=0;o{"use strict";function asyncGeneratorStep(e,t,r,n,o,s,i){try{var a=e[s](i);var A=a.value}catch(e){r(e);return}if(a.done){t(A)}else{Promise.resolve(A).then(n,o)}}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var s=e.apply(t,r);function _next(e){asyncGeneratorStep(s,n,o,_next,_throw,"next",e)}function _throw(e){asyncGeneratorStep(s,n,o,_next,_throw,"throw",e)}_next(undefined)}))}}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);if(t)n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}));r.push.apply(r,n)}return r}function _objectSpread(e){for(var t=1;t{"use strict";var n;function once(e){var t=false;return function(){if(t)return;t=true;e.apply(void 0,arguments)}}var o=r(7214).q,s=o.ERR_MISSING_ARGS,i=o.ERR_STREAM_DESTROYED;function noop(e){if(e)throw e}function isRequest(e){return e.setHeader&&typeof e.abort==="function"}function destroyer(e,t,o,s){s=once(s);var a=false;e.on("close",(function(){a=true}));if(n===undefined)n=r(6080);n(e,{readable:t,writable:o},(function(e){if(e)return s(e);a=true;s()}));var A=false;return function(t){if(a)return;if(A)return;A=true;if(isRequest(e))return e.abort();if(typeof e.destroy==="function")return e.destroy();s(t||new i("pipe"))}}function call(e){e()}function pipe(e,t){return e.pipe(t)}function popCallback(e){if(!e.length)return noop;if(typeof e[e.length-1]!=="function")return noop;return e.pop()}function pipeline(){for(var e=arguments.length,t=new Array(e),r=0;r0;return destroyer(e,s,a,(function(e){if(!o)o=e;if(e)i.forEach(call);if(s)return;i.forEach(call);n(o)}))}));return t.reduce(pipe)}e.exports=pipeline},9948:(e,t,r)=>{"use strict";var n=r(7214).q.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function getHighWaterMark(e,t,r,o){var s=highWaterMarkFrom(t,o,r);if(s!=null){if(!(isFinite(s)&&Math.floor(s)===s)||s<0){var i=o?r:"highWaterMark";throw new n(i,s)}return Math.floor(s)}return e.objectMode?16:16*1024}e.exports={getHighWaterMark:getHighWaterMark}},2387:(e,t,r)=>{e.exports=r(2781)},1642:(e,t,r)=>{var n=r(2781);if(process.env.READABLE_STREAM==="disable"&&n){e.exports=n.Readable;Object.assign(e.exports,n);e.exports.Stream=n}else{t=e.exports=r(1433);t.Stream=n||t;t.Readable=t;t.Writable=r(6993);t.Duplex=r(1359);t.Transform=r(4415);t.PassThrough=r(1542);t.finished=r(6080);t.pipeline=r(6989)}},545:(module,__unused_webpack_exports,__nccwpck_require__)=>{"use strict";const Module=__nccwpck_require__(8188);const xrequire=eval("require");const createRequireFromPath=Module.createRequire||Module.createRequireFromPath||((e,t)=>{const r=new Module(e);r.filename=e;r.paths=Module._nodeModulePaths(t);function _require(e){return xrequire(resolve(e))}function resolve(e,t){return Module._resolveFilename(e,r,false,t)}_require.resolve=resolve;function paths(e){return Module._resolveLookupPaths(e,r,true)}resolve.paths=paths;_require.main=process.mainModule;_require.extensions=Module._extensions;_require.cache=Module._cache;return _require});module.exports=createRequireFromPath},2058:(e,t,r)=>{"use strict";const n=r(1017);const o=r(7147);const s=r(545);const i=new Map;function requireAt(e,t){const makeIt=(r,i)=>{let a=requireAt.cache&&requireAt.cache.get(r);if(!a){let t;try{t=o.statSync(r)}catch(e){throw new Error(`require-at: stat '${r}' failed: ${e.message}`)}if(!t||!t.isDirectory()){if(i)throw new Error(`require-at: not a directory: '${e}'`);return makeIt(n.dirname(r),true)}a=s(n.join(r,"._require-at_"),r);requireAt.cache&&requireAt.cache.set(r,a)}return t?a(t):a};return makeIt(n.resolve(e),false)}requireAt.cache=i;e.exports=requireAt},4959:(e,t,r)=>{const n=r(9491);const o=r(1017);const s=r(7147);let i=undefined;try{i=r(1957)}catch(e){}const a={nosort:true,silent:true};let A=0;const c=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&i===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||a};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof r,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let a=0;const next=e=>{s=s||e;if(--a===0)r(s)};const afterGlob=(e,n)=>{if(e)return r(e);a=n.length;if(a===0)return r();n.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&Arimraf_(e,t,CB)),A++)}if(r.code==="ENOENT")r=null}A=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!i.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,n)=>{if(!r)return afterGlob(null,[e]);i(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.lstat(e,((n,o)=>{if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&c)fixWinEPERM(e,t,n,r);if(o&&o.isDirectory())return rmdir(e,t,n,r);t.unlink(e,(n=>{if(n){if(n.code==="ENOENT")return r(null);if(n.code==="EPERM")return c?fixWinEPERM(e,t,n,r):rmdir(e,t,n,r);if(n.code==="EISDIR")return rmdir(e,t,n,r)}return r(n)}))}))};const fixWinEPERM=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.chmod(e,438,(n=>{if(n)o(n.code==="ENOENT"?null:r);else t.stat(e,((n,s)=>{if(n)o(n.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{n(e);n(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{n(e);n(t);n(typeof o==="function");t.rmdir(e,(n=>{if(n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM"))rmkids(e,t,o);else if(n&&n.code==="ENOTDIR")o(r);else o(n)}))};const rmkids=(e,t,r)=>{n(e);n(t);n(typeof r==="function");t.readdir(e,((n,s)=>{if(n)return r(n);let i=s.length;if(i===0)return t.rmdir(e,r);let a;s.forEach((n=>{rimraf(o.join(e,n),t,(n=>{if(a)return;if(n)return r(a=n);if(--i===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n(t,"rimraf: missing options");n.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!i.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(n){r=i.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{n(e);n(t);try{t.rmdirSync(e)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;if(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{n(e);n(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=c?100:1;let s=0;do{let n=true;try{const r=t.rmdirSync(e,t);n=false;return r}finally{if(++s{var n=r(4300);var o=n.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=o(e);if(t!==undefined){if(typeof r==="string"){n.fill(t,r)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},9178:(e,t,r)=>{"use strict";const{unassigned_code_points:n,commonly_mapped_to_nothing:o,non_ASCII_space_characters:s,prohibited_characters:i,bidirectional_r_al:a,bidirectional_l:A}=r(8916);e.exports=saslprep;const c=s;const l=o;const getCodePoint=e=>e.codePointAt(0);const first=e=>e[0];const last=e=>e[e.length-1];function toCodePoints(e){const t=[];const r=e.length;for(let n=0;n=55296&&o<=56319&&r>n+1){const r=e.charCodeAt(n+1);if(r>=56320&&r<=57343){t.push((o-55296)*1024+r-56320+65536);n+=1;continue}}t.push(o)}return t}function saslprep(e,t={}){if(typeof e!=="string"){throw new TypeError("Expected string.")}if(e.length===0){return""}const r=toCodePoints(e).map((e=>c.get(e)?32:e)).filter((e=>!l.get(e)));const o=String.fromCodePoint.apply(null,r).normalize("NFKC");const s=toCodePoints(o);const u=s.some((e=>i.get(e)));if(u){throw new Error("Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3")}if(t.allowUnassigned!==true){const e=s.some((e=>n.get(e)));if(e){throw new Error("Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5")}}const h=s.some((e=>a.get(e)));const d=s.some((e=>A.get(e)));if(h&&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 g=a.get(getCodePoint(first(o)));const p=a.get(getCodePoint(last(o)));if(h&&!(g&&p)){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}},8916:(e,t,r)=>{"use strict";const n=r(7147);const o=r(1017);const s=r(1453);const i=n.readFileSync(r.ab+"code-points.mem");let a=0;function read(){const e=i.readUInt32BE(a);a+=4;const t=i.slice(a,a+e);a+=e;return s({buffer:t})}const A=read();const c=read();const l=read();const u=read();const h=read();const d=read();e.exports={unassigned_code_points:A,commonly_mapped_to_nothing:c,non_ASCII_space_characters:l,prohibited_characters:u,bidirectional_r_al:h,bidirectional_l:d}},1532:(e,t,r)=>{const n=Symbol("SemVer ANY");class Comparator{static get ANY(){return n}constructor(e,t){t=o(t);if(e instanceof Comparator){if(e.loose===!!t.loose){return e}else{e=e.value}}e=e.trim().split(/\s+/).join(" ");A("comparator",e,t);this.options=t;this.loose=!!t.loose;this.parse(e);if(this.semver===n){this.value=""}else{this.value=this.operator+this.semver.version}A("comp",this)}parse(e){const t=this.options.loose?s[i.COMPARATORLOOSE]:s[i.COMPARATOR];const r=e.match(t);if(!r){throw new TypeError(`Invalid comparator: ${e}`)}this.operator=r[1]!==undefined?r[1]:"";if(this.operator==="="){this.operator=""}if(!r[2]){this.semver=n}else{this.semver=new c(r[2],this.options.loose)}}toString(){return this.value}test(e){A("Comparator.test",e,this.options.loose);if(this.semver===n||e===n){return true}if(typeof e==="string"){try{e=new c(e,this.options)}catch(e){return false}}return a(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Comparator)){throw new TypeError("a Comparator is required")}if(this.operator===""){if(this.value===""){return true}return new l(e.value,t).test(this.value)}else if(e.operator===""){if(e.value===""){return true}return new l(this.value,t).test(e.semver)}t=o(t);if(t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")){return false}if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))){return false}if(this.operator.startsWith(">")&&e.operator.startsWith(">")){return true}if(this.operator.startsWith("<")&&e.operator.startsWith("<")){return true}if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")){return true}if(a(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")){return true}if(a(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")){return true}return false}}e.exports=Comparator;const o=r(785);const{safeRe:s,t:i}=r(9523);const a=r(5098);const A=r(427);const c=r(8088);const l=r(9828)},9828:(e,t,r)=>{class Range{constructor(e,t){t=s(t);if(e instanceof Range){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{return new Range(e.raw,t)}}if(e instanceof i){this.raw=e.value;this.set=[[e]];this.format();return this}this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;this.raw=e.trim().split(/\s+/).join(" ");this.set=this.raw.split("||").map((e=>this.parseRange(e.trim()))).filter((e=>e.length));if(!this.set.length){throw new TypeError(`Invalid SemVer Range: ${this.raw}`)}if(this.set.length>1){const e=this.set[0];this.set=this.set.filter((e=>!isNullSet(e[0])));if(this.set.length===0){this.set=[e]}else if(this.set.length>1){for(const e of this.set){if(e.length===1&&isAny(e[0])){this.set=[e];break}}}}this.format()}format(){this.range=this.set.map((e=>e.join(" ").trim())).join("||").trim();return this.range}toString(){return this.range}parseRange(e){const t=(this.options.includePrerelease&&g)|(this.options.loose&&p);const r=t+":"+e;const n=o.get(r);if(n){return n}const s=this.options.loose;const A=s?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(A,hyphenReplace(this.options.includePrerelease));a("hyphen replace",e);e=e.replace(c[l.COMPARATORTRIM],u);a("comparator trim",e);e=e.replace(c[l.TILDETRIM],h);a("tilde trim",e);e=e.replace(c[l.CARETTRIM],d);a("caret trim",e);let E=e.split(" ").map((e=>parseComparator(e,this.options))).join(" ").split(/\s+/).map((e=>replaceGTE0(e,this.options)));if(s){E=E.filter((e=>{a("loose invalid filter",e,this.options);return!!e.match(c[l.COMPARATORLOOSE])}))}a("range list",E);const m=new Map;const C=E.map((e=>new i(e,this.options)));for(const e of C){if(isNullSet(e)){return[e]}m.set(e.value,e)}if(m.size>1&&m.has("")){m.delete("")}const I=[...m.values()];o.set(r,I);return I}intersects(e,t){if(!(e instanceof Range)){throw new TypeError("a Range is required")}return this.set.some((r=>isSatisfiable(r,t)&&e.set.some((e=>isSatisfiable(e,t)&&r.every((r=>e.every((e=>r.intersects(e,t)))))))))}test(e){if(!e){return false}if(typeof e==="string"){try{e=new A(e,this.options)}catch(e){return false}}for(let t=0;te.value==="<0.0.0-0";const isAny=e=>e.value==="";const isSatisfiable=(e,t)=>{let r=true;const n=e.slice();let o=n.pop();while(r&&n.length){r=n.every((e=>o.intersects(e,t)));o=n.pop()}return r};const parseComparator=(e,t)=>{a("comp",e,t);e=replaceCarets(e,t);a("caret",e);e=replaceTildes(e,t);a("tildes",e);e=replaceXRanges(e,t);a("xrange",e);e=replaceStars(e,t);a("stars",e);return e};const isX=e=>!e||e.toLowerCase()==="x"||e==="*";const replaceTildes=(e,t)=>e.trim().split(/\s+/).map((e=>replaceTilde(e,t))).join(" ");const replaceTilde=(e,t)=>{const r=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(r,((t,r,n,o,s)=>{a("tilde",e,t,r,n,o,s);let i;if(isX(r)){i=""}else if(isX(n)){i=`>=${r}.0.0 <${+r+1}.0.0-0`}else if(isX(o)){i=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`}else if(s){a("replaceTilde pr",s);i=`>=${r}.${n}.${o}-${s} <${r}.${+n+1}.0-0`}else{i=`>=${r}.${n}.${o} <${r}.${+n+1}.0-0`}a("tilde return",i);return i}))};const replaceCarets=(e,t)=>e.trim().split(/\s+/).map((e=>replaceCaret(e,t))).join(" ");const replaceCaret=(e,t)=>{a("caret",e,t);const r=t.loose?c[l.CARETLOOSE]:c[l.CARET];const n=t.includePrerelease?"-0":"";return e.replace(r,((t,r,o,s,i)=>{a("caret",e,t,r,o,s,i);let A;if(isX(r)){A=""}else if(isX(o)){A=`>=${r}.0.0${n} <${+r+1}.0.0-0`}else if(isX(s)){if(r==="0"){A=`>=${r}.${o}.0${n} <${r}.${+o+1}.0-0`}else{A=`>=${r}.${o}.0${n} <${+r+1}.0.0-0`}}else if(i){a("replaceCaret pr",i);if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}-${i} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}-${i} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s}-${i} <${+r+1}.0.0-0`}}else{a("no pr");if(r==="0"){if(o==="0"){A=`>=${r}.${o}.${s}${n} <${r}.${o}.${+s+1}-0`}else{A=`>=${r}.${o}.${s}${n} <${r}.${+o+1}.0-0`}}else{A=`>=${r}.${o}.${s} <${+r+1}.0.0-0`}}a("caret return",A);return A}))};const replaceXRanges=(e,t)=>{a("replaceXRanges",e,t);return e.split(/\s+/).map((e=>replaceXRange(e,t))).join(" ")};const replaceXRange=(e,t)=>{e=e.trim();const r=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(r,((r,n,o,s,i,A)=>{a("xRange",e,r,n,o,s,i,A);const c=isX(o);const l=c||isX(s);const u=l||isX(i);const h=u;if(n==="="&&h){n=""}A=t.includePrerelease?"-0":"";if(c){if(n===">"||n==="<"){r="<0.0.0-0"}else{r="*"}}else if(n&&h){if(l){s=0}i=0;if(n===">"){n=">=";if(l){o=+o+1;s=0;i=0}else{s=+s+1;i=0}}else if(n==="<="){n="<";if(l){o=+o+1}else{s=+s+1}}if(n==="<"){A="-0"}r=`${n+o}.${s}.${i}${A}`}else if(l){r=`>=${o}.0.0${A} <${+o+1}.0.0-0`}else if(u){r=`>=${o}.${s}.0${A} <${o}.${+s+1}.0-0`}a("xRange return",r);return r}))};const replaceStars=(e,t)=>{a("replaceStars",e,t);return e.trim().replace(c[l.STAR],"")};const replaceGTE0=(e,t)=>{a("replaceGTE0",e,t);return e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],"")};const hyphenReplace=e=>(t,r,n,o,s,i,a,A,c,l,u,h)=>{if(isX(n)){r=""}else if(isX(o)){r=`>=${n}.0.0${e?"-0":""}`}else if(isX(s)){r=`>=${n}.${o}.0${e?"-0":""}`}else if(i){r=`>=${r}`}else{r=`>=${r}${e?"-0":""}`}if(isX(c)){A=""}else if(isX(l)){A=`<${+c+1}.0.0-0`}else if(isX(u)){A=`<${c}.${+l+1}.0-0`}else if(h){A=`<=${c}.${l}.${u}-${h}`}else if(e){A=`<${c}.${l}.${+u+1}-0`}else{A=`<=${A}`}return`${r} ${A}`.trim()};const testSet=(e,t,r)=>{for(let r=0;r0){const n=e[r].semver;if(n.major===t.major&&n.minor===t.minor&&n.patch===t.patch){return true}}}return false}return true}},8088:(e,t,r)=>{const n=r(427);const{MAX_LENGTH:o,MAX_SAFE_INTEGER:s}=r(2293);const{safeRe:i,t:a}=r(9523);const A=r(785);const{compareIdentifiers:c}=r(2463);class SemVer{constructor(e,t){t=A(t);if(e instanceof SemVer){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease){return e}else{e=e.version}}else if(typeof e!=="string"){throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`)}if(e.length>o){throw new TypeError(`version is longer than ${o} characters`)}n("SemVer",e,t);this.options=t;this.loose=!!t.loose;this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?i[a.LOOSE]:i[a.FULL]);if(!r){throw new TypeError(`Invalid Version: ${e}`)}this.raw=e;this.major=+r[1];this.minor=+r[2];this.patch=+r[3];if(this.major>s||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>s||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>s||this.patch<0){throw new TypeError("Invalid patch version")}if(!r[4]){this.prerelease=[]}else{this.prerelease=r[4].split(".").map((e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t=0){if(typeof this.prerelease[n]==="number"){this.prerelease[n]++;n=-2}}if(n===-1){if(t===this.prerelease.join(".")&&r===false){throw new Error("invalid increment argument: identifier already exists")}this.prerelease.push(e)}}if(t){let n=[t,e];if(r===false){n=[t]}if(c(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1])){this.prerelease=n}}else{this.prerelease=n}}break}default:throw new Error(`invalid increment argument: ${e}`)}this.raw=this.format();if(this.build.length){this.raw+=`+${this.build.join(".")}`}return this}}e.exports=SemVer},8848:(e,t,r)=>{const n=r(5925);const clean=(e,t)=>{const r=n(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};e.exports=clean},5098:(e,t,r)=>{const n=r(1898);const o=r(6017);const s=r(4123);const i=r(5522);const a=r(194);const A=r(7520);const cmp=(e,t,r,c)=>{switch(t){case"===":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e===r;case"!==":if(typeof e==="object"){e=e.version}if(typeof r==="object"){r=r.version}return e!==r;case"":case"=":case"==":return n(e,r,c);case"!=":return o(e,r,c);case">":return s(e,r,c);case">=":return i(e,r,c);case"<":return a(e,r,c);case"<=":return A(e,r,c);default:throw new TypeError(`Invalid operator: ${t}`)}};e.exports=cmp},3466:(e,t,r)=>{const n=r(8088);const o=r(5925);const{safeRe:s,t:i}=r(9523);const coerce=(e,t)=>{if(e instanceof n){return e}if(typeof e==="number"){e=String(e)}if(typeof e!=="string"){return null}t=t||{};let r=null;if(!t.rtl){r=e.match(t.includePrerelease?s[i.COERCEFULL]:s[i.COERCE])}else{const n=t.includePrerelease?s[i.COERCERTLFULL]:s[i.COERCERTL];let o;while((o=n.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||o.index+o[0].length!==r.index+r[0].length){r=o}n.lastIndex=o.index+o[1].length+o[2].length}n.lastIndex=-1}if(r===null){return null}const a=r[2];const A=r[3]||"0";const c=r[4]||"0";const l=t.includePrerelease&&r[5]?`-${r[5]}`:"";const u=t.includePrerelease&&r[6]?`+${r[6]}`:"";return o(`${a}.${A}.${c}${l}${u}`,t)};e.exports=coerce},2156:(e,t,r)=>{const n=r(8088);const compareBuild=(e,t,r)=>{const o=new n(e,r);const s=new n(t,r);return o.compare(s)||o.compareBuild(s)};e.exports=compareBuild},2804:(e,t,r)=>{const n=r(4309);const compareLoose=(e,t)=>n(e,t,true);e.exports=compareLoose},4309:(e,t,r)=>{const n=r(8088);const compare=(e,t,r)=>new n(e,r).compare(new n(t,r));e.exports=compare},4297:(e,t,r)=>{const n=r(5925);const diff=(e,t)=>{const r=n(e,null,true);const o=n(t,null,true);const s=r.compare(o);if(s===0){return null}const i=s>0;const a=i?r:o;const A=i?o:r;const c=!!a.prerelease.length;const l=!!A.prerelease.length;if(l&&!c){if(!A.patch&&!A.minor){return"major"}if(a.patch){return"patch"}if(a.minor){return"minor"}return"major"}const u=c?"pre":"";if(r.major!==o.major){return u+"major"}if(r.minor!==o.minor){return u+"minor"}if(r.patch!==o.patch){return u+"patch"}return"prerelease"};e.exports=diff},1898:(e,t,r)=>{const n=r(4309);const eq=(e,t,r)=>n(e,t,r)===0;e.exports=eq},4123:(e,t,r)=>{const n=r(4309);const gt=(e,t,r)=>n(e,t,r)>0;e.exports=gt},5522:(e,t,r)=>{const n=r(4309);const gte=(e,t,r)=>n(e,t,r)>=0;e.exports=gte},929:(e,t,r)=>{const n=r(8088);const inc=(e,t,r,o,s)=>{if(typeof r==="string"){s=o;o=r;r=undefined}try{return new n(e instanceof n?e.version:e,r).inc(t,o,s).version}catch(e){return null}};e.exports=inc},194:(e,t,r)=>{const n=r(4309);const lt=(e,t,r)=>n(e,t,r)<0;e.exports=lt},7520:(e,t,r)=>{const n=r(4309);const lte=(e,t,r)=>n(e,t,r)<=0;e.exports=lte},6688:(e,t,r)=>{const n=r(8088);const major=(e,t)=>new n(e,t).major;e.exports=major},8447:(e,t,r)=>{const n=r(8088);const minor=(e,t)=>new n(e,t).minor;e.exports=minor},6017:(e,t,r)=>{const n=r(4309);const neq=(e,t,r)=>n(e,t,r)!==0;e.exports=neq},5925:(e,t,r)=>{const n=r(8088);const parse=(e,t,r=false)=>{if(e instanceof n){return e}try{return new n(e,t)}catch(e){if(!r){return null}throw e}};e.exports=parse},2866:(e,t,r)=>{const n=r(8088);const patch=(e,t)=>new n(e,t).patch;e.exports=patch},4016:(e,t,r)=>{const n=r(5925);const prerelease=(e,t)=>{const r=n(e,t);return r&&r.prerelease.length?r.prerelease:null};e.exports=prerelease},6417:(e,t,r)=>{const n=r(4309);const rcompare=(e,t,r)=>n(t,e,r);e.exports=rcompare},8701:(e,t,r)=>{const n=r(2156);const rsort=(e,t)=>e.sort(((e,r)=>n(r,e,t)));e.exports=rsort},6055:(e,t,r)=>{const n=r(9828);const satisfies=(e,t,r)=>{try{t=new n(t,r)}catch(e){return false}return t.test(e)};e.exports=satisfies},1426:(e,t,r)=>{const n=r(2156);const sort=(e,t)=>e.sort(((e,r)=>n(e,r,t)));e.exports=sort},9601:(e,t,r)=>{const n=r(5925);const valid=(e,t)=>{const r=n(e,t);return r?r.version:null};e.exports=valid},1383:(e,t,r)=>{const n=r(9523);const o=r(2293);const s=r(8088);const i=r(2463);const a=r(5925);const A=r(9601);const c=r(8848);const l=r(929);const u=r(4297);const h=r(6688);const d=r(8447);const g=r(2866);const p=r(4016);const E=r(4309);const m=r(6417);const C=r(2804);const I=r(2156);const y=r(1426);const B=r(8701);const Q=r(4123);const b=r(194);const w=r(1898);const S=r(6017);const v=r(5522);const R=r(7520);const k=r(5098);const D=r(3466);const N=r(1532);const T=r(9828);const O=r(6055);const _=r(2706);const M=r(579);const L=r(832);const F=r(4179);const U=r(2098);const P=r(420);const G=r(9380);const Y=r(3323);const V=r(7008);const W=r(5297);const J=r(7863);e.exports={parse:a,valid:A,clean:c,inc:l,diff:u,major:h,minor:d,patch:g,prerelease:p,compare:E,rcompare:m,compareLoose:C,compareBuild:I,sort:y,rsort:B,gt:Q,lt:b,eq:w,neq:S,gte:v,lte:R,cmp:k,coerce:D,Comparator:N,Range:T,satisfies:O,toComparators:_,maxSatisfying:M,minSatisfying:L,minVersion:F,validRange:U,outside:P,gtr:G,ltr:Y,intersects:V,simplifyRange:W,subset:J,SemVer:s,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:o.SEMVER_SPEC_VERSION,RELEASE_TYPES:o.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}},2293:e=>{const t="2.0.0";const r=256;const n=Number.MAX_SAFE_INTEGER||9007199254740991;const o=16;const s=r-6;const i=["major","premajor","minor","preminor","patch","prepatch","prerelease"];e.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:i,SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},427:e=>{const t=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},2463:e=>{const t=/^[0-9]+$/;const compareIdentifiers=(e,r)=>{const n=t.test(e);const o=t.test(r);if(n&&o){e=+e;r=+r}return e===r?0:n&&!o?-1:o&&!n?1:ecompareIdentifiers(t,e);e.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},5339:e=>{class LRUCache{constructor(){this.max=1e3;this.map=new Map}get(e){const t=this.map.get(e);if(t===undefined){return undefined}else{this.map.delete(e);this.map.set(e,t);return t}}delete(e){return this.map.delete(e)}set(e,t){const r=this.delete(e);if(!r&&t!==undefined){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}e.exports=LRUCache},785:e=>{const t=Object.freeze({loose:true});const r=Object.freeze({});const parseOptions=e=>{if(!e){return r}if(typeof e!=="object"){return t}return e};e.exports=parseOptions},9523:(e,t,r)=>{const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_LENGTH:s}=r(2293);const i=r(427);t=e.exports={};const a=t.re=[];const A=t.safeRe=[];const c=t.src=[];const l=t.t={};let u=0;const h="[a-zA-Z0-9-]";const d=[["\\s",1],["\\d",s],[h,o]];const makeSafeRegex=e=>{for(const[t,r]of d){e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`)}return e};const createToken=(e,t,r)=>{const n=makeSafeRegex(t);const o=u++;i(e,o,t);l[e]=o;c[o]=t;a[o]=new RegExp(t,r?"g":undefined);A[o]=new RegExp(n,r?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","\\d+");createToken("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`);createToken("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})\\.`+`(${c[l.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.`+`(${c[l.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER",`${h}+`);createToken("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`);createToken("FULL",`^${c[l.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`);createToken("LOOSE",`^${c[l.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:\\.(${c[l.XRANGEIDENTIFIER]})`+`(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})`+`(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`);createToken("COERCEPLAIN",`${"(^|[^\\d])"+"(\\d{1,"}${n}})`+`(?:\\.(\\d{1,${n}}))?`+`(?:\\.(\\d{1,${n}}))?`);createToken("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`);createToken("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?`+`(?:$|[^\\d])`);createToken("COERCERTL",c[l.COERCE],true);createToken("COERCERTLFULL",c[l.COERCEFULL],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,true);t.tildeTrimReplace="$1~";createToken("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,true);t.caretTrimReplace="$1^";createToken("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,true);t.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${c[l.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},9380:(e,t,r)=>{const n=r(420);const gtr=(e,t,r)=>n(e,t,">",r);e.exports=gtr},7008:(e,t,r)=>{const n=r(9828);const intersects=(e,t,r)=>{e=new n(e,r);t=new n(t,r);return e.intersects(t,r)};e.exports=intersects},3323:(e,t,r)=>{const n=r(420);const ltr=(e,t,r)=>n(e,t,"<",r);e.exports=ltr},579:(e,t,r)=>{const n=r(8088);const o=r(9828);const maxSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===-1){s=e;i=new n(s,r)}}}));return s};e.exports=maxSatisfying},832:(e,t,r)=>{const n=r(8088);const o=r(9828);const minSatisfying=(e,t,r)=>{let s=null;let i=null;let a=null;try{a=new o(t,r)}catch(e){return null}e.forEach((e=>{if(a.test(e)){if(!s||i.compare(e)===1){s=e;i=new n(s,r)}}}));return s};e.exports=minSatisfying},4179:(e,t,r)=>{const n=r(8088);const o=r(9828);const s=r(4123);const minVersion=(e,t)=>{e=new o(e,t);let r=new n("0.0.0");if(e.test(r)){return r}r=new n("0.0.0-0");if(e.test(r)){return r}r=null;for(let t=0;t{const t=new n(e.semver.version);switch(e.operator){case">":if(t.prerelease.length===0){t.patch++}else{t.prerelease.push(0)}t.raw=t.format();case"":case">=":if(!i||s(t,i)){i=t}break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}));if(i&&(!r||s(r,i))){r=i}}if(r&&e.test(r)){return r}return null};e.exports=minVersion},420:(e,t,r)=>{const n=r(8088);const o=r(1532);const{ANY:s}=o;const i=r(9828);const a=r(6055);const A=r(4123);const c=r(194);const l=r(7520);const u=r(5522);const outside=(e,t,r,h)=>{e=new n(e,h);t=new i(t,h);let d,g,p,E,m;switch(r){case">":d=A;g=l;p=c;E=">";m=">=";break;case"<":d=c;g=u;p=A;E="<";m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(e,t,h)){return false}for(let r=0;r{if(e.semver===s){e=new o(">=0.0.0")}i=i||e;a=a||e;if(d(e.semver,i.semver,h)){i=e}else if(p(e.semver,a.semver,h)){a=e}}));if(i.operator===E||i.operator===m){return false}if((!a.operator||a.operator===E)&&g(e,a.semver)){return false}else if(a.operator===m&&p(e,a.semver)){return false}}return true};e.exports=outside},5297:(e,t,r)=>{const n=r(6055);const o=r(4309);e.exports=(e,t,r)=>{const s=[];let i=null;let a=null;const A=e.sort(((e,t)=>o(e,t,r)));for(const e of A){const o=n(e,t,r);if(o){a=e;if(!i){i=e}}else{if(a){s.push([i,a])}a=null;i=null}}if(i){s.push([i,null])}const c=[];for(const[e,t]of s){if(e===t){c.push(e)}else if(!t&&e===A[0]){c.push("*")}else if(!t){c.push(`>=${e}`)}else if(e===A[0]){c.push(`<=${t}`)}else{c.push(`${e} - ${t}`)}}const l=c.join(" || ");const u=typeof t.raw==="string"?t.raw:String(t);return l.length{const n=r(9828);const o=r(1532);const{ANY:s}=o;const i=r(6055);const a=r(4309);const subset=(e,t,r={})=>{if(e===t){return true}e=new n(e,r);t=new n(t,r);let o=false;e:for(const n of e.set){for(const e of t.set){const t=simpleSubset(n,e,r);o=o||t!==null;if(t){continue e}}if(o){return false}}return true};const A=[new o(">=0.0.0-0")];const c=[new o(">=0.0.0")];const simpleSubset=(e,t,r)=>{if(e===t){return true}if(e.length===1&&e[0].semver===s){if(t.length===1&&t[0].semver===s){return true}else if(r.includePrerelease){e=A}else{e=c}}if(t.length===1&&t[0].semver===s){if(r.includePrerelease){return true}else{t=c}}const n=new Set;let o,l;for(const t of e){if(t.operator===">"||t.operator===">="){o=higherGT(o,t,r)}else if(t.operator==="<"||t.operator==="<="){l=lowerLT(l,t,r)}else{n.add(t.semver)}}if(n.size>1){return null}let u;if(o&&l){u=a(o.semver,l.semver,r);if(u>0){return null}else if(u===0&&(o.operator!==">="||l.operator!=="<=")){return null}}for(const e of n){if(o&&!i(e,String(o),r)){return null}if(l&&!i(e,String(l),r)){return null}for(const n of t){if(!i(e,String(n),r)){return false}}return true}let h,d;let g,p;let E=l&&!r.includePrerelease&&l.semver.prerelease.length?l.semver:false;let m=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:false;if(E&&E.prerelease.length===1&&l.operator==="<"&&E.prerelease[0]===0){E=false}for(const e of t){p=p||e.operator===">"||e.operator===">=";g=g||e.operator==="<"||e.operator==="<=";if(o){if(m){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===m.major&&e.semver.minor===m.minor&&e.semver.patch===m.patch){m=false}}if(e.operator===">"||e.operator===">="){h=higherGT(o,e,r);if(h===e&&h!==o){return false}}else if(o.operator===">="&&!i(o.semver,String(e),r)){return false}}if(l){if(E){if(e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===E.major&&e.semver.minor===E.minor&&e.semver.patch===E.patch){E=false}}if(e.operator==="<"||e.operator==="<="){d=lowerLT(l,e,r);if(d===e&&d!==l){return false}}else if(l.operator==="<="&&!i(l.semver,String(e),r)){return false}}if(!e.operator&&(l||o)&&u!==0){return false}}if(o&&g&&!l&&u!==0){return false}if(l&&p&&!o&&u!==0){return false}if(m||E){return false}return true};const higherGT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e};const lowerLT=(e,t,r)=>{if(!e){return t}const n=a(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};e.exports=subset},2706:(e,t,r)=>{const n=r(9828);const toComparators=(e,t)=>new n(e,t).set.map((e=>e.map((e=>e.value)).join(" ").trim().split(" ")));e.exports=toComparators},2098:(e,t,r)=>{const n=r(9828);const validRange=(e,t)=>{try{return new n(e,t).range||"*"}catch(e){return null}};e.exports=validRange},1453:(e,t,r)=>{var n=r(1529);e.exports=Bitfield;function Bitfield(e){if(!(this instanceof Bitfield))return new Bitfield(e);if(!e)e={};if(Buffer.isBuffer(e))e={buffer:e};this.pageOffset=e.pageOffset||0;this.pageSize=e.pageSize||1024;this.pages=e.pages||n(this.pageSize);this.byteLength=this.pages.length*this.pageSize;this.length=8*this.byteLength;if(!powerOfTwo(this.pageSize))throw new Error("The page size should be a power of two");this._trackUpdates=!!e.trackUpdates;this._pageMask=this.pageSize-1;if(e.buffer){for(var t=0;t>t)};Bitfield.prototype.getByte=function(e){var t=e&this._pageMask;var r=(e-t)/this.pageSize;var n=this.pages.get(r,true);return n?n.buffer[t+this.pageOffset]:0};Bitfield.prototype.set=function(e,t){var r=e&7;var n=(e-r)/8;var o=this.getByte(n);return this.setByte(n,t?o|128>>r:o&(255^128>>r))};Bitfield.prototype.toBuffer=function(){var e=alloc(this.pages.length*this.pageSize);for(var t=0;t=this.byteLength){this.byteLength=e+1;this.length=this.byteLength*8}if(this._trackUpdates)this.pages.updated(o);return true};function alloc(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);t.fill(0);return t}function powerOfTwo(e){return!(e&e-1)}},4841:(e,t,r)=>{"use strict";var n=r(1867).Buffer;var o=n.isEncoding||function(e){e=""+e;switch(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 true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){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=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var n=t.length-1;if(n=0){if(o>0)e.lastNeed=o-1;return o}if(--n=0){if(o>0)e.lastNeed=o-2;return o}if(--n=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},9318:(e,t,r)=>{"use strict";const n=r(2037);const o=r(6224);const s=r(1621);const{env:i}=process;let a;if(s("no-color")||s("no-colors")||s("color=false")||s("color=never")){a=0}else if(s("color")||s("colors")||s("color=true")||s("color=always")){a=1}if("FORCE_COLOR"in i){if(i.FORCE_COLOR==="true"){a=1}else if(i.FORCE_COLOR==="false"){a=0}else{a=i.FORCE_COLOR.length===0?1:Math.min(parseInt(i.FORCE_COLOR,10),3)}}function translateLevel(e){if(e===0){return false}return{level:e,hasBasic:true,has256:e>=2,has16m:e>=3}}function supportsColor(e,t){if(a===0){return 0}if(s("color=16m")||s("color=full")||s("color=truecolor")){return 3}if(s("color=256")){return 2}if(e&&!t&&a===undefined){return 0}const r=a||0;if(i.TERM==="dumb"){return r}if(process.platform==="win32"){const e=n.release().split(".");if(Number(e[0])>=10&&Number(e[2])>=10586){return Number(e[2])>=14931?3:2}return 1}if("CI"in i){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in i))||i.CI_NAME==="codeship"){return 1}return r}if("TEAMCITY_VERSION"in i){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(i.TEAMCITY_VERSION)?1:0}if(i.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in i){const e=parseInt((i.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(i.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(i.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(i.TERM)){return 1}if("COLORTERM"in i){return 1}return r}function getSupportLevel(e){const t=supportsColor(e,e&&e.isTTY);return translateLevel(t)}e.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(true,o.isatty(1))),stderr:translateLevel(supportsColor(true,o.isatty(2)))}},7882:(e,t,r)=>{var n=r(3837);var o=r(336);var s=r(8860);var i=r(1642).Writable;var a=r(1642).PassThrough;var noop=function(){};var overflow=function(e){e&=511;return e&&512-e};var emptyStream=function(e,t){var r=new Source(e,t);r.end();return r};var mixinPax=function(e,t){if(t.path)e.name=t.path;if(t.linkpath)e.linkname=t.linkpath;if(t.size)e.size=parseInt(t.size,10);e.pax=t;return e};var Source=function(e,t){this._parent=e;this.offset=t;a.call(this,{autoDestroy:false})};n.inherits(Source,a);Source.prototype.destroy=function(e){this._parent.destroy(e)};var Extract=function(e){if(!(this instanceof Extract))return new Extract(e);i.call(this,e);e=e||{};this._offset=0;this._buffer=o();this._missing=0;this._partial=false;this._onparse=noop;this._header=null;this._stream=null;this._overflow=null;this._cb=null;this._locked=false;this._destroyed=false;this._pax=null;this._paxGlobal=null;this._gnuLongPath=null;this._gnuLongLinkPath=null;var t=this;var r=t._buffer;var oncontinue=function(){t._continue()};var onunlock=function(e){t._locked=false;if(e)return t.destroy(e);if(!t._stream)oncontinue()};var onstreamend=function(){t._stream=null;var e=overflow(t._header.size);if(e)t._parse(e,ondrain);else t._parse(512,onheader);if(!t._locked)oncontinue()};var ondrain=function(){t._buffer.consume(overflow(t._header.size));t._parse(512,onheader);oncontinue()};var onpaxglobalheader=function(){var e=t._header.size;t._paxGlobal=s.decodePax(r.slice(0,e));r.consume(e);onstreamend()};var onpaxheader=function(){var e=t._header.size;t._pax=s.decodePax(r.slice(0,e));if(t._paxGlobal)t._pax=Object.assign({},t._paxGlobal,t._pax);r.consume(e);onstreamend()};var ongnulongpath=function(){var n=t._header.size;this._gnuLongPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var ongnulonglinkpath=function(){var n=t._header.size;this._gnuLongLinkPath=s.decodeLongPath(r.slice(0,n),e.filenameEncoding);r.consume(n);onstreamend()};var onheader=function(){var n=t._offset;var o;try{o=t._header=s.decode(r.slice(0,512),e.filenameEncoding,e.allowUnknownFormat)}catch(e){t.emit("error",e)}r.consume(512);if(!o){t._parse(512,onheader);oncontinue();return}if(o.type==="gnu-long-path"){t._parse(o.size,ongnulongpath);oncontinue();return}if(o.type==="gnu-long-link-path"){t._parse(o.size,ongnulonglinkpath);oncontinue();return}if(o.type==="pax-global-header"){t._parse(o.size,onpaxglobalheader);oncontinue();return}if(o.type==="pax-header"){t._parse(o.size,onpaxheader);oncontinue();return}if(t._gnuLongPath){o.name=t._gnuLongPath;t._gnuLongPath=null}if(t._gnuLongLinkPath){o.linkname=t._gnuLongLinkPath;t._gnuLongLinkPath=null}if(t._pax){t._header=o=mixinPax(o,t._pax);t._pax=null}t._locked=true;if(!o.size||o.type==="directory"){t._parse(512,onheader);t.emit("entry",o,emptyStream(t,n),onunlock);return}t._stream=new Source(t,n);t.emit("entry",o,t._stream,onunlock);t._parse(o.size,onstreamend);oncontinue()};this._onheader=onheader;this._parse(512,onheader)};n.inherits(Extract,i);Extract.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream)this._stream.emit("close")};Extract.prototype._parse=function(e,t){if(this._destroyed)return;this._offset+=e;this._missing=e;if(t===this._onheader)this._partial=false;this._onparse=t};Extract.prototype._continue=function(){if(this._destroyed)return;var e=this._cb;this._cb=noop;if(this._overflow)this._write(this._overflow,undefined,e);else e()};Extract.prototype._write=function(e,t,r){if(this._destroyed)return;var n=this._stream;var o=this._buffer;var s=this._missing;if(e.length)this._partial=true;if(e.lengths){i=e.slice(s);e=e.slice(0,s)}if(n)n.end(e);else o.append(e);this._overflow=i;this._onparse()};Extract.prototype._final=function(e){if(this._partial)return this.destroy(new Error("Unexpected end of data"));e()};e.exports=Extract},8860:(e,t)=>{var r=Buffer.alloc;var n="0000000000000000000";var o="7777777777777777777";var s="0".charCodeAt(0);var i=Buffer.from("ustar\0","binary");var a=Buffer.from("00","binary");var A=Buffer.from("ustar ","binary");var c=Buffer.from(" \0","binary");var l=parseInt("7777",8);var u=257;var h=263;var clamp=function(e,t,r){if(typeof e!=="number")return r;e=~~e;if(e>=t)return t;if(e>=0)return e;e+=t;if(e>=0)return e;return 0};var toType=function(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null};var toTypeflag=function(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0};var indexOf=function(e,t,r,n){for(;rt)return o.slice(0,t)+" ";else return n.slice(0,t-e.length)+e+" "};function parse256(e){var t;if(e[0]===128)t=true;else if(e[0]===255)t=false;else return null;var r=[];for(var n=e.length-1;n>0;n--){var o=e[n];if(t)r.push(o);else r.push(255-o)}var s=0;var i=r.length;for(n=0;n=Math.pow(10,r))r++;return t+r+e};t.decodeLongPath=function(e,t){return decodeStr(e,0,e.length,t)};t.encodePax=function(e){var t="";if(e.name)t+=addLength(" path="+e.name+"\n");if(e.linkname)t+=addLength(" linkpath="+e.linkname+"\n");var r=e.pax;if(r){for(var n in r){t+=addLength(" "+n+"="+r[n]+"\n")}}return Buffer.from(t)};t.decodePax=function(e){var t={};while(e.length){var r=0;while(r100){var A=n.indexOf("/");if(A===-1)return null;o+=o?"/"+n.slice(0,A):n.slice(0,A);n=n.slice(A+1)}if(Buffer.byteLength(n)>100||Buffer.byteLength(o)>155)return null;if(e.linkname&&Buffer.byteLength(e.linkname)>100)return null;t.write(n);t.write(encodeOct(e.mode&l,6),100);t.write(encodeOct(e.uid,6),108);t.write(encodeOct(e.gid,6),116);t.write(encodeOct(e.size,11),124);t.write(encodeOct(e.mtime.getTime()/1e3|0,11),136);t[156]=s+toTypeflag(e.type);if(e.linkname)t.write(e.linkname,157);i.copy(t,u);a.copy(t,h);if(e.uname)t.write(e.uname,265);if(e.gname)t.write(e.gname,297);t.write(encodeOct(e.devmajor||0,6),329);t.write(encodeOct(e.devminor||0,6),337);if(o)t.write(o,345);t.write(encodeOct(cksum(t),6),148);return t};t.decode=function(e,t,r){var n=e[156]===0?0:e[156]-s;var o=decodeStr(e,0,100,t);var a=decodeOct(e,100,8);var l=decodeOct(e,108,8);var d=decodeOct(e,116,8);var g=decodeOct(e,124,12);var p=decodeOct(e,136,12);var E=toType(n);var m=e[157]===0?null:decodeStr(e,157,100,t);var C=decodeStr(e,265,32);var I=decodeStr(e,297,32);var y=decodeOct(e,329,8);var B=decodeOct(e,337,8);var Q=cksum(e);if(Q===8*32)return null;if(Q!==decodeOct(e,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(i.compare(e,u,u+6)===0){if(e[345])o=decodeStr(e,345,155,t)+"/"+o}else if(A.compare(e,u,u+6)===0&&c.compare(e,h,h+2)===0){}else{if(!r){throw new Error("Invalid tar header: unknown format.")}}if(n===0&&o&&o[o.length-1]==="/")n=5;return{name:o,mode:a,uid:l,gid:d,size:g,mtime:new Date(1e3*p),type:E,linkname:m,uname:C,gname:I,devmajor:y,devminor:B}}},2283:(e,t,r)=>{t.extract=r(7882);t.pack=r(4930)},4930:(e,t,r)=>{var n=r(3186);var o=r(1205);var s=r(4124);var i=Buffer.alloc;var a=r(1642).Readable;var A=r(1642).Writable;var c=r(1576).StringDecoder;var l=r(8860);var u=parseInt("755",8);var h=parseInt("644",8);var d=i(1024);var noop=function(){};var overflow=function(e,t){t&=511;if(t)e.push(d.slice(0,512-t))};function modeToType(e){switch(e&n.S_IFMT){case n.S_IFBLK:return"block-device";case n.S_IFCHR:return"character-device";case n.S_IFDIR:return"directory";case n.S_IFIFO:return"fifo";case n.S_IFLNK:return"symlink"}return"file"}var Sink=function(e){A.call(this);this.written=0;this._to=e;this._destroyed=false};s(Sink,A);Sink.prototype._write=function(e,t,r){this.written+=e.length;if(this._to.push(e))return r();this._to._drain=r};Sink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var LinkSink=function(){A.call(this);this.linkname="";this._decoder=new c("utf-8");this._destroyed=false};s(LinkSink,A);LinkSink.prototype._write=function(e,t,r){this.linkname+=this._decoder.write(e);r()};LinkSink.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Void=function(){A.call(this);this._destroyed=false};s(Void,A);Void.prototype._write=function(e,t,r){r(new Error("No body allowed for this entry"))};Void.prototype.destroy=function(){if(this._destroyed)return;this._destroyed=true;this.emit("close")};var Pack=function(e){if(!(this instanceof Pack))return new Pack(e);a.call(this,e);this._drain=noop;this._finalized=false;this._finalizing=false;this._destroyed=false;this._stream=null};s(Pack,a);Pack.prototype.entry=function(e,t,r){if(this._stream)throw new Error("already piping an entry");if(this._finalized||this._destroyed)return;if(typeof t==="function"){r=t;t=null}if(!r)r=noop;var n=this;if(!e.size||e.type==="symlink")e.size=0;if(!e.type)e.type=modeToType(e.mode);if(!e.mode)e.mode=e.type==="directory"?u:h;if(!e.uid)e.uid=0;if(!e.gid)e.gid=0;if(!e.mtime)e.mtime=new Date;if(typeof t==="string")t=Buffer.from(t);if(Buffer.isBuffer(t)){e.size=t.length;this._encode(e);var s=this.push(t);overflow(n,e.size);if(s)process.nextTick(r);else this._drain=r;return new Void}if(e.type==="symlink"&&!e.linkname){var i=new LinkSink;o(i,(function(t){if(t){n.destroy();return r(t)}e.linkname=i.linkname;n._encode(e);r()}));return i}this._encode(e);if(e.type!=="file"&&e.type!=="contiguous-file"){process.nextTick(r);return new Void}var a=new Sink(this);this._stream=a;o(a,(function(t){n._stream=null;if(t){n.destroy();return r(t)}if(a.written!==e.size){n.destroy();return r(new Error("size mismatch"))}overflow(n,e.size);if(n._finalizing)n.finalize();r()}));return a};Pack.prototype.finalize=function(){if(this._stream){this._finalizing=true;return}if(this._finalized)return;this._finalized=true;this.push(d);this.push(null)};Pack.prototype.destroy=function(e){if(this._destroyed)return;this._destroyed=true;if(e)this.emit("error",e);this.emit("close");if(this._stream&&this._stream.destroy)this._stream.destroy()};Pack.prototype._encode=function(e){if(!e.pax){var t=l.encode(e);if(t){this.push(t);return}}this._encodePax(e)};Pack.prototype._encodePax=function(e){var t=l.encodePax({name:e.name,linkname:e.linkname,pax:e.pax});var r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.length,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(l.encode(r));this.push(t);overflow(this,t.length);r.size=e.size;r.type=e.type;this.push(l.encode(r))};Pack.prototype._read=function(e){var t=this._drain;this._drain=noop;t()};e.exports=Pack},8517:(e,t,r)=>{ /*! * Tmp * From dfead6b7d795b6f7c90867c22c36c9a3c69401a6 Mon Sep 17 00:00:00 2001 From: Lucas Parreira Date: Wed, 1 Oct 2025 13:33:47 -0600 Subject: [PATCH 5/5] Removing test branch. --- .github/workflows/publish.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 24f1583..4ec7867 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -1,7 +1,7 @@ name: publish on: push: - branches: [master, main, enginfs-545300/move-actions] + branches: [master, main] permissions: contents: write jobs: